Force subprocess to use Python 3 [closed]

2020-01-20 01:02发布

So, I was trying to write a Python script that utilized subprocess to call another Python script in the same directory. This was all going well until an import statement within the second script was reached of a Python 3-only library, and since the script was opened using subprocess, which in turn uses Python 2, an ImportError occurred.

How can I force subprocess, specifically Popen(), to use Python 3 to open the script? There does not seem to be advice on this online.

Edit

While I always default to posting MWEs, for this question I believed it was unnecessary, but at any rate s soon as I proceeded to post it, it occurred to me to use 'python3' instead of just 'python',

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

and now the app works. What is strange is that I have only one version of Python installed by myself (3.7), and python redirects to python3, so it is strange I had to manually specify python3.

1条回答
不美不萌又怎样
2楼-- · 2020-01-20 01:55

Here's a way to force a script to be run with Python3:

#! /usr/bin/python3

import sys, subprocess

if sys.version_info[:2] < (3, 0):
    # FORCE PYTHON3
    code = subprocess.check_call(['python3'] + sys.argv)
    raise SystemExit(code)

print("Using Python v%d.%d" % sys.version_info[:2])

Example when run in Bash:

> python3 force_python3.py                                                                                                                         
Using Python v3.7

> python2 force_python3.py                                                                                                                         
Using Python v3.7
查看更多
登录 后发表回答