Dennis
Dennis

Reputation: 21

Execute Bash Command in new Process

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?

Upvotes: 1

Views: 559

Answers (1)

Daniel
Daniel

Reputation: 42758

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

Upvotes: 1

Related Questions