2

I know py_compile.compile("file.py") will compile file.py.

But can I in that same code that runs that command somehow check if the compilation was successful or not?

I want to essentially have an if-condition depending on whether the compilation was a success or not. Is it possible using the py_compile module? Or is there something better I could use?

1
  • Have you tried with the doraise option turned to true so it raises an exception if it fails? Commented Jan 31, 2018 at 17:05

1 Answer 1

5

You can do something like this:

import py_compile
try:
    py_compile.compile("file.py", doraise=True)
except py_compile.PyCompileError:
    print("Compilation failed!")

As always in Python, it is better to seek forgiveness than to ask permission.

Sign up to request clarification or add additional context in comments.

2 Comments

Yup that's it. Is there something equivalent for compileall.compile_dir?
It doesn't appear there is, at first glance... It'd be relatively straightforward to use py_compile and write the recursion yourself (using eg. os.walk), but I'm not sure if compileall does other things than just compile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.