Calling Other Programs with subprocess

Intuitive Python — by David Muller (18 / 41)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Creating Temporary Workspaces with tempfile | TOC | Using Python’s Built-In Database with sqli te3 👉

You can use the subprocess standard library module to invoke other command line programs available on your system and process their results in Python. You might find the subprocess useful if, for example, you want to call a program like git from inside Python to learn about the current state of your version controlled project. Indeed, some examples in this section will combine subprocess and git to do just that.

Note, if you don’t have git installed on your machine or are not currently in a directory with a git repository, some of the following examples may not successfully execute on your computer. You can download git if you like,[49] but it’s also OK to just follow along with the examples here so you get a sense of the abilities of the subprocess module (you don’t need any special git knowledge).

You can use subprocess with git to retrieve the name of the current git branch you are on:

​ >>> ​import​ ​subprocess​
​ >>> command = [​"git"​, ​"branch"​, ​"--show-current"​]
​ >>> result = subprocess.run(command, capture_output=True)
​ >>> result.returncode
​ 0
​ >>> result.stdout
​ b​'main​​\n​​'​
​ >>> result.stdout.decode(​"utf-8"​).strip()
​ ​'main'​
​ >>>

In the preceding example, you call subprocess.run with two arguments. The first…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.