Lasse V. Karlsen Lasse V. Karlsen - 3 years ago 243
Python Question

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

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"');

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"');

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.

Edit This does not work either:

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

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.

Answer Source 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['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download