Search code examples
pythonexeexit-code

(Python) Launching an external application and wait for the end of it


I need to write an application in Python (in linux) that launching an external exe, and waiting to the end of his running.

Here is my parameters:

Path: /home/user/docs/myapp.mat
Application: Matlab:exe

I need to send myapp.mat file to matlab.exe, and wait for the completion of the program. I need to print the exit code of the app as well in order to check if the exe has ended without any problem.

Any recommendations how to do that? I've found some examples of running exe from Python but i didn't find so far the best solution for my case.


Solution

  • You could use the subprocess module, for example like this:

    If you need the output of your programm you can use this:

    import subprocess
    
    output = subprocess.check_output(["Matlab.exe", "/home/user/docs/myapp.mat"])
    print output
    

    If you just need the exit code, you can use the call function:

    import subprocess
    
    exitcode = subprocess.call(["Matlab.exe", "/home/user/docs/myapp.mat"])
    print exitcode
    

    If you need both, the exit code and the output, you could do something like this:

    import subprocess
    
    try:
        output = subprocess.check_output(["Matlab.exe", "/home/user/docs/myapp.mat"])
        # If it doesn't fail, the exitcode equals to 0.
        print output # Prints the output.
    except subprocess.CalledProcessError as e:
        print e.returncode # Prints the exitcode.