pythoninterpreter

Understanding python compile


I seen the some difference when I execute the .py file. I have observed two cases,

1) when I run the .py file using the python mypython.py

I got the result. But .pyc file not created in my folder.

2) when I run the .py file using the python -c "import mypython"

I got the same result. But .pyc file was created in my folder.

My question is why first case not created .pyc file ?


Solution

  • Python saves the precompiled .pyc file only for imported modules, not for the main script you're running.

    Running a program as main or importing it as a module is not the exact same thing, but very similar because in a module everything that is at top level is executed at import time.

    Note that for main program the source code is completely parsed and compiled too (so for example if you have a syntax error in last line nothing will be executed). The difference is only that the result of compilation is not saved back to disk.