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

2024-05-26 01:06:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果我有以下test.py脚本(读取built-in constant ^{}):

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

然后:

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

因为constant ^{}是如何工作的:

This constant is true if Python was not started with an -O option. See also the assert statement.

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

以下内容正确打印“调试关闭”

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

但是有没有一种更类似于Python的方式呢? 如果不调用python解释器,那么上面的代码似乎不是很容易移植

我已经在这里和网上搜索过了


Tags: textpydebugtest脚本ifhereon
1条回答
网友
1楼 · 发布于 2024-05-26 01:06:51

使用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:使用与运行函数的Python解释器相同的优化级别compile
  • 0:没有优化,和__debug__ == true
  • 1:与-O类似,即删除assert语句和__debug__ == false
  • 2:与{}类似,也就是说,删除文档字符串

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

使用subprocess.run

基于subprocess的方法更加简洁,可以通过使用^{}进行移植:

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)

上面的代码调用函数^{}

检查变量sys.executable的值是由CPython的documentation引起的:

If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None.

检查是用raise语句而不是assert语句来实现的,以便在上述Python代码本身使用Python请求的优化运行的情况下也进行检查,例如,通过使用^{}^{}或环境变量^{}

When optimization is requested, ^{} statements are removed

使用raise语句还可以引发除AssertionError之外的异常,在本例中是^{}

对于在同一源文件内的函数内运行Python代码(即在main.py内,而不是在test.py内),函数^{}可以与option ^{} of ^{}一起使用

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

相关问题 更多 >