【发布时间】:2011-04-09 19:28:20
【问题描述】:
由于某种原因,我不能依赖 Python 的“import”语句自动生成 .pyc 文件
有没有办法实现如下功能?
def py_to_pyc(py_filepath, pyc_filepath):
...
【问题讨论】:
标签: python
由于某种原因,我不能依赖 Python 的“import”语句自动生成 .pyc 文件
有没有办法实现如下功能?
def py_to_pyc(py_filepath, pyc_filepath):
...
【问题讨论】:
标签: python
您可以在终端中使用compileall。以下命令将递归进入子目录并为它找到的所有 python 文件创建 pyc 文件。 compileall 模块是 python 标准库的一部分,所以你不需要安装任何额外的东西来使用它。这对 python2 和 python3 的工作方式完全相同。
python -m compileall .
【讨论】:
-O 标志,用于字节码(.pyo 文件 iso .pyc)编译。
compileall,它搞砸了一切
您可以使用以下命令从命令行编译单个文件:
python -m compileall <file_1>.py <file_n>.py
【讨论】:
自从我上次使用Python已经有一段时间了,但我相信你可以使用py_compile:
import py_compile
py_compile.compile("file.py")
【讨论】:
__pycache__/file.cpython-32.pyc 之类的东西,你会得到它作为返回值。
我找到了几种将python脚本编译成字节码的方法
在终端中使用py_compile:
python -m py_compile File1.py File2.py File3.py ...
-m 指定要编译的模块名称。
或者,用于文件的交互式编译
python -m py_compile -
File1.py
File2.py
File3.py
.
.
.
使用py_compile.compile:
import py_compile
py_compile.compile('YourFileName.py')
使用py_compile.main():
它一次编译多个文件。
import py_compile
py_compile.main(['File1.py','File2.py','File3.py'])
列表可以随心所欲地增长。或者,您显然可以在 main 中传递文件列表,甚至可以在命令行 args 中传递文件名。
或者,如果您在 main 中传递 ['-'],那么它可以交互编译文件。
使用compileall.compile_dir():
import compileall
compileall.compile_dir(direname)
它编译提供的目录中存在的每个 Python 文件。
使用compileall.compile_file():
import compileall
compileall.compile_file('YourFileName.py')
看看下面的链接:
【讨论】:
py_compile 和compileall 而不是py_compile.py 或compileall.py。换句话说,应该是python3 -m py_compile PYTHON_FILENAME 或python3 -m compileall PYTHON_FILES_DIRECTORY。
我会使用compileall。它在脚本和命令行中都能很好地工作。它比已经提到的py_compile 更高级别的模块/工具,它也在内部使用。
【讨论】:
compileall 不包含跳过对应.pyc 文件已经是最新的文件的逻辑,是吗?
compileall 会跳过已经有最新的.pyc 的文件(使用 Python 2.7.11 测试)
python -m compileall <pythonic-project-name>
将所有.py 文件编译为包含包和模块的项目中的.pyc 文件。
python3 -m compileall <pythonic-project-name>
将所有.py 文件编译到包含包和模块的项目中的__pycache__ 文件夹。
或者this post的褐变:
您可以在文件夹中强制使用相同的
.pyc文件布局 Python2 使用:
python3 -m compileall -b <pythonic-project-name>选项
-b触发.pyc文件的输出到他们的 legacy-locations(即与 Python2 中的相同)。
【讨论】:
为了匹配原始问题要求(源路径和目标路径),代码应该是这样的:
import py_compile
py_compile.compile(py_filepath, pyc_filepath)
如果输入代码有错误,则会引发 py_compile.PyCompileError 异常。
【讨论】:
import (the name of the file without the extension)
【讨论】:
如果您使用命令行,请使用python -m compileall <argument> 将python 代码编译为python 二进制代码。
例如:python -m compileall -x ./*
或者, 您可以使用此代码将您的库编译为字节码:
import compileall
import os
lib_path = "your_lib_path"
build_path = "your-dest_path"
compileall.compile_dir(lib_path, force=True, legacy=True)
def moveToNewLocation(cu_path):
for file in os.listdir(cu_path):
if os.path.isdir(os.path.join(cu_path, file)):
compile(os.path.join(cu_path, file))
elif file.endswith(".pyc"):
dest = os.path.join(build_path, cu_path ,file)
os.makedirs(os.path.dirname(dest), exist_ok=True)
os.rename(os.path.join(cu_path, file), dest)
moveToNewLocation(lib_path)
查看☞ docs.python.org 了解详细文档
【讨论】: