I'm trying to write a small server wrapper in Python in which I can start multiple servers and make them print in the same terminal. Each process would be started in a thread, and print stdout to the terminal. Below is my code:
class Server():
def __init__(self,name,args):
self.name = name
self.args = shlex.split(args)
self.started = False
def start(self):
threading.Thread(target=self.__start).start()
def __start(self):
print(bcolors.HEADER+"{}: INFO: Server started.".format(self.name)+bcolors.ENDC)
self.started = True
self.p = subprocess.Popen(self.args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout_list = []
while True:
stdout = self.p.stdout.readline()
if stdout == '' and self.p.poll() != None:
break
else:
if not stdout == '':
stdout_list.append(stdout)
stdout = stdout.rstrip()
print("{}: STDOUT: {}".format(self.name,stdout))
stderr = self.p.stdout.readline()
if stderr != '':
print(bcolors.WARNING+"{}: STDERR: {}".format(self.name,stderr)+bcolors.ENDC)
print(bcolors.HEADER+"{}: INFO: Server closed.".format(self.name)+bcolors.ENDC)
self.start = False
return ''.join(stdout)
def interrupt(self):
if self.started == True:
self.p.send_signal(signal.SIGINT)
else:
print("Server not started.")
def terminate(self):
if self.started == True:
self.p.kill()
else:
print("Server not started.")
t=Server("Test","python testserver.py")
t2=Server("Test2","python testserver.py")
t.start()
t2.start()
testserver.py is a simple script that prints 1-3, one each second, and each time flushing the stdout. It's just here to test if the program can host and print stuff concurrently.
The main script works fine if only t.start() is executed, it would print 1-3 one by one, and it also runs from a thread, so any code after it would work as well. Yet when I add t2.start(), I get mixed results.
user@desktop:~/Documents/home automation$ python serverhost.py
Test: INFO: Server started.
Test2: INFO: Server started.
Test: STDOUT: 1
Test2: STDOUT: 1
Test: STDOUT: 2
Test2: STDOUT: 2
Test: STDOUT: 3
Test2: STDOUT: 3
Test: INFO: Server closed.
Test2: INFO: Server closed.
and sometimes
user@desktop:~/Documents/home automation$ python serverhost.py
Test: INFO: Server started.
Test2: INFO: Server started.
Test: STDOUT: 1
Test: STDOUT: 2
Test: STDOUT: 3
Test: INFO: Server closed.
Test2: STDOUT: 1
Test2: STDOUT: 2
Test2: STDOUT: 3
Test2: INFO: Server closed.
with the STDOUT from Test2 all showing at once (not realtime) when the host quits.
Anyone knows what's going on? I thought if it doesn't work, it should at least be consistent..