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())

1
  • Since you're running Python files, you could consider using the multiprocessing module instead if it suits you. Commented Sep 5, 2013 at 17:49

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

You probably want to save the result of subprocess.Popen: processes = [subprocess.Popen(option) for option in options]
If 'python' is always used, you don't need to keep repeating it in the list.
0
exec("p1 = subprocess.Popen('python','hello.py')")

Note that exec executes statements, while eval evaulates expressions.

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.

1 Comment

... also note that execing random strings is a very bad practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.