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 document icon in Explorer or Finder. What is the best way to do this in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
I prefer:
Note that this module supports filenames that have spaces in their folders and files e.g.
(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.
Start does not support long path names and white spaces. You have to convert it to 8.3 compatible paths.
The file has to exist in order to work with the API call.
I am pretty late to the lot, but here is a solution using the windows api. This always opens the associated application.
A lot of magic constants. The first zero is the hwnd of the current program. Can be zero. The other two zeros are optional parameters (parameters and directory). 5 == SW_SHOW, it specifies how to execute the app. Read the ShellExecute API docs for more info.
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]")
On windows 8.1, below have worked while other given ways with
subprocess.call
fails with path has spaces in it.By utilizing this and other's answers before, here's an inline code which works on multiple platforms.
If you want to go the
subprocess.call()
way, it should look like this on Windows:You can't just use:
because
start
is not an executable but a command of thecmd.exe
program. This works:but only if there are no spaces in the FILE_NAME.
While
subprocess.call
methodenquotes the parameters properly, thestart
command has a rather strange syntax, where:does something else than:
The first quoted string should set the title of the window. To make it work with spaces, we have to do:
which is what the code on top does.