2

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

3

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

12 Comments

Thanks! Now how would I capture output from the c program? It simply printfs multiplule lines of text?
If you read the documentation you will see that check_output returns the output of the command. docs.python.org/library/subprocess.html#subprocess.check_output
I see. so doing something like this: process = subprocess.check_output(["make","run_pci"],cwd="/home/ecorbett/hello_world_pthread") print process.communicate() Would be unnecessary/incorrect?
But back to my original question. If my C program will be running, processing data and producing output that I need to process with my python program simultaneously, will this method still work?
@NASAIntern: no, then you need to use Popen instead of check_output. Pass it stdout=subprocess.PIPE, then read from its stdout member.
|
0

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

Comments

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.