子进程不能在非交互模式下运行python可执行文件吗?

时间:2022-09-22 20:42:34

I am using python 3.6.3 and subprocess module to run another python script

我正在使用python 3.6.3和子进程模块来运行另一个python脚本。

#  main.py

#!/bin/env python
from subprocess import Popen,PIPE
from sys import executable

p = Popen([executable, 'test.py', 'arg1'],shell=True, stdout=PIPE)
p.wait()
print(p.stdout.read().decode())

and

#  test.py

import sys
print(sys.argv)

I expect it will run and execute test.py. However, it opens an python interpreter in interactive mode!

我希望它能运行并执行test.py。但是,它在交互模式下打开一个python解释器!

I tested shell=False option, it works. I tested string form rather than list form of args, it works.

我测试了shell=False选项,它是有效的。我测试的是字符串形式,而不是args的列表形式。

I am not sure if it is a bug or not.

我不确定这是否是一个bug。

1 个解决方案

#1


2  

You need to remove shell=True or change the first argument to be executable + ' test.py arg1' instead of [executable, 'test.py', 'arg1'].

您需要删除shell=True或将第一个参数更改为可执行的+ ' test。py arg1'代替[可执行,'测试。py”、“__arg1 ']。

As explained in the documentation, with shell = True, it will run it as /bin/sh -c python test.py arg1, which means python will be run without arguments.

如文档中所解释的,使用shell = True,它将运行为/bin/sh -c python测试。py arg1,这意味着python将不带参数运行。

#1


2  

You need to remove shell=True or change the first argument to be executable + ' test.py arg1' instead of [executable, 'test.py', 'arg1'].

您需要删除shell=True或将第一个参数更改为可执行的+ ' test。py arg1'代替[可执行,'测试。py”、“__arg1 ']。

As explained in the documentation, with shell = True, it will run it as /bin/sh -c python test.py arg1, which means python will be run without arguments.

如文档中所解释的,使用shell = True,它将运行为/bin/sh -c python测试。py arg1,这意味着python将不带参数运行。