传递参数给从subprocess.Popen

问题描述:

从另一个脚本(scriptB)内(说SCRIPTA)使用subprocess.Popen功能在Python 3

传递参数给从subprocess.Popen

,我希望该脚本argparse

我想打电话给使用python 2脚本调用实现其期望像下面两个参数的东西的方法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 

现在,我使用的子流程如下调用上面的脚本: ScriptB:

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

但是,我得到一个错误: 错误:参数-arg1/- ARG1需要

我想下一步是使用os.system类似下面来代替subprocess.Popen:

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

这个工程脚本和我能够在这种情况下访问ScriptA的参数。 任何关于在第一种情况下可能出错的指针?我是一种新的Python,所以任何形式的帮助,将不胜感激

或者传递命令作为一个字符串,就像你在命令行上看到的一样,或者如果你使用一个列表然后在参数周围放置空格字符

from subprocess import check_output 

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

如果您留下空格;它们用双引号包裹。脚本中的print sys.argv,以准确查看它获取的参数。

+0

谢谢!我错过了这一点。删除它的工作空间后。 – Abhi