简体   繁体   English

Python-将字符串转换为命令

[英]Python - Convert string to command

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? 我将如何执行它以便稍后在脚本中调用p1或p2? (Eg p1.wait()) (例如p1.wait())

Using strings is a bad idea, I'd use a list: 使用字符串是个坏主意,我会使用一个列表:

options = [('python','hello.py'), ('python','hello2.py')]
for option in options:
    process = subprocess.Popen(option) 
    #do something here
exec("p1 = subprocess.Popen('python','hello.py')")

Note that exec executes statements, while eval evaulates expressions. 请注意, exec 执行语句,而eval 撤消表达式。

But I agree with the other answer that it's better to do this in a different way if you can. 但我同意另一个答案,即如果可以的话,最好以其他方式进行此操作。 One thing you should definitely never do is execute arbitrary strings whose source you don't know, for instance if they could come from a user. 您绝对不应该做的一件事就是执行您不知道其来源的任意字符串,例如,如果它们可能来自用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM