0

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];

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?

4

2 Answers 2

1

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?

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

Comments

1

You can open the output file in Python, and pass the file object to subprocess.run().

import subprocess
import sys

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

with open(outputFileName, "w") as out:
    subprocess.run(['/home/dev/Desktop/myfile', inputFileName], stdout=out)

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.