如何在Python中生成字节码文件

如何在Python中生成字节码文件

所有的Python程序在执行之前自动将源代码编译成字节码,也称为编译码。

每当我们第一次导入一个模块,或者当您的源文件是一个新文件或是一个已更新的文件时,则最近编译的文件,即.pyc文件,将在与.py文件相同的目录中(从Python3开始,您可能会看到.pyc文件位于名为pycache的子目录中,而不是与.py文件相同的目录中)。这是一个节省时间的机制,因为它可以防止Python在下一次运行程序时跳过编译步骤。

如果您运行的是一个带有import(其他文件)的脚本,则不会创建.pyc文件。例如,如果您有一个脚本(file1.py)导入另一个文件(file2.py)。

创建PYC文件的最简单方法是导入它。假设你有一个名为MainP.py的模块。只需执行以下操作—

>>> import MainP
>>>
Python

然而,如果您想为一个未被导入的模块创建.pyc文件,则我们需要一组名称为py_compile和compile的模块来完成这个任务。

Py_compile模块可以手动编译任何模块。我们还可以使用py_compile.compile函数使py_compile模块交互。

>>> import py_compile
>>> py_compile.compile('test.py')
'__pycache__\test.cpython-36.pyc'
>>>
Python

一旦我们在Python shell中运行上述语句,我们可以看到一个.pyc文件被创建在pycache文件夹中(Python 3中),否则将被创建在与test.py文件相同的位置。

如何在Python中生成字节码文件

如果您想一次编译多个文件,您可以使用py_compile.main()函数,如下所示—

>>> #编译多个文件
>>> py_compile.main(['test1.py', 'test2.py', 'test_sample1.py', 'test_sample2.py'])
0
Python

我们可以看到生成了四个不同的编译文件—

如何在Python中生成字节码文件

但是,如果您想为一个文件夹中的所有文件编译.pyc文件,则可以使用compileall.compile_dir()函数。

>>> #从特定文件夹中编译所有.py文件。
>>> import compileall
>>> compileall.compile_dir('gmplot')
Listing 'gmplot'...
Listing 'gmplot\.git'...
Listing 'gmplot\.git\hooks'...
Listing 'gmplot\.git\info'...
Listing 'gmplot\.git\logs'...
Listing 'gmplot\.git\logs\refs'...
Listing 'gmplot\.git\logs\refs\heads'...
Listing 'gmplot\.git\logs\refs\remotes'...
Listing 'gmplot\.git\logs\refs\remotes\origin'...
Listing 'gmplot\.git\objects'...
Listing 'gmplot\.git\objects\info'...
Listing 'gmplot\.git\objects\pack'...
Listing 'gmplot\.git\refs'...
Listing 'gmplot\.git\refs\heads'...
Listing 'gmplot\.git\refs\remotes'...
Listing 'gmplot\.git\refs\remotes\origin'...
Listing 'gmplot\.git\refs\tags'...
Compiling 'gmplot\__init__.py'...
Compiling 'gmplot\color_dicts.py'...
Listing 'gmplot\gmplot'...
Listing 'gmplot\gmplot\markers'...
Compiling 'gmplot\gmplot.py'...
Compiling 'gmplot\google_maps_templates.py'...
Compiling 'gmplot\setup.py'...
Listing 'gmplot\tests'...
True
Python

现在我们可以看到.pyc文件被创建在’folder_name\__pycache__’位置中。

如何在Python中生成字节码文件

如果您想编译一个目录或多个目录中的所有文件,则可以使用 compile function。

C:\Users\rajesh>python -m compileall
跳过当前目录
列出'C:\Python\Python361\python36.zip'...
无法列出'C:\Python\Python361\python36.zip'
列出'C:\Python\Python361\DLLs'...
列出'C:\Python\Python361\lib'...
列出'C:\Python\Python361'...
编译'C:\Python\Python361\BeautifulSoup_script1.py'...
编译'C:\Python\Python361\EDA_python1.py'...
编译'C:\Python\Python361\MainP.py'...
编译'C:\Python\Python361\NegativeAgeException.py'...
编译'C:\Python\Python361\NegativeNumberException.py'...
编译'C:\Python\Python361\OtherP.py'...
编译'C:\Python\Python361\__init__ Constructor.py'...
编译'C:\Python\Python361\attribute_access.py'...
..

编译'C:\Python\Python361\variable_arguments_list.py'...
编译'C:\Python\Python361\variable_arguments_list1.py'...
编译'C:\Python\Python361\winquality1.py'...
Python

我们可以看到.pycache目录中的所有文件都创建了.pyc文件。

如何在Python中生成字节码文件

阅读更多:Python 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册