1

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.

KurzedMetal
  • 12,540
  • 6
  • 39
  • 65
Dhiwakar Ravikumar
  • 1,983
  • 2
  • 21
  • 36
  • 2
    The os.exec* function will stop your program from executing. Is that really what you want? – Winston Ewert Sep 15 '14 at 12:14
  • fine how to exexute the external command without stopping my program ? – Dhiwakar Ravikumar Sep 15 '14 at 12:29
  • "I just started learning Python today and couldn't find a good example online to help me understand `os.execve(path, args, env)` properly.". Python has a superb online documentation, if you can find it, you are doing something wrong... [Link to os.execve documentation](https://docs.python.org/2/library/os.html#os.execve) – KurzedMetal Sep 15 '14 at 13:13
  • @KurzedMetal The os.exec* has a horrible documentation. Which type should the `args` be? What should be the `env`? If the documentation bothered to give an example, perhaps I wouldn't be banging the wall with an `AttributeError: 'str' object has no attribute 'keys'` error right now. – Dr__Soul Dec 25 '20 at 08:04
  • UPD. Ok, the following is a working example to execute a python script from python: `os.execv('./myscript.py', ['any_arbitrary_tag', '--my-argument', '--another-argument 42'])` The `env` means the PATH variable of current environment and can be retrieved by `os.environ.get('PATH')` – Dr__Soul Dec 25 '20 at 08:24

1 Answers1

3

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.

Winston Ewert
  • 44,070
  • 10
  • 68
  • 83