Opening Documents with Default Applications in Python Across Windows and Mac OS
In the realm of automation, the need often arises to open documents using their designated default applications. Whether you're working on Windows or Mac OS, Python offers a convenient solution for this task.
Python provides the subprocess module, a powerful tool for interacting with the operating system. This module allows you to execute system commands as if you were invoking them manually in the shell.
To open a document using its default application:
Windows:
import os os.startfile(filepath)
Mac OS:
import subprocess subprocess.call(('open', filepath))
The os.startfile() function is specific to Windows, while subprocess.call() works on both Windows and Mac OS. In the above commands, filepath represents the path to the document you wish to open.
Note: For Linux systems, you can use either the xdg-open command, which is a Free Desktop Foundation standard, or the gnome-open command specifically for Gnome desktop environments.
import subprocess, platform if platform.system() == 'Linux': subprocess.call(('xdg-open', filepath))
The above is the detailed content of How Can I Open Documents with Their Default Applications Using Python on Windows and macOS?. For more information, please follow other related articles on the PHP Chinese website!