The Python process and OS services

Execute external commands with Python

the subprocess module

Overview

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes
This module intends to replace several older modules and functions:
os.system
os.spawn

subprocess.call(args)

Run the command described by args. Wait for command to complete, then return the returncode attribute.
Note that, if the returncode is
0 => the command exit with success
!= 0 => command result in failure

			# execute 'date +%H:%M:%S' by Python:
			>>> import subprocess
			>>>
			>>> subprocess.call(["date", "+%H:%M:%S"])
			0
		

subprocess.check_output(args)

Run command with arguments and return its output
If the return code was non-zero it raises a CalledProcessError

			# execute 'date +%H:%M:%S' and get output:

			>>> import subprocess
			>>> output = subprocess.check_output(["date", "+%H:%M:%S"])
			>>> output
			b'15:33:16\n'

			# decode the bytestring to ascii
			>>> output_ascii = output.decode('ascii')
			>>> output_ascii
			'15:33:16\n'

			# strip leading and trailing spaces:
			>>> output_ascii.strip()
			'15:33:16'
		

Open terminal - (MACOS/Unix) example

Open a terminal with a custom profile in the given directory


			import subprocess

			def open_terminal(profile, directory):
				"""open a terminal with a custom profile in the given directory"""
				cmd = "gnome-terminal"
				args = (
					"--window-with-profile",profile,
					"--working-directory",directory
				)

				subprocess.call([cmd, *args])

			open_terminal("day", "/data/python_demos/music")
		

Open VS Code - (MACOS/Unix) example

open VS Code editor and load given directory:


			import subprocess

			def open_vscode(directory):
				"""open VS Code editor and load given directory"""
				cmd = "code"

				subprocess.call([cmd, directory])

			open_vscode("/data/python_demos/music")
		

Open Chrome browser - example

Open Chrome browser in a new window, with the given user profile and loads the specified URLs
This is just a demo. For controlling a browser with Python it's better to use the built-in webbrowser module!

			import subprocess

			def load_browser(profile, url):
				"""open Chrome browser in new window,
				   with the given user profile and loads the specified URLs
				"""
				cmd = "google-chrome"
				args = "--new-window --profile-directory=" + "'{:s}' {:s}".format(profile, url)

				subprocess.call(cmd + " " + args, shell=True)


			urls_to_load = [
				"https://mail.google.com",
				"http://wwwcourses.github.io/ProgressBG-VC-Python"
			]


			load_browser("Profile 7",  " ".join(urls_to_load))
		

Reference

subprocess @python3 docs

These slides are based on

customised version of

Hakimel's reveal.js

framework