1

I'm currently creating a script that'll loop run a set of Subprocess, and then wait for all the subprocess to finish. I have to add variables in to the subprocess before running them, so I was thinking of writing it as a string, and then converting the string to a command? Would something like that exist?

For example, I have these stringss:

"p1 = subprocess.Popen('python','hello.py')"
"p2 = subprocess.Popen('python','hello2.py')"

How would I execute it to be able to call p1 or p2 later on in the script? (E.g p1.wait())

4

2 回答 2

6

使用字符串是一个坏主意,我会使用一个列表:

options = [('python','hello.py'), ('python','hello2.py')]
for option in options:
    process = subprocess.Popen(option) 
    #do something here
于 2013-09-05T16:58:34.527 回答
0
exec("p1 = subprocess.Popen('python','hello.py')")

请注意,exec 执行语句,而eval 评估表达式。

但我同意另一个答案,如果可以的话,最好以不同的方式来做这件事。您绝对不应该做的一件事是执行您不知道其来源的任意字符串,例如它们是否来自用户。

于 2013-09-05T16:57:44.360 回答