Open document with default OS application in Python, both in Windows and Mac OS

前端 未结 13 1599
刺人心
刺人心 2020-11-22 10:36

I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double-click on the do

13条回答
  •  醉梦人生
    2020-11-22 10:59

    If you want to go the subprocess.call() way, it should look like this on Windows:

    import subprocess
    subprocess.call(('cmd', '/C', 'start', '', FILE_NAME))
    

    You can't just use:

    subprocess.call(('start', FILE_NAME))
    

    because start is not an executable but a command of the cmd.exe program. This works:

    subprocess.call(('cmd', '/C', 'start', FILE_NAME))
    

    but only if there are no spaces in the FILE_NAME.

    While subprocess.call method enquotes the parameters properly, the start command has a rather strange syntax, where:

    start notes.txt
    

    does something else than:

    start "notes.txt"
    

    The first quoted string should set the title of the window. To make it work with spaces, we have to do:

    start "" "my notes.txt"
    

    which is what the code on top does.

提交回复
热议问题