pysys.utils.pycompat

Compatibility utilities to allow PySys to support both Python 2 and 3.

Enum

pysys.utils.pycompat.Enum = <enum 'Enum'>[source]

In Python 2 an enumeration can be simulated by just assigning constant values with a unique value (perhaps a string) as statics in a simple object, e.g.

class MyEnum(Enum):
        OPTION1 = 'MyEnum.OPTION1'
        OPTION2 = 'MyEnum.OPTION2'

val = getattr(MyEnum, 'option1'.upper(), None)
if val is None: raise Exception('Bad option: "%s"'%...)

isstring

pysys.utils.pycompat.isstring(s)[source]

Returns True if the specified object is a python string. On Python 2 this could be a unicode character string or a byte str, on python 3 this must be a character str.

quotestring

pysys.utils.pycompat.quotestring(s)[source]

Adds double quotation marks around the specified character or byte string, and additional escaping only if needed to make the meaning clear, but trying to avoid double-slashes unless actually needed since it makes paths harder to read

If a byte string is provided and this is Python 3+ then the repr() representation is used instead.

openfile

pysys.utils.pycompat.openfile(path, mode='r', encoding=None, errors=None, **kwargs)[source]

Opens the specified file, following the default “open()” semantics for this Python version unless an encoding is explicitly specified, in which case a file stream yielding (unicode) character strings is always returned.

Specifically:

On Python 3 this method returns a file stream yielding character strings unless a binary mode was specified in which case a stream yielding bytes is returned.

On Python 2 this method returns a file stream yielding unicode character strings only if an encoding was explicitly specified; otherwise it returns a file stream yielding “str” bytes objects.

Parameters
  • path – The path to open; must be an absolute path. Even on Windows this path can be long (e.g. more than the usual 256 character Windows limit).

  • mode – The file mode, e.g. ‘r’ for reading, ‘wb’ for binary writing.

  • encoding – The encoding to use to translate between the bytes of the file and the characters used in the returned stream. If an encoding is specified then the returned stream is always a unicode character stream. This must be None if the mode specifies binary.

  • errors – Optional string that specifies how encoding/decoding errors are handled, such as ‘strict’, ‘ignore’, ‘replace’; see documentation of io module for more details. The value of this attribute is ignored if using the python 2 open() built-in with bytes mode that does not support it.

  • kwargs – Any additional args to be passed to open() or io.open().

Returns

A file stream, either using unicode characters or binary bytes. This stream should be closed when no longer required.