Home >Backend Development >Python Tutorial >How Can Python Open Documents with Their Default Applications on Windows and macOS?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 11:53:10672browse

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

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:

  • The platform.system() function discerns the operating system the code is executing on.
  • For macOS, the 'open' command is used to open the document.
  • In Windows, os.startfile() accomplishes the task.
  • On Linux systems, xdg-open is utilized as the Free Desktop Foundation standard.

Additional Notes:

  • Gnome-open can be employed on Linux systems with Gnome, but xdg-open is recommended for cross-environment compatibility.
  • The double parentheses around the command in the subprocess.call() function are necessary to provide a sequence as its input, which is a tuple in this case.

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!

Statement:
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