How Can I Open Documents with Their Default Applications Using Python on Windows and macOS?

Patricia Arquette
Release: 2024-11-24 09:47:10
Original
733 people have browsed it

How Can I Open Documents with Their Default Applications Using Python on Windows and macOS?

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

Mac OS:

import subprocess
subprocess.call(('open', filepath))
Copy after login

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

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!

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