Python:os.system 执行 meld 命令在 Windows 中不起作用

Python: os.system to execute meld command doesn't work in Windows

我正在 Python 中编写一个 sublime 插件。但我对 Python 语言还是很陌生。我正在使用这条线在 Python 中调用 meld:

if meld_cmd == None:
   meld_cmd = "C:\Program Files (x86)\Meld\meld\meld"
os.system('"%s" "%s" "%s" ' %(meld_cmd, source_name, dest_name))

它在 Windows 中效果不佳。 cmd window 仅闪烁一秒钟(似乎在执行某些操作)然后消失。我在 sublime 中打印出执行的字符串,然后将字符串复制到 cmd window 中并执行。它在管理员和非管理员模式下都运行良好。我尝试在执行之前添加一个暂停:

os.system('pause && "%s" "%s" "%s" ' %(meld_cmd, source_name, dest_name))

在按任意键继续...行后单击回车后,这也很好用。

不确定如何调试它以及它失败的原因是什么。

问题可能是您需要以管理员权限执行该脚本。

继续提问 How to run python script with elevated privilege on windows 以获得关于该主题的更多信息。

cmd.exe /c command 当命令以引号开头并且有两个以上的引号时,会出现解析问题。确切的规则在通过 cmd /? 提供的在线帮助文​​本中进行了解释:

If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:

    1.  If all of the following conditions are met, then quote characters
        on the command line are preserved:

        - no /S switch
        - exactly two quote characters
        - no special characters between the two quote characters,
          where special is one of: &<>()@^|
        - there are one or more whitespace characters between the
          two quote characters
        - the string between the two quote characters is the name
          of an executable file.

    2.  Otherwise, old behavior is to see if the first character is
        a quote character and if so, strip the leading character and
        remove the last quote character on the command line, preserving
        any text after the last quote character.

要解决这个问题,只需将整个命令用引号引起来,例如'""%s" "%s" "%s""' % (meld_cmd, source_name, dest_name).