0

I want to call c program from python. My c program required several input arguments (for calculating several properties of image) for example, image name, central position (x_c, y_c), area, radii etc. So these input arguments I am calculating in python and then want to pass it to the c program. In python code, I need to first get image for which I need to calculate x_c, y_c, area etc. So in python script I used,

file=sys.argv[1] # here I am passing the name of input image
***
calculate x_c, y_c, area, etc...
***

Now in the same python script, I want to pass above calculated values as well as image name to the c program. In python, image name is in string and calculated values are in float, so how can I pass all to the c program using subprocess call or os.system? So far I tried,

os.system("cshift "+str(file)+' '+str(x_c) +' '+str(y_c)+' '+str(area))

but its not giving me the proper answer.

Thanks in advance,

Cheers,

-Viral

2
  • I just realize (after writing my answer), what do you mean by "it's not giving me the proper answer" ? Commented Sep 6, 2015 at 10:10
  • It means, without calculating properties, c program was giving just zero value. C program was not taking arguments properly. Now it works with your suggestions. Thanks. Commented Sep 6, 2015 at 10:20

1 Answer 1

1

From the os.system() documentation:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

So subprocess.call(['cshift', str(file), str(x_c), str(y_c), str(area)]) should do the trick.

If you want to read the output of your C code, you have to use a Popen object with stdout=subprocess.PIPE.

process = subprocess.Popen(['cshift', str(file), str(x_c), str(y_c), str(area)], 
                           stdout=subprocess.PIPE)
output = process.stdout.read()

On a side note, I recommend you to take a look at argparse or begins to handle the arguments of your python script.

Related question:

Sign up to request clarification or add additional context in comments.

1 Comment

Could you tell me how can I store values from this C code output? Simply `results=subprocess.call...' is not saving values in results.

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.