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

后端 未结 10 877
一生所求
一生所求 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 09:07

    subprocess.call will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e.

    import subprocess
    subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])
    
    0 讨论(0)
  • 2020-11-22 09:08
    import win32api # if active state python is installed or install pywin32 package seperately
    
    try: win32api.WinExec('NOTEPAD.exe') # Works seamlessly
    except: pass
    
    0 讨论(0)
  • 2020-11-22 09:12

    The outermost quotes are consumed by Python itself, and the Windows shell doesn't see it. As mentioned above, Windows only understands double-quotes. Python will convert forward-slashed to backslashes on Windows, so you can use

    os.system('"C://Temp/a b c/Notepad.exe"')
    

    The ' is consumed by Python, which then passes "C://Temp/a b c/Notepad.exe" (as a Windows path, no double-backslashes needed) to CMD.EXE

    0 讨论(0)
  • 2020-11-22 09:14

    Here's a different way of doing it.

    If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.

    filepath = 'textfile.txt'
    import os
    os.startfile(filepath)
    

    Example:

    import os
    os.startfile('textfile.txt')
    

    This will open textfile.txt with Notepad if Notepad is associated with .txt files.

    0 讨论(0)
提交回复
热议问题