- 1 year ago
Get windows shell output of long running script in python
To capture the output of a long-running script in the Windows shell (Command Prompt) using Python, you can use the subprocess
module. The subprocess
module provides functions for creating new processes, executing commands, and capturing their output. Here's an example:
pythonimport subprocess
# Run the long-running script and capture the output
process = subprocess.Popen('python long_script.py', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
# Read and print the output line by line
while True:
line = process.stdout.readline()
if not line:
break
print(line.strip().decode())
# Wait for the process to finish
process.wait()
# Get the exit code
exit_code = process.returncode
# Output the exit code
print(f"Exit Code: {exit_code}")
In this example:
Replace
'python long_script.py'
with the actual command or script you want to execute in the Windows shell.The
subprocess.Popen()
function is used to start the process and capture its output. Thestdout=subprocess.PIPE
parameter redirects the standard output to a pipe, andstderr=subprocess.STDOUT
redirects the standard error to the same pipe.The
while
loop reads the output of the process line by line usingprocess.stdout.readline()
. It continues reading until there is no more output.Each line of the output is printed using
print(line.strip().decode())
. Modify this line to process or store the output as needed.process.wait()
waits for the process to finish before proceeding.process.returncode
retrieves the exit code of the process.The exit code is printed using
print(f"Exit Code: {exit_code}")
.
By using subprocess.Popen()
and capturing the output, you can obtain and process the output of a long-running script in the Windows shell using Python.