出于某些原因,我无法依靠Python的"import"语句自动生成.pyc文件
是否有一种实现以下函数的方法?
def py_to_pyc(py_filepath, pyc_filepath):
...
出于某些原因,我无法依靠Python的"import"语句自动生成.pyc文件
是否有一种实现以下函数的方法?
def py_to_pyc(py_filepath, pyc_filepath):
...
compileall
。以下命令将递归进入子目录,并为找到的所有Python文件创建pyc文件。 compileall模块是Python标准库的一部分,因此您不需要安装任何额外的软件包来使用它。这对于Python2和Python3完全相同。python -m compileall .
您可以使用以下命令行编译单个文件:
python -m compileall <file_1>.py <file_n>.py
我已经有一段时间没有用Python了,但我相信你可以使用py_compile
:
import py_compile
py_compile.compile("file.py")
我找到了几种将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函数中传递文件列表,甚至是命令行参数中的文件名。
或者,如果您在主函数中传递['-']
,则它可以交互地编译文件。
使用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
。 - Devy我会使用compileall。它可以很好地从脚本和命令行中工作。它比已经提到的py_compile模块/工具更高级,它也在内部使用它。
compileall
是否包含跳过已经是最新的 .pyc
文件的逻辑呢? - Kyle Strandcompileall
命令会跳过已经存在最新的 .pyc
文件的文件(在 Python 2.7.11 中测试过)。 - Eponymous通常以下命令编译Python项目:
python -m compileall <project-name>
在Python2中,对于包含模块和包的项目,它会将所有的.py
文件编译成.pyc
文件。
而在Python3中,对于包含模块和包的项目,它会将所有的.py
文件编译到__pycache__
文件夹中。
根据这篇文章的提示:
你可以使用以下命令强制让
.pyc
文件与Python2中相同的布局方式生成:
python3 -m compileall -b <pythonic-project-name>
选项
-b
会触发输出.pyc
文件到它们遗留的位置(就像在Python2中一样)。
import py_compile
py_compile.compile(py_filepath, pyc_filepath)
import(文件名不带扩展名)
如果您正在使用命令行,请使用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
compileall
命令,这导致了一切都出现了问题。请小心操作。 - Alex