Domanda

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 ?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

Import is generally used when you need to use the contents of a file in another script or program, see What does python file extensions, .pyc .pyd .pyo stand for?. So to more specifically answer the question, the .pyc is created to ease access to the contents of the file in the future and is only created when the import command is used.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top