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

前端 未结 13 1316
刺人心
刺人心 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 11:11

    Start does not support long path names and white spaces. You have to convert it to 8.3 compatible paths.

    import subprocess
    import win32api
    
    filename = "C:\\Documents and Settings\\user\\Desktop\file.avi"
    filename_short = win32api.GetShortPathName(filename)
    
    subprocess.Popen('start ' + filename_short, shell=True )
    

    The file has to exist in order to work with the API call.

    0 讨论(0)
  • 2020-11-22 11:12

    Just for completeness (it wasn't in the question), xdg-open will do the same on Linux.

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

    I prefer:

    os.startfile(path, 'open')
    

    Note that this module supports filenames that have spaces in their folders and files e.g.

    A:\abc\folder with spaces\file with-spaces.txt
    

    (python docs) 'open' does not have to be added (it is the default). The docs specifically mention that this is like double-clicking on a file's icon in Windows Explorer.

    This solution is windows only.

    0 讨论(0)
  • 2020-11-22 11:15

    on mac os you can call 'open'

    import os
    os.popen("open myfile.txt")
    

    this would open the file with TextEdit, or whatever app is set as default for this filetype

    0 讨论(0)
  • 2020-11-22 11:20

    If you have to use an heuristic method, you may consider webbrowser.
    It's standard library and despite of its name it would also try to open files:

    Note that on some platforms, trying to open a filename using this function, may work and start the operating system’s associated program. However, this is neither supported nor portable. (Reference)

    I tried this code and it worked fine in Windows 7 and Ubuntu Natty:

    import webbrowser
    webbrowser.open("path_to_file")
    

    This code also works fine in Windows XP Professional, using Internet Explorer 8.

    0 讨论(0)
  • 2020-11-22 11:21

    If you want to specify the app to open the file with on Mac OS X, use this: os.system("open -a [app name] [file name]")

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