使用不同的脚本有效地重新执行Python解释器

2024-04-25 19:03:16 发布

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

我正在编写一个用Python编写的包装器脚本。包装器应该根据系统状态选择另一个Python脚本并执行它(使用绝对路径)。不需要返回父脚本。在

应该注意的是,我无法控制正在运行的脚本。它们可以使用__name__检查、访问sys.argv,而且它们的行为都应该与直接运行脚本的行为类似。在

现在,我正在使用os.execl()

import os, sys

# ...

os.execl(sys.executable, sys.executable, new_script, *sys.argv[1:])

但我至少可以算出三个问题:

  1. 传递给Python解释器的任何选项都不会被保留(例如,python -v wrapper在重新执行时不再是冗长的)
  2. 不必要地重新执行Python解释器(使用PyPy,它在我的系统上添加了0,7s)
  3. 它依赖于sys.executable是否有用,文档中说:

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

我想知道我应该用什么替代os.execl调用来解决所有问题。到目前为止,我可以看出:
  1. execfile()可能可以工作,但它在Python3中被删除了,手工重新实现它是丑陋的(因为编码问题)。我不确定execfile()还有什么其他含义
  2. imp.load_module()可能可以工作,但它有点老套,在Python3.3中被弃用。它可能也会遇到Python3编码问题。在

你建议我用哪种方法?在


编辑:我会忘记的。这个解决方案必须使用python2.5+、PyPy和jython2.5+。在


Tags: toname脚本编码os状态系统sys
2条回答

我只使用execfile()而不是imp.load_module()。虽然控制权将回到执行脚本,但一个很大的优势是引用文档:

It is different from the import statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module.

这意味着脚本文件可以在任何地方,可以有任何(或没有)文件扩展名,并且在执行与模块导入相关的任务时不会浪费资源。在

这样做会自动完成或避免您想要的事情:

  1. 解释器选项将被保留
  2. 不需要重新执行解释器
  3. 它不依赖sys.executable的值

你试过这种方法吗?在

### wrapped script ###

import sys

print("__name__: {0}\nsys.argv: {1}".format(__name__, sys.argv))
^{pr2}$

结果:

$ python3 wrapped_script.py  foo  bar=quux
__name__: __main__
sys.argv: ['wrapped_script.py', ' foo', ' bar=quux']

$ python3 wrapper.py  foo  bar=quux
Executing the wrapped script...
__name__: __main__
sys.argv: ['wrapped_script.py', ' foo', ' bar=quux']

相关问题 更多 >