Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用N个参数运行subprocess.popen_Python_Subprocess_Dynamic Programming_Popen - Fatal编程技术网

Python 使用N个参数运行subprocess.popen

Python 使用N个参数运行subprocess.popen,python,subprocess,dynamic-programming,popen,Python,Subprocess,Dynamic Programming,Popen,subprocess.popen在后台调用进程 我调用php进程,有时调用python进程,每次参数都可能不同。我想写一个函数,并在其中传递参数列表。该函数将根据参数执行进程 所以我现在做的是,写在下面,实际上这是一个糟糕的方式,我不想写这么多行 def RunBackGroundProcess(args): # args is an array of params # index 0 - command - php/python or anyother

subprocess.popen在后台调用进程

我调用php进程,有时调用python进程,每次参数都可能不同。我想写一个函数,并在其中传递参数列表。该函数将根据参数执行进程

所以我现在做的是,写在下面,实际上这是一个糟糕的方式,我不想写这么多行

    def RunBackGroundProcess(args):
        # args is an array of params
        # index 0 - command - php/python or anyother
        # index 1 - filename - that you want to run. Specify fullpath if required
        # index 2 - param_1
        # index 3 - param_2
        # index N - param_N

        if(len(args) == 2):
            subprocess.Popen([args[0], args[1], args[2]])

        if(len(args) == 3):
            subprocess.Popen([args[0], args[1], args[2], args[3]])

        if(len(args) == 4):
            subprocess.Popen([args[0], args[1], args[2], args[3], args[4]])
如果我有10个论点或15个论点呢?这不是个好办法,对吧?
请帮助我以较小的行编写此代码

您正在以列表的形式传递参数,因此subprocess.Popen()不需要检查参数长度,您可以按原样传递给subprocess

def RunBackGroundProcess(args):
    subprocess.Popen(args)

这将起作用

子流程。Popen(list(args))
?@mgilson正在用
列表
包装它,是否需要?我假设它已经是一个列表(虽然它确实说数组似乎不太可能)@sberry——这取决于输入以及您希望接口的偏执/灵活程度。。。如果输入总是要求是一个
序列
,则不需要,您绝对不需要将其包装在
列表
中。话虽如此,如果您试图编写框架式的东西,因此也希望接受任意的iterables(我假设您没有传递生成足够元素的生成器,这些元素会对
子流程产生问题)
args
的大小是否正确?为什么不干脆
Popen(args)
?或者可能使用shell=True并传入字符串而不是列表…子流程。Popen('my_script.py param1 param2',shell=True,stdout=PIPE,stderr=PIPE)