InterviewSolution
| 1. |
Python scripts are saved with .py extension. However, .pyc files are frequently found. What do they stand for? |
|
Answer» The mechanism of execution of a Python program is similar to Java. A Python script is first COMPILED to a bytecode which in turn is executed by a platform specific Python virtual machine i.e. Python interpreter. However, unlike Java, bytecode version is not stored as a disk file. It is held temporarily in the RAM itself and DISCARDED after execution. However, things are different when a script imports one or more MODULES. The imported modules are compiled to bytecode in the form of .pyc file and stored in a directory named as __pycache__. Following Python script imports another script as module. #hello.py def hello(): print ("Hello World") #example.py import hello hello.hello()Run example.py from command line Python example.pyYou will find a __pycache__ folder created in current working directory with hello.cpython-36.pyc file created in it. The advantage of this compiled file is that whenever hello module is imported, it need not be converted to bytecode again as LONG as it is not modified. As mentioned above, when executed, .pyc file of the .py script is not created. If you want it to be explicitly created, you can use py_compile and compileall modules available in standard library. To compile a specific script import py_compile py_compile.compile(‘example.py’, ‘example.pyc’)This module can be directly used from command line python -m py_compile example.pyTo compile all files in a directory import compileall compileall.compile_dir(‘newdir’)Following command line usage of compileall module is also allowed: python -m compileall newdirWhere newdir is a folder under current working directory. |
|