Python subprocess.Popen:如何将列表作为参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19683779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:21:47  来源:igfitidea点击:

subprocess.Popen : how to pass a list as argument

pythonsubprocesspopen

提问by Serge

I just need a hint on how to do things properly.

我只需要一个关于如何正确做事的提示。

Say I have a script called script.py which uses a list of names as argument ["name1", "name2", etc. ].

假设我有一个名为 script.py 的脚本,它使用名称列表作为参数 ["name1"、"name2" 等]。

I want to call this script from another script using the subprocess module. So what I would like to do is the following :

我想使用 subprocess 模块从另一个脚本调用这个脚本。所以我想做的是以下内容:

myList = ["name1", "name2", "name3"]
subprocess.Popen(["python", "script.py", myList])

Of course that doesn't work because the subprocess.Popen method requires a list of strings as arguments. So I considered doing the following :

当然这不起作用,因为 subprocess.Popen 方法需要一个字符串列表作为参数。所以我考虑做以下事情:

subprocess.Popen(["python", "script.py", str(myList)])

Now the process starts but it doesn't work because it has a string as argument and not a list. How should I fix that properly?

现在这个过程开始了,但它不起作用,因为它有一个字符串作为参数而不是一个列表。我应该如何正确解决这个问题?

采纳答案by falsetru

Concatenate them using +operator.

使用+运算符连接它们。

myList = ["name1", "name2", "name3"]
subprocess.Popen(["python", "script.py"] + myList)

BTW, if you want use same python program, replace "python"with sys.executable.

顺便说一句,如果您想使用相同的 python 程序,请替换"python"sys.executable.

回答by Serge

Thanks for the quick answer falsetru. It doesn't work directly but I understand how to do. You're suggestion is equivalent to doing :

感谢您的快速回答 falsetru。它不能直接工作,但我知道该怎么做。你的建议相当于做:

subprocess.Popen(["Python","script.py","name1","name2","name3"])

Where I have 3 arguments that are the strings contained in my original list.

我有 3 个参数,它们是原始列表中包含的字符串。

All I need to do in my script.py file is to build a new list from each argument received by doing the following :

我需要在我的 script.py 文件中做的就是从通过执行以下操作收到的每个参数构建一个新列表:

myList = sys.argv[1:]

myList is now the same than the one I had initially!

myList 现在与我最初拥有的相同!

["name1","name2","name3"]

Don't know why I didn't think about it earlier!

不知道为什么我没有早点考虑!