从 subprocess.Popen 将参数传递给 argparse

Abh*_*bhi 5 subprocess os.system python-2.x python-3.x

我正在尝试使用 python 3 中的 subprocess.Popen 功能从另一个脚本(scriptB)中使用 python 2 (例如 scriptA) 调用脚本

我希望调用的脚本实现了一个 argparse 方法,该方法需要两个参数,如下所示:ScriptA(需要 python 2):

def get_argument_parser():
'''
'''
import argparse

parser = argparse.ArgumentParser("Get the args") 

parser.add_argument("-arg1", "--arg1",required = True,
                    help = "First Argument")

parser.add_argument("-arg2", "--arg2",required = True,
                    help = "Second Argument")

return parser
Run Code Online (Sandbox Code Playgroud)

现在,我使用子进程调用上述脚本,如下所示: ScriptB:

value1 = "Some value"
value2 = "Some other value"
subprocess.Popen(["C:\\Python27\\python.exe ", ScriptAPATH, " -arg1 " , value1, " -arg2 ", value2],shell = True, stdout = subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个错误: error: argument -arg1/--arg1 is required

接下来我尝试的是将 subprocess.Popen 替换为 os.system ,如下所示:

cmd = "C:\\Python27\\python.exe scriptA.py" + " -arg1 " + value1 + " -arg2 " + value2
os.system(cmd)
Run Code Online (Sandbox Code Playgroud)

这有效,在这种情况下我可以从 ScriptA 访问参数。关于第一种情况可能出什么问题的任何指示吗?我对 python 有点陌生,所以任何形式的帮助将不胜感激

jfs*_*jfs 4

Either pass the command as a string exactly as you see it on the command-line or if you use a list then drop space characters around arguments:

from subprocess import check_output

output = check_output([r"C:\Python27\python.exe", script_path,
                       "-arg1" , value1, "-arg2", value2])
Run Code Online (Sandbox Code Playgroud)

If you leave spaces; they are wrapped with double quotes. print sys.argv in the script, to see exactly what arguments it gets.