【问题标题】:How to make a .pyc file from Python script [duplicate]如何从 Python 脚本制作 .pyc 文件 [重复]
【发布时间】:2015-12-11 06:22:16
【问题描述】:

我知道当 Python 脚本被导入到其他 python 脚本中时,会创建一个 .pyc 脚本。有没有其他方法可以使用 linux bash 终端创建 .pyc 文件?

【问题讨论】:

标签: python terminal pyc


【解决方案1】:

使用以下命令:

python -m compileall <your_script.py>

这将在同一目录中创建your_script.pyc 文件。

您也可以将目录传递为:

python -m compileall <directory>

这将为目录中的所有 .py 文件创建 .pyc 文件

另一种方法是创建另一个脚本

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

它还会创建 your_script.pyc 文件。您可以将文件名作为命令行参数

【讨论】:

    【解决方案2】:

    您可以使用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__': 块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-24
      • 2016-08-11
      • 1970-01-01
      相关资源
      最近更新 更多