I need to call an executable that is in the same directory as a running python script . I need to know how I can call it through a command from my script with some parameters.
In the Windows command line, I do this:
miejecutable -p1 datos
Preferably if there is a way to run it in both Python 2 and 3.
Answer translated from: https://stackoverflow.com/a/89243/255257
Use the sobprocess module in stdlib:
edition
It is worth mentioning that
call
it returns the exit code of the executed program or command, which you can collect as follows:Another feature is that you can make the call through the system shell, passing the shell=True parameter, like so:
The advantage of using subprocess versus system is that it is more flexible (you can get both stdout and stderr, the "real" exit code, better error handling, etc.).
os.system is deprecated, or will be soon:
https://docs.python.org/2/library/subprocess.html#replacing-older-functions-with-the-subprocess-module
For one-run scripts, or quick and dirty solutions,
os.system
it's enough:It seems simple, you have your script as follows:
I'll explain line by line: In line 1, we import the operating system module. Line 2 is a comment and line 3 is where you already need to run the command, the function
os.system
gives us a system line on which we can run commands.Line 4 saves the result of the command, and in line 5 we compare, if the output of the command is 0, it means that the system executed the command without problems, in line 6 we handle in case the system has had an error .
If you look at line 3, we tell the system line that, everything that the command throws, it empties it in the file exit_del_command.log, in order to have details of what could have failed.
Hope this can help you.
EDIT: I forgot what @jachguate commented, that os.system is about to be replaced in the following versions of Python, so the use of
subprocess.call
EDIT 2: If you are going to use
subprocess.call
remember to also add the parametershell=True
, leaving your call:So that you avoid problems that it cannot find files that depend on the shell/line of the current system where you are.