41 lines
1.1 KiB
Python
41 lines
1.1 KiB
Python
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
# A command that produces output over time
|
|
# For example, pinging a server
|
|
command = ["ping", "-c", "5", "google.com"]
|
|
|
|
print(f"--- Starting command: '{' '.join(command)}' ---")
|
|
|
|
try:
|
|
# Start the subprocess
|
|
# stdout=subprocess.PIPE redirects the output so we can capture it
|
|
# text=True decodes the output as text using the default encoding
|
|
# bufsize=1 enables line-buffering for real-time output
|
|
process = subprocess.Popen(
|
|
command,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
text=True,
|
|
bufsize=1
|
|
)
|
|
|
|
# Read the output line by line in real-time
|
|
if process.stdout:
|
|
for line in iter(process.stdout.readline, ''):
|
|
print(line, end="")
|
|
sys.stdout.flush() # Ensure the output is printed immediately
|
|
|
|
# Wait for the process to complete and get the return code
|
|
process.wait()
|
|
return_code = process.returncode
|
|
|
|
print(f"--- Command finished with exit code: {return_code} ---")
|
|
|
|
except FileNotFoundError:
|
|
print(f"Error: Command not found: {command[0]}")
|
|
except Exception as e:
|
|
print(f"An error occurred: {e}")
|