How do I execute a program from Python? os.system fails due to spaces in path

后端 未结 10 992
一生所求
一生所求 2020-11-22 08:19

I have a Python script that needs to execute an external program, but for some reason fails.

If I have the following script:

import os;
os.system(\"C         


        
10条回答
  •  误落风尘
    2020-11-22 08:57

    At least in Windows 7 and Python 3.1, os.system in Windows wants the command line double-quoted if there are spaces in path to the command. For example:

      TheCommand = '\"\"C:\\Temp\\a b c\\Notepad.exe\"\"'
      os.system(TheCommand)
    

    A real-world example that was stumping me was cloning a drive in VirtualBox. The subprocess.call solution above didn't work because of some access rights issue, but when I double-quoted the command, os.system became happy:

      TheCommand = '\"\"C:\\Program Files\\Sun\\VirtualBox\\VBoxManage.exe\" ' \
                     + ' clonehd \"' + OrigFile + '\" \"' + NewFile + '\"\"'
      os.system(TheCommand)
    

提交回复
热议问题