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

physics_for_all
  • 2,193
  • 4
  • 19
  • 20
  • I just realize (after writing my answer), what do you mean by "it's not giving me the proper answer" ? – NiziL Sep 06 '15 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. – physics_for_all Sep 06 '15 at 10:20

1 Answers1

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:

Community
  • 1
  • 1
NiziL
  • 5,068
  • 23
  • 33
  • Could you tell me how can I store values from this C code output? Simply `results=subprocess.call...' is not saving values in results. – physics_for_all Sep 13 '15 at 12:31