Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running a C executable from Python with command line arguments

I have a C file say, myfile.c.

Now to compile I am doing : gcc myfile.c -o myfile

So now to run this I need to do : ./myfile inputFileName > outputFileName

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Where inputFileName and outputFileName are 2 command line inputs.

Now I am trying to execute this within a python program and I am trying this below approach but it is not working properly may be due to the >

import subprocess
import sys

inputFileName = sys.argv[1];
outputFileName = sys.argv[2];

subprocess.run(['/home/dev/Desktop/myfile', inputFileName, outputFileName])

Where /home/dev/Desktop is the name of my directory and myfile is the name of the executable file.

What should I do?

>Solution :

The > that you use in your command is a shell-specific syntax for output redirection. If you want to do the same through Python, you will have to invoke the shell to do it for you, with shell=True and with a single command line (not a list).

Like this:

subprocess.run(f'/home/dev/Desktop/myfile "{inputFileName}" > "{outputFileName}"', shell=True)

If you want to do this through Python only without invoking the shell (which is what shell=True does) take a look at this other Q&A: How to redirect output with subprocess in Python?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading