Search code examples
pythonpython-3.xos.execl

How to use os.execve in Python


I just started learning Python today and couldn't find a good example online to help me understand os.execve(path, args, env) properly.

How do I use this method (os.execve) to achieve the following task in Python 3.4?
Execute an external command (this command is not some windows command like mkdir, cd... It's a custom command), its location is C:\blah and it takes 5 command line arguments.

Any simpler example of using this command would be much appreciated.


Solution

  • You want to use subprocess:

    import subprocess
    subprocess.check_call(["C:\my program.exe", "all", "my", "args"])
    

    os.exec* replaces the current program with another one. It has is uses, but its usually not what you want.

    Note that there are several variants here:

    1. call just calls the program.
    2. check_call calls the program and throws an exception if it fails.
    3. check_output calls the program, throws an exception if it fails, and returns the output of the program.

    More advanced use cases can be handled by subprocess.Popen objects.