subprocess.Popen:如何将列表作为参数传递 [英] subprocess.Popen : how to pass a list as argument

查看:837
本文介绍了subprocess.Popen:如何将列表作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要提示如何正确做事.

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

说我有一个名为script.py的脚本,该脚本使用名称列表作为参数["name1","name2"等.].

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

我想使用子流程模块从另一个脚本中调用此脚本.所以我想做的是以下事情:

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

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

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

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(["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?

推荐答案

使用+运算符将它们连接起来.

Concatenate them using + operator.

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

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

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

这篇关于subprocess.Popen:如何将列表作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆