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?
Share
openandstartare command-interpreter things for Mac OS/X and Windows respectively, to do this.To call them from Python, you can either use
subprocessmodule oros.system().Here are considerations on which package to use:
You can call them via
os.system, which works, but…Escaping:
os.systemonly works with filenames that don’t have any spaces or other shell metacharacters in the pathname (e.g.A:\abc\def\a.txt), or else these need to be escaped. There isshlex.quotefor Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlexos.system('open ' + shlex.quote(filename))os.system('start ' + filename)where properly speakingfilenameshould be escaped, too.You can also call them via
subprocessmodule, but…For Python 2.7 and newer, simply use
In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile
If you need to be compatible all the way back to Python 2.4, you can use
subprocess.call()and implement your own error checking:Now, what are the advantages of using
subprocess?'filename ; rm -rf /'‘ problem, and if the file name can be corrupted, usingsubprocess.callgives us little additional protection.retcodein either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).To the objection ‘But
subprocessis preferred.’ However,os.system()is not deprecated, and it’s in some sense the simplest tool for this particular job. Conclusion: usingos.system()is therefore also a correct answer.A marked disadvantage is that the Windows
startcommand requires you to pass inshell=Truewhich negates most of the benefits of usingsubprocess.