How does Python read and interpret source files?

后端 未结 2 1838
后悔当初
后悔当初 2021-01-20 18:34

Say I run a Python (2.7, though I\'m not sure that makes a difference here) script. Instead of terminating the script, I tab out, or somehow switch back to my editing enviro

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 19:03

    Python loads the main script into memory, compiles it into bytecode and runs that. If you modify the source file in the meantime, you're not affecting the bytecode.

    If you're running the script as the main script (i. e. by calling it like python myfile.py, then the bytecode will be discarded when the script exits.

    If you're importing the script, however, then the bytecode will be written to disk as a .pyc file which won't be recompiled when imported again, unless you modify the corresponding .py file.

    Your big 6.5 MB program consists of many modules which are imported by the (probably small) main script, so only that will have to be compiled at each run. All the other files will have their .pyc file ready to run.

提交回复
热议问题