2015-09-15 53 views
8

我知道,當Python腳本在其他python腳本中導入時,將創建一個.pyc腳本。有沒有其他方法可以通過使用linux bash終端創建.pyc文件?如何從Python腳本創建.pyc文件

+0

不能做$ python -c「import script」? – Yichun

+1

['python -m compileall'](https://docs.python.org/2/library/compileall.html) –

+0

我想你應該嘗試使用'zipfile'來製作pyc。 製作它非常容易。 您可以使用它來通過no src部署您的代碼。 – xiaohen

回答

5

您可以使用py_compile模塊。從命令行(-m選項)運行:

在此模塊中運行的腳本,該的main()用來編譯所有 命名的命令行上的文件。

例子:

$ 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提供了類似的功能,使用它,你會做這樣的事情

$ python3 -m compileall ... 

...是文件編譯或包含在源文件目錄,遞歸遍歷


另一種選擇是導入模塊:

$ 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'-m module不同,因爲前者不會module.py執行if __name__ == '__main__':塊。

6

使用以下命令:

python -m compileall <your_script.py> 

這將在同一目錄中創建your_script.pyc文件。

您可以通過目錄也爲:

python -m compileall <directory> 

這將在目錄中創建.pyc文件的所有.py文件的文件

另一種方法是創建另一個腳本

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

它也創建your_script.pyc文件。你可以把文件名作爲命令行參數

相關問題