To get an output of a command we could do this
os.popen("ls").read()
But suppose I have a command that I don't want to wait for it to return. In fact, I want to keep it running, and occasionally spit out some output.
(Eg., java PrintEvery5
) (Suppose the PrintEvery5
would print a line every 5 seconds).
How do subscribe to the process/thread and grab the output of this?
I've tried the following, which didn't seem to work.
### file: deqthread.py
import threading, os, subprocess
class DeqThread(threading.Thread):
def __init__(self):
super(DeqThread, self).__init__()
self.f=os.popen("java PrintEvery5")
def run(self):
print("in run")
def readResult(self):
return self.f.read()
thread1 = DeqThread()
thread1.start()
while True:
print(thread1.readResult())
Running python deqthread.py
, I don't see any output. THe whole thing just hangs there.
When I try this, I could see the output. (ie., it keeps printing to the console),
$python <ENTER>
>>> import os
>>> os.system("java PrintEvery5")
So what do I need to change in my deqthread.py
file so that I can get output out of my command?