Running Executables That Include Metacharacters
Friday November 21, 2008
When calling an external program from within Python, one is oft bound by the naming conventions used in developing the other program. It is bad form to use metacharacters in the base name of an executable, but this does not stop it from being done. If the program is not needed elsewhere, one can rename it, of course. But if there is any doubt, best to leave it as it is and work around it. You can do that by escaping the metacharacter in the same way one would handle a regular expression.
Having imported the
Having imported the
os module, one can pass a system call with os.system('') . However, one will run into problems if a metacharacter is in the name of the executable. For example, let's say we saved the code from the recent Python and Tkinter guide to 'hello&tk.py'. If we wanted to call it from within Python's interpreter or another program, we need to escape the metacharacter. Consider:
>>> import os
>>> os.system('/path/to/program/hello\&tk.py')
0
>>>
If the executable is not in the path of your Python interpreter, you will need to use the absolute path, starting from the root or base of the directory tree. While the program is being executed, the Python interpreter will hang until the external program is run. On a Linux installation (or Unix-derivative), one can background the process using a trailing (and unescaped) ampersand (Windows users can try the subprocess module). If the process executes cleanly, Python returns 0.