Opening Documents with Default Application in Python Across Windows and Mac OS
In various operating systems, double-clicking a document icon prompts it to be opened using its designated application. Achieving this functionality in Python involves utilizing the appropriate system commands.
In Python 2.4 and later versions, the subprocess module provides the capability to open documents with the default application. Instead of relying on os.system(), this module offers a more efficient solution that eliminates the need for complex shell escaping.
Code:
import subprocess, os, platform filepath = 'path/to/document.ext' 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))
Explanation:
Additional Notes:
The above is the detailed content of How Can Python Open Documents with Their Default Applications on Windows and macOS?. For more information, please follow other related articles on the PHP Chinese website!