How do I execute a program from Python? os.system fails due to spaces in path How do I execute a program from Python? os.system fails due to spaces in path python python

How do I execute a program from Python? os.system fails due to spaces in path


subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

import subprocesssubprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])


Here's a different way of doing it.

If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.

filepath = 'textfile.txt'import osos.startfile(filepath)

Example:

import osos.startfile('textfile.txt')

This will open textfile.txt with Notepad if Notepad is associated with .txt files.


The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes. Python will convert forward-slashed to backslashes on Windows, so you can use

os.system('"C://Temp/a b c/Notepad.exe"')

The ' is consumed by Python, which then passes "C://Temp/a b c/Notepad.exe" (as a Windows path, no double-backslashes needed) to CMD.EXE