如何从.py文件手动生成.pyc文件

问题:如何从.py文件手动生成.pyc文件

由于某种原因,我不能依靠Python的“ import”语句来自动生成.pyc文件

有没有一种方法可以实现以下功能?

def py_to_pyc(py_filepath, pyc_filepath):
    ...

For some reason, I can not depend on Python’s “import” statement to generate .pyc file automatically

Is there a way to implement a function as following?

def py_to_pyc(py_filepath, pyc_filepath):
    ...

回答 0

您可以compileall在终端中使用。以下命令将递归进入子目录,并为找到的所有python文件创建pyc文件。该compileall模块是Python标准库的一部分,所以你不需要安装任何额外的使用它。这对于python2和python3完全相同。

python -m compileall .

You can use compileall in the terminal. The following command will go recursively into sub directories and make pyc files for all the python files it finds. The compileall module is part of the python standard library, so you don’t need to install anything extra to use it. This works exactly the same way for python2 and python3.

python -m compileall .

回答 1

您可以使用以下命令从命令行编译单个文件:

python -m compileall <file_1>.py <file_n>.py

You can compile individual files(s) from the command line with:

python -m compileall <file_1>.py <file_n>.py

回答 2

自从我上一次使用Python已经有一段时间了,但是我相信您可以使用py_compile

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

It’s been a while since I last used Python, but I believe you can use py_compile:

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

回答 3

我发现几种将python脚本编译成字节码的方法

  1. py_compile在终端中使用:

    python -m py_compile File1.py File2.py File3.py ...

    -m 指定要编译的模块名称。

    或者,用于文件的交互式编译

    python -m py_compile -
    File1.py
    File2.py
    File3.py
       .
       .
       .
  2. 使用py_compile.compile

    import py_compile
    py_compile.compile('YourFileName.py')
  3. 使用py_compile.main()

    它一次编译几个文件。

    import py_compile
    py_compile.main(['File1.py','File2.py','File3.py'])

    该列表可以根据需要增加。或者,您显然可以在命令行args中传递主要甚至文件名中的文件列表。

    或者,如果您传入['-']main,则它可以交互式地编译文件。

  4. 使用compileall.compile_dir()

    import compileall
    compileall.compile_dir(direname)

    它编译提供的目录中存在的每个Python文件。

  5. 使用compileall.compile_file()

    import compileall
    compileall.compile_file('YourFileName.py')

看一下下面的链接:

https://docs.python.org/3/library/py_compile.html

https://docs.python.org/3/library/compileall.html

I found several ways to compile python scripts into bytecode

  1. Using py_compile in terminal:

    python -m py_compile File1.py File2.py File3.py ...
    

    -m specifies the module(s) name to be compiled.

    Or, for interactive compilation of files

    python -m py_compile -
    File1.py
    File2.py
    File3.py
       .
       .
       .
    
  2. Using py_compile.compile:

    import py_compile
    py_compile.compile('YourFileName.py')
    
  3. Using py_compile.main():

    It compiles several files at a time.

    import py_compile
    py_compile.main(['File1.py','File2.py','File3.py'])
    

    The list can grow as long as you wish. Alternatively, you can obviously pass a list of files in main or even file names in command line args.

    Or, if you pass ['-'] in main then it can compile files interactively.

  4. Using compileall.compile_dir():

    import compileall
    compileall.compile_dir(direname)
    

    It compiles every single Python file present in the supplied directory.

  5. Using 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


回答 4

我会用compileall。从脚本和命令行都可以很好地工作。它比已经在内部使用的py_compile更高级别的模块/工具。

I would use compileall. It works nicely both from scripts and from the command line. It’s a bit higher level module/tool than the already mentioned py_compile that it also uses internally.


回答 5

在Python2中,您可以使用:

python -m compileall <pythonic-project-name>

这样就可以全部编译.py.pyc包含子文件夹的项目中。


在Python3中,您可以使用:

python3 -m compileall <pythonic-project-name>

这样就可以全部编译.py__pycache__项目中包含子文件夹的文件夹中。

或从这篇文章中褐变:

您可以.pyc使用以下命令在文件夹中强制执行与Python2中相同的文件布局:

python3 -m compileall -b <pythonic-project-name>

该选项-b触发.pyc文件输出到其旧位置(即与Python2中相同)。

In Python2 you could use:

python -m compileall <pythonic-project-name>

which compiles all .py files to .pyc files in a project which contains packages as well as modules.


In Python3 you could use:

python3 -m compileall <pythonic-project-name>

which compiles all .py files to __pycache__ folders in a project which contains packages as well as modules.

Or with browning from this post:

You can enforce the same layout of .pyc files in the folders as in Python2 by using:

python3 -m compileall -b <pythonic-project-name>

The option -b triggers the output of .pyc files to their legacy-locations (i.e. the same as in Python2).


回答 6

为了匹配原始问题要求(源路径和目标路径),代码应如下所示:

import py_compile
py_compile.compile(py_filepath, pyc_filepath)

如果输入代码有错误,则会引发py_compile.PyCompileError异常。

To match the original question requirements (source path and destination path) the code should be like that:

import py_compile
py_compile.compile(py_filepath, pyc_filepath)

If the input code has errors then the py_compile.PyCompileError exception is raised.


回答 7

有两种方法可以做到这一点

  1. 命令行
  2. 使用python程序

如果使用命令行,则将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 compile(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)

compile(lib_path)

看看☞docs.python.org详细资料

There is two way to do this

  1. Command line
  2. Using python program

If you are using command line use python -m compileall <argument> to compile python code to python binary code. Ex: python -m compileall -x ./*

Or, You can use this code to compile your library into byte-code.

import compileall
import os

lib_path = "your_lib_path"
build_path = "your-dest_path"

compileall.compile_dir(lib_path, force=True, legacy=True)

def compile(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)

compile(lib_path)

look at ☞ docs.python.org for detailed documentation