I have spent hours discovering a good method to execute a .exe file with a proper arguments and retrieve the console log as it appears in my python code. I have a code sample.exe that gets two arguments and print them 20 times, I also have a main code that runs this script and print the console log. Here is my main script
import sys
from threading import Thread
import time
import subprocess
import os
from subprocess import Popen, PIPE
class CommandExecution(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
exe = os.path.normcase(r'C:\\Users\\...\\...\\...\\...\\...\\...\\...\\sample.exe -i testINFile -o testOUTFile')
proc = subprocess.Popen(exe, stdout=subprocess.PIPE, shell=True, bufsize=1, universal_newlines=True)
for line in proc.stdout:
print(line.strip())
thread_1 = CommandExecution()
thread_1.start()
After I run this code, I do not get any response until the sample.exe is completely executed then I get the following response at once.
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b'salam -i testFile -o testFile'
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
Then I have replaced the run() function with another implementation but again it did not work. Here is another implementation for it.
def run(self):
self.command = os.path.normcase(r'C:\\Users\\...\\...\\...\\...\\...\\...\\...\\sample.exe -i testINFile -o testOUTFile')
if os.name == 'nt': # windows
if isinstance(self.command, str):
self.command = "powershell" + " " + self.command
else:
self.command.insert(0, "powershell")
print(self.command)
p = Popen(self.command, stdout=PIPE, shell="false")
while True:
line = p.stdout.readline()
print(line.strip())
if line == "b''" or p.poll() is not None:
break
return
If you have any idea I will be more than happy to hear.
Update:
To me it seems that the problem is the code being stuck at the Popen line and once the execution is done it will go to the next line ,and prints all of the output. But the question is why it is happening?