- 1 year ago
How to catch an output of .exe command that opens in another cmd?
To capture the output of an .exe
command that opens in another cmd window, you can use the subprocess
module in Python. Here is an example code snippet that demonstrates how to do this:
pythonimport subprocess
command = "start cmd /c my_program.exe arg1 arg2"
output = subprocess.check_output(command, shell=True)
print(output.decode("utf-8"))
In this code, we use the subprocess.check_output()
method to execute the command. The start
command is used to launch the command in a new cmd window, and the /c
option is used to close the window when the command is finished. The my_program.exe
command is executed with the arg1
and arg2
arguments.
The output of the command is captured using the subprocess.check_output()
method and is stored in the output
variable. We then use the decode()
method to convert the bytes object to a string and print the output to the console.
Note that the subprocess.check_output()
method will wait for the command to finish before returning the output. If you want to execute the command in the background and capture the output asynchronously, you can use the subprocess.Popen()
method instead.
pythonimport subprocess
command = "start cmd /c my_program.exe arg1 arg2"
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
while True:
output = process.stdout.readline().decode("utf-8")
if output == "" and process.poll() is not None:
break
if output:
print(output.strip())
print("Exit code:", process.returncode)
In this code, we use the subprocess.Popen()
method to execute the command in the background and capture the output asynchronously. The stdout=subprocess.PIPE
option is used to redirect the output of the command to a pipe, which we can read from in our Python code.
We use a while
loop to read the output of the command line by line and print it to the console. The loop exits when there is no more output and the process has completed. We also print the exit code of the process to the console when it has finished.