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

pythonshellexecute

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");
raw_input();

Then it fails with the following error:

'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.

If I escape the program with quotes:

import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe"');
raw_input();

Then it works. However, if I add a parameter, it stops working again:

import os;
os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"');
raw_input();

What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.

Also note, moving the program to a non-spaced path is not an option either.


This does not work either:

import os;
os.system("'C:\\Temp\\a b c\\Notepad.exe'");
raw_input();

Note the swapped single/double quotes.

With or without a parameter to Notepad here, it fails with the error message

The filename, directory name, or volume label syntax is incorrect.

Best Answer

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