我已经开始学习Python,而且我也是Ubuntu的新用户。我需要知道如何编译`.py`文件的方法。我已尝试使用以下命令:
其他编译Python的方法有哪些?
python "hello.py"
其他编译Python的方法有哪些?
py_compile
模块作为脚本:
python -m py_compile fileA.py fileB.py fileC.py ...
-O
标志,例如python -O -m py_compile …
,这将“开启基本优化”。它主要会去除assert
语句和if __debug__
代码,所以对大多数代码没有影响。详细信息请参考man python
和“What does Python optimization … do?”。 - Rory O'Kane还要注意的是,您不需要编译 .py
文件就可以运行它。Python 是一种解释型语言,您可以直接运行脚本,方法如下:
python hello.py
#!/usr/bin/env python
,使脚本可执行,然后使用chmod +x hello.py
将文件设置为可执行,并运行以下命令:./hello.py
chmod +x
),解释器是如何读取脚本的呢? - fabda01#!/path/to/interpreter
开头的脚本,内核实际上会执行在那里声明的内容,并将脚本路径作为一个参数传递。以我的例子为例,当你运行./hello.py
时,实际执行的是/usr/bin/env python ./hello.py
。详见https://en.wikipedia.org/wiki/Shebang_(Unix) - MestreLionchmod +x
授予执行权限,并且不会影响现有的权限,因此可以假设它在现在具有可执行权限的同时也是可读的。 - spectrascompileall
:python -m compileall ./
看看这个链接 在Python中编译
在页面的中间部分,它谈到了可以导入的py_compile模块。 语法如下:
import py_compile
py_compile.compile("file.py")
nuitka hello.py
python -m py_compile script.py
- Mayur