我已经知道有几个问题针对这个主题,但没有一个解决了我的具体问题。或者至少我找不到。
我需要在后台执行一些程序,等待输出并对其进行操作。,但是后台程序必须继续执行。
我需要的背景程序的信息,准确地定位在其输出的第二行。如果这个程序阻止我的代码,直到到达这一行,就没有问题了。但是,它必须在这一行之后解锁,这样我就可以执行与后台程序完全无关的其他任务。
不过,我还是想不出如何做到这一点。我读过很多关于subprocess模块的文档,特别是subprocess.Popen。
实用:为什么this code不适用于['localtunnel', '8000']参数?它什么也不输出..。
我知道我不需要根特权来执行这个操作。
在jadkik94和fest的答案之后编辑
不幸的是,这两种答案对我都不起作用。也许我做错了什么..。
首先。一份“健全检查”:
import subprocess, threading, time
can_break = False
def run():
args = ["ping", "google.com"]
popen = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE)
while not can_break:
print popen.stdout.readline()
t = threading.Thread(target=run)
try:
t.start()
while True:
print 'Main thread...'
time.sleep(1)
except KeyboardInterrupt:
can_break = True上面的代码与类似于以下输出的输出正常工作:
Main thread...
PING google.com (74.125.234.160) 56(84) bytes of data.
64 bytes from plusone.google.com (74.125.234.160): icmp_req=1 ttl=54 time=82.5 ms
Main thread...
64 bytes from plusone.google.com (74.125.234.160): icmp_req=2 ttl=54 time=82.7 ms
[...]但是,当我将它与我想要的args (args = ['localtunnel', 8000])一起使用时,唯一的输出是Main thread...。
当我在主线程(阻塞)中调用localtunnel时,它返回所需的输出:
In [x]: popen = subprocess.Popen(['localtunnel', '8000'])
This localtunnel service is brought to you by Twilio.
Port 8000 is now publicly accessible from http://????.localtunnel.com ...这种方法是基于jadkik94 94的回答。但fest的回答也不管用。
发布于 2012-05-15 16:44:33
要以非阻塞的方式启动程序,但仍然能够看到程序的输出,程序必须在单独的线程或进程中启动。Ryan在这里发布了一个很好的代码示例:Python Subprocess.Popen from a thread
请记住,最后一行print myclass.stdout将打印当时的输出。如果程序刚刚启动,它可能根本没有输出,所以您的代码应该从myclass.stdout读取,直到它收到所需的行为止。
https://stackoverflow.com/questions/10604958
复制相似问题