false_azure
false_azure

Reputation: 1503

How can I execute a shell command in a child process in Python?

I need to use the multiprocessing module (rather than subprocess, as I need to use pipes) to execute a shell command as a new child process. At the moment I'm using:

p = subprocess.Popen(subprocess_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=parent_env)

where subprocess_command is a shell command (it runs a Python script with arguments) and parent_env is the current environment with an environmental variable (LD_PRELOAD) set differently. What would be the equivalent using the multiprocessing module? The child process (Python script) needs to be able to pipe back to the parent.

Upvotes: 0

Views: 2492

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113988

this will demonstrate how to get streaming output back from a Popen

file1.py

import time,os
while True:
    print "OK ?"+os.environ["LD_PRELOAD"]
    time.sleep(1)

file2.py

import os
os.environ["LD_PRELOAD"] = "5"
p = subprocess.Popen(subprocess_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ)
p.start()
for line in iter(p.stdout.readline, b''):
   print line
   time.sleep(0.6)

Upvotes: 1

Related Questions