[英]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__
是一个常量,如文档here和here中所述。 __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
。
使用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.