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

shellexecute – 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 subprocess
subprocess.call([C:\Temp\a b c\Notepad.exe, C:\test.txt])

Heres a different way of doing it.

If youre 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 os
os.startfile(filepath)

Example:

import os
os.startfile(textfile.txt)

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

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

The outermost quotes are consumed by Python itself, and the Windows shell doesnt 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

Leave a Reply

Your email address will not be published. Required fields are marked *