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

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];['/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:'/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?

Leave a Reply