Is there an platform independent equivalent of os.startfile()?

后端 未结 3 1905
迷失自我
迷失自我 2020-12-01 03:08

I want to run a program on several platforms (including Mac OS), so I try to keep it as platform independent as possible. I use Windows myself, and I have a line os.st

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 03:23

    It appears that a cross-platform file opening module does not yet exist, but you can rely on existing infrastructure of the popular systems. This snippet covers Windows, MacOS and Unix-like systems (Linux, FreeBSD, Solaris...):

    import os, sys, subprocess
    
    def open_file(filename):
        if sys.platform == "win32":
            os.startfile(filename)
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, filename])
    

提交回复
热议问题