Python, subprocess, filepath white spaces and famous 'C:/Program' is not recognized as an internal or external command
Solution 1
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. ;)
Solution 2
Either use:
cmd = '"C:\\Program Files (x86)\\iTunes\\iTunes.exe"'
or
cmd = r'"C:\Program Files (x86)\iTunesr\iTunes.exe"'
Solution 3
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'
Related videos on Youtube
alphanumeric
Updated on June 13, 2022Comments
-
alphanumeric almost 2 years
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.
-
Tim Pierce over 10 yearsAre you sure that the problem is with the white space and not with the backslashes? Try
cmd = "C:\\Program Files (x86)\\iTunes\\iTunes.exe"
.
-
-
alphanumeric over 10 yearscmd = '"C:\\Program Files (x86)\\iTunes\\iTunes.exe"' won't work.
-
alphanumeric over 10 yearsI am not sure about r' "c:\\Program Files\\executable.exe '
-
Ryan Haining over 10 years@Sputnix 1) the first won't work or doesn't work? 2) so try it.
-
Steve Barnes over 10 yearsWindows doesn't support unquoted and un-escaped spaces. :(
-
Max Noel over 10 yearsSo what, does Popen always use the shell (or whatever the equivalent is) to open external programs on Windows, even with
shell=False
? In that case, the fix is easy: just add quotes.cmd = '"C:/Program Files (x86)/iTunes/iTunes.exe"'
-
Steve Barnes over 10 yearsWithout a windows machine to hand I was reluctant to suggest this without testing as it is Python for Windows that supports forward slashes in file paths rather than windows and I suspected that the nested quotes could possibly defeat this.