I need to be able to open a document using it's 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?
In Mac OS, you can use the "open" command. There is a Windows API call that does something similar, but I don't remember it offhand.
Update
Okay, the "start" command will do it, so this should work.
Mac OS/X:
os.system("open "+filename);
Windows:
os.system("start "+filename);
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
I prefer:
os.startfile(path, 'open')
(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.
Edit: Windows only
Use the subprocess module available on Python 2.4+, not os.system, so you don't have to deal with shell escaping.
import subprocess, os
if os.name = 'mac':
subprocess.call(('open', filepath))
elif os.name = 'nt':
subprocess.call(('start', filepath))
elif os.name = 'posix':
subprocess.call(('xdg-open', filepath))
The double parentheses are because subprocess.call wants a sequence as its first argument, so we're using a tuple here. On Linux systems with Gnome there is also a "gnome-open" command that does the same thing.
import os
import subprocess
def click_on_file(filename):
try:
os.startfile(filename):
except AttributeError:
subprocess.call(['open', filename])
If you want to go the sybprocess.call()
way, it should look like this on Windows:
import subprocess
subprocess.call(('cmd', '/C', 'start', '', FILE_NAME))
You can't just use:
supbrocess.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.
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.