jpyams
jpyams

Reputation: 4364

Preferred Method of Opening a PDF in Python 3

Is there a newer way to open a PDF using an external viewer from Python 3 in Linux other than subprocess?

This sounds like a noobish and duplicate question, but I looked at this question and this question, and all of the answers are over 7 years old and recommended discouraged methods like os.system, old methods like manually creating a subprocess.Popen or Windows-only methods like os.startfile.

So in the time since these questions were answered, have preferred methods of launching a PDF reader from within Python emerged, or are these still the best answers?

Upvotes: 1

Views: 1774

Answers (1)

Kos
Kos

Reputation: 72241

Python as of 3.6 still doesn't have a cross-platform way to open files using default programs.
Issue 3177 suggested to add one, but it didn't happen yet.

So:

  • On Windows, there's a system call for this, you can reach it from Python via os.startfile,
  • On Linux, there's a command-line tool called xdg-open that does this,
  • On Mac OS, there's a command-line tool simply called open.

This means that unfortunately you still need to check the operating system and pick the right approach. The correct way to call the command-line tools is using the subprocess module.

This answer provides a code snippet:

Open document with default application in Python

Upvotes: 3

Related Questions