Python: Tips to support both Python 2 and Python3

  1. Use ‘.decode’ and ‘str’ methods
    #Converts base64-encoded bytes to string
    import base64
    data = str(
        base64.b64decode(commit_msg_hook).decode("utf-8")
    )
    
  2. Use ‘stat’ module to change file’s permission
    import os
    import stat
    os.chmod('./run.sh', stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
    
  3. Don’t use ‘urllib2’ module. It’s only available for Python 2
    Use ‘requests’ module


		
Advertisements