Understand Python's Subprocess Module with Practical Exercises for Beginners

SANA MUJAWARSANA MUJAWAR
3 min read

Run system commands, automate tasks, and start scripting like a pro!


Introduction

Ever wondered how to run terminal or command line commands directly from your Python code? Whether you're working on cybersecurity automation, Linux auditing, or just want to build smarter scripts, Python's subprocess module is your gateway.

In this blog, you’ll learn:

What the subprocess module does

How to use it in real-world automation tasks

Hands-on exercises that make learning fun and practical!


What is subprocess in Python?

The subprocess module allows Python to interact with the operating system by executing shell commands or external programs. Instead of manually typing commands in a terminal, you can automate them using Python.

It’s especially useful in:

System administration

Penetration testing

DevOps automation

Linux hardening scripts


Basic Syntax

Here’s a simple example:

import subprocess

subprocess.run(["echo", "Hello from Python!"])

This will print:

Hello from Python!


Why Use subprocess?

Reason Benefit

Automate repetitive CLI tasks Less manual work Capture output programmatically Use in reports or logs Combine Python + Bash power Best of both worlds Secure alternative to os.system More control and safety


Hands-On Learning Exercises

Let’s walk through 7 simple exercises that you can try directly on your system — whether you’re on Windows, Linux, or Mac.

Exercise 1: Run a Basic Command

import subprocess

subprocess.run(["echo", "Hello, subprocess!"])

Expected Output:

Hello, subprocess!

Try replacing echo with commands like date, whoami, or ls.

Exercise 2: Capture Output

result = subprocess.run(["ls"], capture_output=True, text=True) print("Files:\n", result.stdout)

Why this matters: Useful for storing and analyzing results.

Exercise 3: Handle Errors Gracefully

try: subprocess.run(["ls", "/not/found"], check=True) except subprocess.CalledProcessError as e: print("Error occurred:", e)

Output:

Error occurred: Command '['ls', '/not/found']' returned non-zero exit status 2.

Tip: Add .stderr to get the exact error message.

Exercise 4: Use shell=True

subprocess.run("echo Shell mode is active!", shell=True)

Warning: Only use shell=True when necessary, especially with user input (can be unsafe!).

Exercise 5: Redirect Output to File

with open("output.txt", "w") as f: subprocess.run(["ls", "-l"], stdout=f)

Open the output.txt file to view the result.

Exercise 6: Get Return Code

result = subprocess.run(["ls"]) print("Return code:", result.returncode)

Return code 0 = success. Non-zero = error.

Exercise 7: Run Background Process with Popen

from subprocess import Popen

p = Popen(["ping", "-c", "3", "google.com"]) print("Running ping in the background...")

Useful for long-running tasks like scans or monitoring tools.

Quick Reference Table

Task Code Snippet

Run basic command : subprocess.run(["ls"])

Capture output : capture_output=True, text=True

Check for errors: check=True in run()

Use shell syntax: shell=True

Redirect to file: stdout=f

Return code check: result.returncode

Run in background: subprocess.Popen([...])

Conclusion

The subprocess module is a powerful tool for automating system-level tasks in Python. Whether you're a beginner or a budding cybersecurity enthusiast, mastering this module will supercharge your scripts and workflows.

Next step: Try applying what you learned to:

A Linux audit script

A security scanner

A log automation tool

Keep Learning!

If you found this blog helpful, feel free to share it or bookmark it for future reference. Happy scripting!

0
Subscribe to my newsletter

Read articles from SANA MUJAWAR directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

SANA MUJAWAR
SANA MUJAWAR