2016-06-10 47 views
0

我有一个我想打电话的外部程序,例如ping -t 8.8.8.8每次子过程打印回调

而且我为了在每次打印输出时都要回调该怎么做而有些困惑。

我正在寻找一种方法,每次有输出时调用带有最新输出行的代码段。

感谢您的帮助!

回答

0

此代码的作品,诀窍是使用process.stdout.readline(),因为它阻止直到有一条线准备好。

示例代码:

cmd = "ping -t www.google.com" 
ping = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) 

try: 
    while True: 
     line = str(ping.stdout.readline(), "ascii") 
     print(line) # this can be anything 
except KeyboardInterrupt: 
    ping.terminate() # don't wanna leave a process hanging in the background