Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a .pyc file from Python script [duplicate]

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

like image 978
MikhilMC Avatar asked Sep 15 '15 05:09

MikhilMC


2 Answers

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

When this module is run as a script, the main() is used to compile all the files named 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'd do something like

$ python3 -m compileall ...

Where ... are files to compile or directories that contain source files, traversed 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 former won't execute the if __name__ == '__main__': block in module.py.

like image 99
vaultah Avatar answered Sep 25 '22 23:09

vaultah


Use the following command:

python -m compileall <your_script.py>

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

You can pass directory also as :

python -m compileall <directory>

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

Other way is to create another script as

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

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

like image 43
User007 Avatar answered Sep 25 '22 23:09

User007