How do you specify what directory the python module subprocess uses to execute commands? I want to run a C program and process it's output in Python in near realtime.
I want to excute the command (this runs my makefile for my C program:
make run_pci
In:
/home/ecorbett/hello_world_pthread
I also want to process the output from the C program in Python. I'm new to Python so example code would be greatly appreciated!
Thanks, Edward
2 Answers 2
Use the cwd argument to Popen, call, check_call or check_output. E.g.
subprocess.check_output(["make", "run_pci"],
cwd="/home/ecorbett/hello_world_pthread")
Edit: ok, now I understand what you mean by "near realtime". Try
p = subprocess.Popen(["make", "run_pci"],
stdout=subprocess.PIPE,
cwd="/home/ecorbett/hello_world_pthread")
for ln in p.stdout:
# do processing
12 Comments
Popen instead of check_output. Pass it stdout=subprocess.PIPE, then read from its stdout member.Read the documentation. You can specify it with the cwd argument, otherwise it uses the current directory of the parent (i.e., the script running the subprocess).