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.
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.
Expanding on FatalError's suggestion with an example.
One additional benefit of using subprocessing
rather than os.system
is that it uses the same syntax cross-platform (os.system
on Windows requires a "start" at the beginning, whereas OS X requires an "open". Not a huge deal, but one less thing to remember).
Opening a file with subprocess.call
.
All you need to do to launch a program is call subprocess.call()
and pass in a list
of arguments where the first is the path to the program, and the rest are additional arguments that you want to supply to the program you're launching.
For instance, to launch Notepad.exe
import subprocess
path_to_notepad = 'C:\\Windows\\System32\\notepad.exe'
path_to_file = 'C:\\Users\\Desktop\\hello.txt'
subprocess.call([path_to_notepad, path_to_file])
Passing multiple arguments and paths is equally as simple. Just add additional items to the list.
Launching with multiple arguments
This, for example, launches a JAR file using a specific copy of the Java runtime environment.
import subprocess
import os
current_path = os.getcwd()
subprocess.call([current_path + '/contents/home/bin/java', # Param 1
'-jar', #Param2
current_path + '/Whoo.jar']) #param3
Argument 1 targets the program I want to launch. Argument2 supplies an argument to that program telling it that it's going to run a JAR, and finally Argument3 tells the target program where to find the file to open.