Here are 10 Python snippets demonstrating subprocess management with the subprocess module for running system commands and interacting with external processes. Each snippet is separated by a delimiter.
import subprocess
with open('output.txt', 'w') as file:
subprocess.run(['echo', 'Writing to a file'], stdout=file)
print("Output written to 'output.txt'")
import subprocess
result = subprocess.run(['cat'], input="This is input text\n", text=True, capture_output=True)
print("Command Output:", result.stdout)
import subprocess
process = subprocess.Popen(['sleep', '5'])
print("Process started with PID:", process.pid)
import subprocess
process = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
stdout, _ = process.communicate("This is sent to stdin")
print("Output from the process:", stdout)
import subprocess
process = subprocess.Popen(['ping', '-c', '4', 'google.com'], stdout=subprocess.PIPE, text=True)
for line in process.stdout:
print(line.strip())