0% found this document useful (0 votes)
7 views

The subprocess module in Python is used for spawning new processes

Uploaded by

Bhuvan Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

The subprocess module in Python is used for spawning new processes

Uploaded by

Bhuvan Gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

The subprocess module in Python is used for spawning new processes, connecting to their

input/output/error pipes, and obtaining their return codes. It provides a powerful interface to
interact with system commands and scripts.

Here are some common use cases with examples:

1. Running a Simple Command

python

Copy code

import subprocess

# Run a simple command

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)

print(result.stdout)

2. Checking the Return Code

python

Copy code

import subprocess

# Run a command and check return code

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)

if result.returncode == 0:

print("Command executed successfully!")

else:

print("Command failed with return code:", result.returncode)

3. Capturing Output and Error

python

Copy code

import subprocess

# Run a command that may fail

result = subprocess.run(['ls', 'non_existent_file'], capture_output=True, text=True)


# Output standard output and error

print("STDOUT:", result.stdout)

print("STDERR:", result.stderr)

4. Running a Command with Shell=True

python

Copy code

import subprocess

# Run a command with shell=True

result = subprocess.run('echo $HOME', shell=True, capture_output=True, text=True)

print("Home directory:", result.stdout.strip())

5. Using Popen for More Control

python

Copy code

import subprocess

# Using Popen for more control

process = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# Capture output

stdout, stderr = process.communicate()

print("STDOUT:", stdout.decode())

print("STDERR:", stderr.decode())

6. Redirecting Output to a File

python

Copy code

import subprocess

# Redirect output to a file

with open('output.txt', 'w') as f:

subprocess.run(['ls', '-l'], stdout=f)


7. Input to a Command

python

Copy code

import subprocess

# Provide input to a command

process = subprocess.run(['grep', 'some_pattern'], input='some_pattern\nother_line', text=True,


capture_output=True)

print("Grep output:", process.stdout)

8. Running Commands Concurrently with ThreadPoolExecutor

python

Copy code

import subprocess

from concurrent.futures import ThreadPoolExecutor

def run_command(command):

result = subprocess.run(command, capture_output=True, text=True)

return result.stdout

commands = [['ls', '-l'], ['pwd'], ['echo', 'Hello, World!']]

with ThreadPoolExecutor() as executor:

results = list(executor.map(run_command, commands))

for result in results:

print(result)

9. Handling Timeouts

python

Copy code

import subprocess
try:

# Run a command with a timeout

result = subprocess.run(['sleep', '5'], timeout=2)

except subprocess.TimeoutExpired:

print("Command timed out!")

10. Chaining Commands

python

Copy code

import subprocess

# Using pipe to chain commands

p1 = subprocess.Popen(['echo', 'Hello, World!'], stdout=subprocess.PIPE)

p2 = subprocess.Popen(['grep', 'Hello'], stdin=p1.stdout, stdout=subprocess.PIPE)

p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.

output = p2.communicate()[0]

print(output.decode())

These examples demonstrate various ways to use the subprocess module effectively. Depending on
your needs, you can adapt these patterns to suit your applications, whether you need simple
command execution or more complex inter-process communication.

You might also like