How to Execute a Program from Python? Os.System Fails Due to Spaces in Path

os.system to invoke an exe which lies in a dir whose name contains whitespace

Putting quotes around the path will work:

file = 'C:\\Exe\\First Version\\filename.exe'
os.system('"' + file + '"')

but a better solution is to use the subprocess module instead:

import subprocess
file = 'C:\\Exe\\First Version\\filename.exe'
subprocess.call([file])

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

os.system with spaces in path

You almost had it a couple of times. The problem is that you either need to put double backslashes, since backslash is the escape character in Python strings, or use raw strings with the r prefix. In either case, though, you must have a backslash after C:, and quotes around the portion of the name containing spaces. Any of the following examples should work:

cmd = 'C:\\"Program Files\\OpenSCAD\\openscad.exe" -o block0.stl block0.scad'
cmd = r'C:\"Program Files\OpenSCAD\openscad.exe" -o block0.stl block0.scad'
cmd = "\"C:\\Program Files\\OpenSCAD\\openscad.exe\" -o block0.stl block0.scad"
cmd = r'"C:\Program Files\OpenSCAD\openscad.exe" -o block0.stl block0.scad'

Notice that you won't be able to use double quotes and a raw Python string because you won't be able to escape the double quotes and the path in the string.

Execute a Windows path with spaces in Python

The first argument after start is the name of the newly created command prompt window, and the second and third should be the path to the application and its parameters, respectively.

start "" "c:\path with spaces\app.exe" param1 "param with spaces"

If you want to use os.system, you could try:

norm_path = os.path.normpath("{0}://courses/subjects/{1}/classes/{2}".format (drive, subject, class_name))
os.system('start "" "' + norm_path + '"')

But I would probably use os.startfile:

norm_path = os.path.normpath("{0}://courses/subjects/{1}/classes/{2}".format (drive, subject, class_name))
os.startfile( norm_path )

Please note: you should not use a variable named class.

Why does os.system recognise space in a path when a filename exists but need spaces escaped to give a correct error when a file doesn't exist?

That's simply because os.system is effectively system() (as noted in the addendum to the question - specifically the wide char variant _wsystem, but it is effectively identical as per documentation), which runs commands as cmd /C command. Putting this exact setup into a cmd.exe:

C:\Users\User>cmd /C "C:\Program Files\Windows NT\Accessories\wordpad.exe"

C:\Users\User>cmd /C "C:\Program Files\Windows NT\Accessories\zordpad.exe"
'C:\Program' is not recognized as an internal or external command,
operable program or batch file.

The message is derived as is from directly via system() calling cmd /C, and not a fault in Python. This can be proven by changing the relevant environment variable COMSPEC in a Python interactive shell to something that doesn't expect the /c flag (e.g. the Python interpreter):

>>> import os, sys
>>> os.environ['COMSPEC']
'C:\\Windows\\system32\\cmd.exe'
>>> os.environ['COMSPEC'] = sys.executable
>>> os.system('print')
C:\Users\User\AppData\Local\Programs\Python\Python35-32\python.exe: can't open
file '/c': [Errno 2] No such file or directory
2
>>>

Note the attempt by Python to execute /c as it was the first argument passed to it through os.system, indicating that system() passes /c first before the rest of the command.

Now as to how to workaround this, this post on Super User suggested using double quotes, so take that advice and see (with COMSPEC restored; e.g. new Python interactive console):

>>> os.system(r'""C:\Program Files\Windows NT\Accessories\zordpad.exe""')
'"C:\Program Files\Windows NT\Accessories\zordpad.exe"' is not recognized as an
internal or external command,
operable program or batch file.
1
>>> os.system(r'""C:\Program Files\Windows NT\Accessories\wordpad.exe""')
0
>>>

Now the error message is reported correctly on the missing executable, while wordpad.exe still gets executed as expected.

Executing command line from python that contains spaces

Like the os.system documentation already tells you, a better solution altogether is to use subprocess instead.

subprocess.run([
r"C:\Program Files\PTGui\ptgui.exe",
"-batch",
r"C:\Users\mw4168\OneDrive\Desktop\PTGui Tests\3 rows\panorama.pts"])

The string you created also lacked spaces between the indvidual arguments; but letting Python pass the arguments to the OS instead also gives you more control over quoting etc.

How do I execute a program from python? os.system fails

os.system has some serious drawbacks, especially with space in filenames and w.r.t. security. I suggest you look into the subprocess module and particularly subprocess.check_call, which is much more powerful. You could then do e.g.

import subprocess
subprocess.check_call(["c:\\fe re\\python.exe", "program", etcetc...])

Of course, make sure to take great care not to have user-determined variables in these calls unless the user is already running the script herself from the command line with the same privileges.

Use os.system to launch executable from path assigned to a variable?

Nowadays, you should use the standard libraries subprocess module to do such tasks.

Also, you should always use context managers with files. These handle automical closing and exception handling.

What might also be a problem, is that readlines() will return all lines in the file as a list but with endline character.
Use f.read().splitlines() to remove the endline or call .strip() on the individual lines.

putting it together:

import subprocess as sp

with open('config.txt') as config:
lines = config.read().splitlines()

appone = lines[0]

def launch_appone():
sp.run([appone])

Edit: also the python docs mention that os.system should not be used anymore

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

https://docs.python.org/3/library/os.html#os.system

Python error for space in path

You can make it working by using r.

E.g. :

import os
cmd =r'"C:\Program Files (x86)\Java\jre7\bin\java.exe"'
os.system(cmd)

Am I using os.system correctly? My application won't open anymore

I figured it out. For some reason, os.system stopped working consistently and subprocess.run or subprocess.call didn't work. I switched my command to use os.startfile instead and it started to work properly.

Here's the end result:

os.startfile(r"C:\Users\red\Desktop\Test UI")


Related Topics



Leave a reply



Submit