- 1 year ago
Read text from os.Popen that opens new command prompt
You can use the subprocess
module in Python to execute a command using os.Popen
and capture its output. Here's an example:
pythonimport subprocess
# Execute the command and capture its output
process = subprocess.Popen(['cmd', '/c', 'echo hello'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Read the output from stdout and stderr
stdout, stderr = process.communicate()
# Print the output
print(stdout.decode('utf-8'))
In this example, we use subprocess.Popen
to execute the echo
command in a new command prompt window. The /c
parameter is used to close the command prompt window after the command completes. We redirect the standard output of the process to a pipe using the stdout=subprocess.PIPE
parameter.
After starting the process, we use the communicate
method to wait for the process to complete and capture its output from both stdout and stderr. We then decode the stdout output using the decode
method and print it to the console.
Note that when executing a command in a new command prompt window, you may need to add additional parameters to the command to prevent the window from closing immediately. For example, you can add the pause
command to the end of the command to keep the window open until the user presses a key.