强制子进程使用 Python 3

所以,我试图编写一个 Python 脚本,用于subprocess调用同一目录中的另一个 Python 脚本。这一切都很顺利,直到第二个脚本中的 import 语句被一个 Python 3-only 库访问,并且由于脚本是使用 打开的subprocess,而后者又使用 Python 2,所以ImportError发生了。

subprocess具体来说Popen(),我如何强制使用 Python 3 打开脚本?网上好像没有这方面的建议。

编辑

虽然我总是默认发布 MWE,但对于这个问题,我认为这是不必要的,但无论如何,当我开始发布它时,我突然想到使用“python3”而不仅仅是“python”,

stream = subprocess.Popen(['python3', 'app.py'])

现在该应用程序可以运行了。奇怪的是,我自己只安装了一个版本的 Python(3.7),并且python重定向到python3,所以很奇怪我不得不手动指定python3.


猛跑小猪
浏览 135回答 1
1回答

浮云间

这是强制使用 Python3 运行脚本的方法:#! /usr/bin/python3import sys, subprocessif sys.version_info[:2] < (3, 0):&nbsp; &nbsp; # FORCE PYTHON3&nbsp; &nbsp; code = subprocess.check_call(['python3'] + sys.argv)&nbsp; &nbsp; raise SystemExit(code)print("Using Python v%d.%d" % sys.version_info[:2])在 Bash 中运行的示例:> python3 force_python3.py&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Using Python v3.7> python2 force_python3.py&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Using Python v3.7
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python