Accessing Default Document Applications in Python: Windows and Mac OS
Often, it becomes necessary to open a document using its associated default application in Python, similar to double-clicking the document icon in File Explorer or Finder. This article explores the best approach to achieve this task in both Windows and macOS environments.
The recommended method involves the use of Python's subprocess module, avoiding os.system() to eliminate concerns related to shell escaping. The following code demonstrates how to execute this task:
import subprocess, os, platform filepath = "path/to/document.txt" # Replace with actual document path if platform.system() == 'Darwin': # macOS subprocess.call(('open', filepath)) elif platform.system() == 'Windows': # Windows os.startfile(filepath) else: # linux variants subprocess.call(('xdg-open', filepath))
In this code, double parentheses are used for subprocess.call(), which requires a sequence as its first argument. The approach uses a tuple here. On Linux systems with Gnome, gnome-open can also be utilized; however, xdg-open is the Free Desktop Foundation standard and is compatible across Linux desktop environments.
The above is the detailed content of How Can I Open Default Document Applications in Python on Windows and macOS?. For more information, please follow other related articles on the PHP Chinese website!