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

后端 未结 10 876
一生所求
一生所求 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:50

    Suppose we want to run your Django web server (in Linux) that there is space between your path (path='/home/<you>/<first-path-section> <second-path-section>'), so do the following:

    import subprocess
    
    args = ['{}/manage.py'.format('/home/<you>/<first-path-section> <second-path-section>'), 'runserver']
    res = subprocess.Popen(args, stdout=subprocess.PIPE)
    output, error_ = res.communicate()
    
    if not error_:
        print(output)
    else:
        print(error_)
    

    [Note]:

    • Do not forget accessing permission: chmod 755 -R <'yor path'>
    • manage.py is exceutable: chmod +x manage.py
    0 讨论(0)
  • 2020-11-22 08:52

    I suspect it's the same problem as when you use shortcuts in Windows... Try this:

    import os;
    os.system("\"C:\\Temp\\a b c\\Notepad.exe\" C:\\test.txt");
    
    0 讨论(0)
  • 2020-11-22 08:56

    No need for sub-process, It can be simply achieved by

    GitPath="C:\\Program Files\\Git\\git-bash.exe"# Application File Path in mycase its GITBASH
    os.startfile(GitPath)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-22 09:00

    For python >= 3.5 subprocess.run should be used in place of subprocess.call

    https://docs.python.org/3/library/subprocess.html#older-high-level-api

    import subprocess
    subprocess.run(['notepad.exe', 'test.txt'])
    
    0 讨论(0)
  • 2020-11-22 09:06

    For Python 3.7, use subprocess.call. Use raw string to simplify the Windows paths:

    import subprocess
    subprocess.call([r'C:\Temp\Example\Notepad.exe', 'C:\test.txt'])
    
    0 讨论(0)
提交回复
热议问题