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?
-
can't do $ python -c "import script" ? – Yichun Sep 15 '15 at 05:48
-
1[`python -m compileall`](https://docs.python.org/2/library/compileall.html) – Peter Wood Sep 15 '15 at 06:11
-
I think you should try to use 'zipfile' to make pyc. It's so easy to make it. You can use it to deploy your code by no src. – huang Sep 15 '15 at 08:13
-
look at https://stackoverflow.com/a/61899114/3404480 it may help you in python3 – Prashant May 19 '20 at 19:26
2 Answers
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

- 2,347
- 7
- 37
- 62
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.

- 44,105
- 12
- 114
- 143