Skip to content Skip to sidebar Skip to footer

How Do I Execute A Program From Python? Os.system Fails Due To Spaces In Path

I have a Python script that needs to execute an external program, but for some reason fails. If I have the following script: import os; os.system('C:\\Temp\\a b c\\Notepad.exe'); r

Solution 1:

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'])

Solution 2:

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.

Solution 3:

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

Solution 4:

At least in Windows 7 and Python 3.1, os.system in Windows wants the command line double-quoted if there are spaces in path to the command. For example:

TheCommand= '\"\"C:\\Temp\\a b c\\Notepad.exe\"\"'
  os.system(TheCommand)

A real-world example that was stumping me was cloning a drive in VirtualBox. The subprocess.call solution above didn't work because of some access rights issue, but when I double-quoted the command, os.system became happy:

TheCommand= '\"\"C:\\Program Files\\Sun\\VirtualBox\\VBoxManage.exe\" ' \
                 + ' clonehd \"' + OrigFile + '\"\"' + NewFile + '\"\"'
  os.system(TheCommand)

Solution 5:

For python >= 3.5 subprocess.run should be used in place of subprocess.call

https://docs.python.org/3/library/subprocess.html#older-high-level-api

import subprocess
subprocess.run(['notepad.exe', 'test.txt'])

Post a Comment for "How Do I Execute A Program From Python? Os.system Fails Due To Spaces In Path"