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?

Dev
  • 576
  • 3
  • 14
  • You should be a able to directly run the C file from python as a module. Please take a [look at this stackoverflow](https://stackoverflow.com/questions/18762621/can-we-use-c-code-in-python) question which can lead to this [Python documentation](https://docs.python.org/3.3/extending/index.html.). – Kevin Hernandez Nov 08 '21 at 16:45
  • Is the author perhaps missing the '>' in their subprocess command? – Aurgho Bhattacharjee Nov 08 '21 at 16:46
  • `> outputFileName` is ouput redirection. It's something your shell is doing - it's not an argument to your program. To reproduce that with python, look at https://stackoverflow.com/questions/4965159/how-to-redirect-output-with-subprocess-in-python – rdas Nov 08 '21 at 16:46
  • Does this answer your question? [How to make a call to an executable from Python script?](https://stackoverflow.com/questions/2473655/how-to-make-a-call-to-an-executable-from-python-script) – homer Nov 08 '21 at 16:48

2 Answers2

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?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
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)
Barmar
  • 741,623
  • 53
  • 500
  • 612