How to Run External Executable Using Python

Running an outside program (executable) in Python?

Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.system, subprocess methods, or whatever...

If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?

Running an external executable in Python interactively

In addition to the errors in your C program that have been mentioned, you are calling .communicate() more than once. .communicate() is single-use function that sends all of its data to the subprocess and waits for the subprocess to exit.

If you must use .communicate(), use it this way:

com = ris.communicate(input='bye\nq\n')

Alternatively, you can use ris.stdin.write(), like so:

import subprocess
from subprocess import PIPE, STDOUT

output = open("test.out","w")
ris = subprocess.Popen(executable="/tmp/test.exe", args="", stdin=PIPE,
stdout=output, stderr=STDOUT,
universal_newlines=True, shell=True)
com = ris.stdin.write('bye\n')
com = ris.stdin.write('q\n')
ris.stdin.flush()
output.close()
ris.wait()

How do I execute a program or call a system command?

Use the subprocess module in the standard library:

import subprocess
subprocess.run(["ls", "-l"])

The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...).

Even the documentation for os.system recommends using subprocess instead:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])

Opening external program in python

I've found a solution for my case, I think there is a problem with Flask upload module, my C++ program was on the same path as my uploaded files from flask, so when I changed the program path and used Windows command prompt to start the program, everything worked like a charm.



Related Topics



Leave a reply



Submit