DEV Community

bluepaperbirds
bluepaperbirds

Posted on

Start an external program with Python

You can start a program using just Python code. You do so by a module called subprocess.

If it is a terminal program, you can save its output in your Python program.

#!/usr/bin/env python

from subprocess import Popen, PIPE

process = Popen(['cat', 'test.py'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print(stdout)
Enter fullscreen mode Exit fullscreen mode

The cat command outputs the contents of a file on a Linux system. This may also work on Mac, but if you're on Windows try another command.

You can start non-terminal programs. This works for any program regardless of if it's something simple like notepad or something more advanced like chrome.

On Linux there's the program mousepad, which is a clone of the notepad program. You could run it like this:

>>> import subprocess
>>> import sys
>>> result = subprocess.run(["mousepad"])
Enter fullscreen mode Exit fullscreen mode

The subprocess module lets you do all kinds of things with running programs.

This module is part of the standard modules, so you don't have to install it with the Python package manager.

If the program is taking to long to execute, you can use a timeout

import subprocess
import sys

result = subprocess.run([sys.executable, "-c", "import time; time.sleep(3)"], timeout=1)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)