Home > Backend Development > Python Tutorial > How Can I Open Default Document Applications in Python on Windows and macOS?

How Can I Open Default Document Applications in Python on Windows and macOS?

Patricia Arquette
Release: 2024-11-18 02:17:02
Original
877 people have browsed it

How Can I Open Default Document Applications in Python on Windows and macOS?

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))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template