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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With