繁体   English   中英

从另一个 Python 脚本以优化模式运行 Python 脚本

[英]Running a Python script in optimized mode from another Python script

有没有办法从另一个 Python (Python 3) 脚本以优化模式运行 python 脚本?

如果我有以下test.py脚本(读取内置常量__debug__ ):

if __debug__:
    print('Debug ON')
else:
    print('Debug OFF')

然后:

  • python text.py打印Debug ON
  • python -OO text.py打印Debug OFF

因为常量__debug__的工作方式:

如果 Python 未使用-O选项启动,则此常量为真。 另请参见assert语句。

此外, __debug__的值不能在运行时更改: __debug__是一个常量,如文档herehere中所述。 __debug__的值是在 Python 解释器启动时确定的。

以下正确打印Debug OFF

import subprocess
subprocess.run(["python", "-OO", "test.py"])

但是有没有更蟒蛇的方式? 如果解释器不被称为python ,则上述内容似乎不太便携。

我已经在这里搜索过 web 没有运气。

使用compile

我想出了一个使用内置 function compile的解决方案,如下所示。

文件main.py的内容:

with open('test.py') as f:
    source_code = f.read()
compiled = compile(
    source_code,
    filename='test.py', mode='exec', optimize=2)
exec(compiled)

文件test.py的内容:

if __debug__:
    print('Debug ON')
else:
    print('Debug OFF')

运行python main.py是:

Debug OFF

参数optimize的可能值:

  • -1 :使用与运行 function compile的 Python 解释器相同的优化级别
  • 0 : 没有优化,并且__debug__ == true
  • 1 :与-O类似,即删除assert语句,并且__debug__ == false
  • 2 : 像-OO一样,也就是删除文档字符串。

不知道这是否是最好的选择,只是分享是否对其他人有用。

使用subprocess.run

基于subprocess的方法更加简洁,并且可以通过使用sys.executable进行移植:

import subprocess
import sys

if not sys.executable:
    raise RuntimeError(sys.executable)
proc = subprocess.run(
    [sys.executable, '-OO', 'test.py'],
    capture_output=True, text=True)
if proc.returncode != 0:
    raise RuntimeError(proc.returncode)

上面的代码调用了 function subprocess.run

检查变量sys.executable的值是由 CPython 的文档推动的:

如果 Python 无法检索到其可执行文件的真实路径, sys.executable将为空字符串或None

The check is implemented with a raise statement, instead of an assert statement, in order to check also in cases that the above Python code is itself run with optimization requested from Python, eg, by using python -O orpython -OO or the environment变量PYTHONOPTIMIZE

当请求优化时, assert语句被删除

使用raise语句还可以引发AssertionError以外的异常,在本例中为RuntimeError

For running Python code that is within a function inside the same source file (ie, inside main.py , not inside test.py ), the function inspect.getsource can be used, together with the option -c of python .

顺便说一句,欢迎更好的答案!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM