Python, subprocess, filepath white spaces and famous 'C:/Program' is not recognized as an internal or external command

StackOverflow https://stackoverflow.com/questions/20456299

  •  30-08-2022
  •  | 
  •  

Frage

Enclosing a full file path inside the "" quotes does not make it work.

cmd = "C:\Program Files (x86)\iTunes\iTunes.exe"

subprocess.popen throws an error of not being able to find an executable if there is a white space in a file-path to be executed.

A while ago I was able to find a solution which involved a use of some weird symbols or their combination... Unfortunately I can't locate a code with that example. I would appreciate if someone would point me in a right direction. Thanks in advance.

War es hilfreich?

Lösung

Backslashes in strings trigger escape characters. Since Windows fully supports the use of the forward slash as a path separator, just do that:

cmd = "C:/Program Files (x86)/iTunes/iTunes.exe"

No need to fiddle around with \\ or raw strings. ;)

Andere Tipps

Either use:

cmd = '"C:\\Program Files (x86)\\iTunes\\iTunes.exe"'

or

cmd = r'"C:\Program Files (x86)\iTunesr\iTunes.exe"'

the file path:

file_path= 'E:\\te st.py'

then you should:

file_path = '"E:\\te st.py"'

then it works, my Main.py as show blow:

import subprocess

doc = '"E:\\te st.py"'

p = subprocess.Popen ('python ' + doc , stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
output = p.communicate()
print output

and the te st.py is:

print 'hello world'

Try to escape your cmd line: replace

"\" 

by

"\\"

And

' ' 

(space) by

'\ ' 

(backslash + space).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top