【发布时间】:2018-01-17 23:45:27
【问题描述】:
我使用的是 subprocess.Popen 而不是 os.fork(),并尝试使用“shell=True”构造。但是,要传递给子进程的参数将被删除。知道为什么,有什么可以解决的吗?
附加的文件是“/tmp/a.py”和“/tmp/a.pl”。如果我在没有任何参数的情况下运行 a.py,我会得到预期的结果。带参数,错误消息。
#!/opt/local/bin/python3.6
import sys, subprocess
class child_proc:
def __init__ (self, useShell):
print ("useShell:", useShell)
acmd = ["/tmp/a.pl", "Hello", "World"]
if useShell:
proc = subprocess.Popen(acmd, stdout=subprocess.PIPE, shell=True)
else:
proc = subprocess.Popen(acmd, stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if line:
try:
aline = line.decode().rstrip()
print (aline)
except UnicodeDecodeError as e:
print("Error decoding child output:", line, e)
break
else:
break
child_proc(len(sys.argv) > 1)
它正在调用的脚本 -
#!/opt/local/bin/perl -w
die "[a.pl] Missing arguments\n" if $#ARGV < 0;
print "[a.pl] @ARGV\n";
exit 0;
这是在 MacOS10.13.1 上。感谢您的洞察力。
【问题讨论】:
-
来自文档:“如果 shell 为 True,建议将 args 作为字符串而不是序列传递。”另外,你不应该使用
Popen,而是run或checkoutput,你也不应该使用shell=True,你也应该使用shell=useShell而不是if/else。当您实际上不使用argv时,为什么首先要这样做? -
我在这里得到的是,如果我使用 Shell=True,我需要使用 ' '.join(acmd) 而不是 acmd - 这解决了问题。
标签: python