How can I open files in external programs in Python? [duplicate]

On Windows you could use os.startfile() to open a file using default application:

import os
os.startfile(filename)

There is no shutil.open() that would do it cross-platform. The close approximation is webbrowser.open():

import webbrowser
webbrowser.open(filename)

that might use automatically open command on OS X, os.startfile() on Windows, xdg-open or similar on Linux.

If you want to run a specific application then you could use subprocess module e.g., Popen() allows to start a program without waiting for it to complete:

import subprocess

p = subprocess.Popen(["notepad.exe", fileName])
# ... do other things while notepad is running
returncode = p.wait() # wait for notepad to exit

There are many ways to use the subprocess module to run programs e.g., subprocess.check_call(command) blocks until the command finishes and raises an exception if the command finishes with a nonzero exit code.

Leave a Comment