I have a Thumbnail_Handler class which has this method, which is supposed to run a file with Adobe Photoshop:
def abrir_photoshop(self):
target = self.path_copia
norm_path = os.path.normpath(r"C:\Program FilesAdobeAdobe Photoshop 2021\Photoshop.exe")
cmd = '"' + norm_path + '" "' + target + '"'
print(cmd)
proc = os.system(cmd)
for filename in os.listdir(PATH_THUMBNAIL + self.nome_playlist):
if re.match(self.id_video_original + '.*.png', filename):
self.set_status(status_thumb.PNG_EXPORTADO)
return filename
The command that is printed on the print(cmd)
line is this: "C:Program FilesAdobeAdobe Photoshop 2021Photoshop.exe" "C:\Users\adassaDesktop\Thiago\Youtube Almir\PSDsNão Temas - 8PydQGvI0E4.psd"
If I simply copy this, and paste to Powershell, or to the common Windows shell, it works as intended, but when python runs the command, I get: 'C:Program' is not recognized as a command.
I reckon this means that the command is going without the double quotes. Why does this happen, and how can I correct it?
3
Answers
mslex.quote
from mslex package looks like a solution to your case.shelx.quote
exits for same task on unix-like systems.When i tried a path similar to yours it only tried to run ‘C:Program’ if the path did not existed, otherwise it worked fine, but since you said it worked when you manually copied the path maybe it’s something else.
I found two ways to force the proper path:
Solution 1: Quote only part of the path
Solution 2: Escape the space with a caret
os.system calls [MS.Docs]: system, _wsystem, which in turn calls the command interpreter (cmd).
When system invokes cmd (I didn’t see any official documentation to support this, so I’m posting a screenshot to support my statement), it passes the /c argument:
According to [MS.Docs]: cmd or
cmd /?
(emphasis is mine):So, when passing a quoted executable, followed by a quoted argument, cmd alters the command yielding the weird results you’re seeing.
I don’t know if this behavior could be avoided, (maybe symlinks with no spaces in their path could be created and passed to os.system), but that would be just a lame workaround (gainarie). The common sense approach would be to use [Python.Docs]: subprocess – Subprocess management.
code00.py:
Output:
As seen:
In the 1st run (os.system), the variants that worked were (quoted executable):
In the 2nd one (subprocess), everything worked smoothly (and Acrobat Reader had no problem opening the files – you’ll have to trust me on this one 🙂 ), no additional quoting required at all