1

I need to get information from a bash command which takes several seconds. I want the rest of program to continue until I get the returncode. I tried to do it with multiprocessing but I cant get the returncode of the subprocess alltough the console prints the correct returncode.

from multiprocessing import Process, Value
import subprocess

num = Value("d", 0.0)

class foo(object):
    def __init__(self):
        self.createProcess()

    def createProcess(self):
        p = Process(target=self.Process, args=(num,))
        p.start()
        ...Do Stuff here in parallel...

    def Process(self,n):
        somebashParam = int(n.value)
        p = subprocess.Popen("some -command"+str(somebashParam),shell=True)
        out, err = p.communicate()
        n.value = p.returncode
  1. why does the console print out the right returncode but I cant grab it?
  2. It seems strange for me to launch a subprocess in a other new Process. Is there a better way?

1 Answer 1

1

External processes automatically run in parallel. If you are only interested in the return code, you don't need any additional code:

n = 23
process = subprocess.Popen(["some", "-command", str(n)])
while process.poll() is None:
    do_something_else()
result = process.wait()
Sign up to request clarification or add additional context in comments.

5 Comments

Why do you poll the process? Wouldn't it make more sense to simply do_something_else() and then process.wait() ?
@hek2mgl: it depends on how you want to wait for the result.
What do you mean?
First of all Thank you Daniel that solved my problem. @hek2mgl In my program the rest of the the code is to be repeated until I get the result.So I have to use process.poll(). If the rest of the code only is to be executed once you can use process.wait()
I see, in that case the poll makes sense.

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.