Open document with default OS application in Python, both in Windows and Mac OS
open
and start
are command-interpreter things for Mac OS/X and Windows respectively, to do this.
To call them from Python, you can either use subprocess
module or os.system()
.
Here are considerations on which package to use:
You can call them via
os.system
, which works, but...Escaping:
os.system
only 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.quote
for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex- MacOS/X:
os.system("open " + shlex.quote(filename))
- Windows:
os.system("start " + filename)
where properly speakingfilename
should be escaped, too.
- MacOS/X:
You can also call them via
subprocess
module, but...For Python 2.7 and newer, simply use
subprocess.check_call(['open', filename])
In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile
subprocess.run(['open', filename], check=True)
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:try:
retcode = subprocess.call("open " + filename, shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", eNow, what are the advantages of using
subprocess
?- Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type
'filename ; rm -rf /'
" problem, and if the file name can be corrupted, usingsubprocess.call
gives us little additional protection. - Error handling: It doesn't actually give us any more error detection, we're still depending on the
retcode
in 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). - Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.
To the objection "But
subprocess
is 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
start
command requires you to pass inshell=True
which negates most of the benefits of usingsubprocess
.- Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type
Open file with its default program via python
To open it in the default application for that file type:
subprocess.Popen([file],shell=True)
Considering that you are implementing a user guide, you may want to open it in a web browser.
import webbrowser
webbrowser.open_new(r'file://C:\path\to\file.pdf')
How can I open files in external programs in Python?
Use this to open any file with the default program:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("start " + fileName)
If you really want to use a certain program, such as notepad, you can do it like this:
import os
def openFile():
fileName = listbox_1.get(ACTIVE)
os.system("notepad.exe " + fileName)
Also if you need some if checks before opening the file, feel free to add them. This only shows you how to open the file.
How to open a file with the standard application?
os.startfile is only available for windows for now, but xdg-open will be available on any unix client running X.
if sys.platform == 'linux2':
subprocess.call(["xdg-open", file])
else:
os.startfile(file)
Open document with default OS application in Python, both in Windows and Mac OS
open
and start
are command-interpreter things for Mac OS/X and Windows respectively, to do this.
To call them from Python, you can either use subprocess
module or os.system()
.
Here are considerations on which package to use:
You can call them via
os.system
, which works, but...Escaping:
os.system
only 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.quote
for Unix-like systems, but nothing really standard for Windows. Maybe see also python, windows : parsing command lines with shlex- MacOS/X:
os.system("open " + shlex.quote(filename))
- Windows:
os.system("start " + filename)
where properly speakingfilename
should be escaped, too.
- MacOS/X:
You can also call them via
subprocess
module, but...For Python 2.7 and newer, simply use
subprocess.check_call(['open', filename])
In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile
subprocess.run(['open', filename], check=True)
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:try:
retcode = subprocess.call("open " + filename, shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", eNow, what are the advantages of using
subprocess
?- Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type
'filename ; rm -rf /'
" problem, and if the file name can be corrupted, usingsubprocess.call
gives us little additional protection. - Error handling: It doesn't actually give us any more error detection, we're still depending on the
retcode
in 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). - Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.
To the objection "But
subprocess
is 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
start
command requires you to pass inshell=True
which negates most of the benefits of usingsubprocess
.- Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type
Related Topics
Unicodeencodeerror: 'Charmap' Codec Can't Encode - Character Maps to <Undefined>, Print Function
Cannot Open Include File: 'Io.H': No Such File or Directory
How to Cross Compile Python Interpreter for Windows Under Linux
Does Python Do Variable Interpolation Similar to "String #{Var}" in Ruby
Magicexception:File 5.41 Supports Only Version 16 Magic File, Magic.Mgc Is Version 14
Request Uac Elevation from Within a Python Script
Detect Face Then Autocrop Pictures
How to Make a Discontinuous Axis in Matplotlib
Serving a Request from Gunicorn
Clang Error: Unknown Argument: '-Mno-Fused-Madd' (Python Package Installation Failure)
Bring the Current Python Program to Background
Differencebetween "Is None" and "== None"
To Read Line from File Without Getting "\N" Appended at the End
How to Use Python Requests to Fake a Browser Visit A.K.A and Generate User Agent