0

I am using py_compile to convert the python files(.py) to .pyc files.

py_compile.compile(py_src_file, doraise=True)

The python scripts contains code which have syntax both for python version 2.7 and 3.8 version. The py_compile when using with python 3.8 version generates an error for corresponding 2.7 syntax. Is there a way to check the python version while compiling the code and compile corresponding instruction only.

For ex:

if python_version == 2.7:
   # py_compile should see 2.7 code
else:
   # py_compile should see 3.8 code

I got some help in this answer: How would you do the equivalent of preprocessor directives in Python?, but don't know how to exactly use in my case. Thanks for your help.

Shaido
  • 27,497
  • 23
  • 70
  • 73
  • Using a python preprocessor that has access to the version would be the way to go. https://pypi.org/project/preprocessor/ – FlipMcF Aug 17 '20 at 16:10
  • 2
    If `py_compile` fails due to the mixture of version-specific syntaxes - then surely the files would fail in exactly the same way when actually imported? I don't think you're trying to solve the right problem here. – jasonharper Aug 17 '20 at 16:42
  • @jasonharper.. I am thinking to use the conditional imports too based on the same above approach – Utkarash Singh Aug 17 '20 at 16:48
  • Conditional imports of files that are individually in a single version's syntax would work - but then you'd have to run `py_compile` once with each version of Python, specifying only the files in its syntax. – jasonharper Aug 17 '20 at 16:53

0 Answers0