出于某种原因,我不能依赖 Python 的“ import”语句自动生成.pyc 文件
有没有一种方法来实现如下函数?
def py_to_pyc(py_filepath, pyc_filepath): ...
我已经有一段时间没有使用 Python 了,但是我相信你可以使用 py_compile:
py_compile
import py_compile py_compile.compile("file.py")
我会用 编译。它从脚本和命令行都可以很好地工作。它比它内部使用的前面提到的 Py _ 编译模块/工具稍微高级一些。
您可以在终端中使用 compileall。下面的命令将递归地进入子目录,并为它找到的所有 python 文件创建 pyc 文件。编译模块是 python 标准库的一部分,因此使用它不需要安装任何额外的东西。这与 python2和 python3的工作方式完全相同。
compileall
python -m compileall .
您可以使用以下命令行编译单个文件:
python -m compileall <file_1>.py <file_n>.py
我找到了将 python 脚本编译成字节码的 好几个方法
在终端机使用 py_compile:
python -m py_compile File1.py File2.py File3.py ...
-m指定要编译的模块名称。
-m
或者,用于交互式文件编译
python -m py_compile - File1.py File2.py File3.py . . .
Using py_compile.compile:
py_compile.compile
import py_compile py_compile.compile('YourFileName.py')
Using py_compile.main():
py_compile.main()
It compiles several files at a time.
import py_compile py_compile.main(['File1.py','File2.py','File3.py'])
名单可以增加,只要你愿意。或者,显然可以在主文件名中传递文件列表,甚至可以在命令行参数中传递文件名。
或者,如果在 main 中传递 ['-'],那么它可以交互式地编译文件。
['-']
使用 compileall.compile_dir():
compileall.compile_dir()
import compileall compileall.compile_dir(direname)
它编译所提供目录中的每个 Python 文件。
使用 compileall.compile_file():
compileall.compile_file()
import compileall compileall.compile_file('YourFileName.py')
Take a look at the links below:
https://docs.python.org/3/library/py_compile.html
https://docs.python.org/3/library/compileall.html
为了匹配原始问题需求(源路径和目标路径) ,代码应该是这样的:
import py_compile py_compile.compile(py_filepath, pyc_filepath)
如果输入代码有错误,则引发 Py _ edit. PyCompileError异常。
通常,下面的命令编译一个 python 项目:
python -m compileall <project-name>
在 Python 2中,它将所有的 .py文件编译成包含包和模块的项目中的 .pyc文件。
.py
.pyc
而在 Python 3中,它将所有的 .py文件编译成包含包和模块的项目中的 __pycache__文件夹。
__pycache__
伴随 这篇文章的褐变:
中的文件夹中的 .pyc文件的布局可以强制执行相同的布局 Python 2通过使用: python3 -m compileall -b <pythonic-project-name> 选项 -b将 .pyc文件的输出触发到它们的 遗留位置(即与 Python 2中相同)。
中的文件夹中的 .pyc文件的布局可以强制执行相同的布局 Python 2通过使用:
python3 -m compileall -b <pythonic-project-name>
选项 -b将 .pyc文件的输出触发到它们的 遗留位置(即与 Python 2中相同)。
-b
如果使用命令行,请使用 python -m compileall <argument>将 python 代码编译为 python 二进制代码。 例句: python -m compileall -x ./*
python -m compileall <argument>
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)
查看 祝你好运的详细文档
import (the name of the file without the extension)