How to make a .pyc file from a Python script

I know that when a Python script is imported into another python script, then a .pyc script is created. Is there any other way to create a .pyc file using linux bash terminal?

+8
python terminal pyc
source share
2 answers

You can use the py_compile module. Run it from the command line ( -m ):

When this module is run as a script, main () is used to compile all the files whose names are specified on the command line.

Example:

 $ tree . └── script.py 0 directories, 1 file $ python3 -mpy_compile script.py $ tree . β”œβ”€β”€ __pycache__ β”‚  └── script.cpython-34.pyc └── script.py 1 directory, 2 files 

compileall provides similar functionality, to use it, you would do something like

 $ python3 -m compileall ... 

Where ... - files for compilation or directories containing source files are moved recursively.


Another option is to import the module:

 $ tree . β”œβ”€β”€ module.py β”œβ”€β”€ __pycache__ β”‚  └── script.cpython-34.pyc └── script.py 1 directory, 3 files $ python3 -c 'import module' $ tree . β”œβ”€β”€ module.py β”œβ”€β”€ __pycache__ β”‚  β”œβ”€β”€ module.cpython-34.pyc β”‚  └── script.cpython-34.pyc └── script.py 1 directory, 4 files 

-c 'import module' is different from -m module because the first will not execute the if __name__ == '__main__': block in module.py.

+5
source share

Use the following command:

 python -m compileall <your_script.py> 

This will create your_script.pyc file in the same directory.

You can also pass the directory as:

 python -m compileall <directory> 

This will create .pyc files for all .py files in the directory

Another way is to create another script like

 import py_compile py_compile.compile("your_script.py") 

It also creates your_script.pyc file. You can take the file name as a command line argument

+6
source share

All Articles