我正在尝试创建一个简单的应用程序,其中
图像(通过外部进程)推入目录
Python看门狗触发器,图像由函数处理,结果显示在窗口中
作业不断运行,并且在图像进入目录时触发处理功能。结果的绘图窗口应仅用新结果更新,而不是关闭窗口然后重新绘图。
下面的代码不显示结果。绘图窗口保持空白,然后崩溃。如果除matplotlib之外的其他工具可以轻松完成此工作,那也很好。
# plt is matplotlib.pyplot
def process_and_plot(test_file):
y, x = getresults(test_file) # function which returns results on image file
y_pos = range(len(y))
plt.figure(num=1,figsize=(20,10))
plt.bar(y_pos, y, align='center')
plt.xticks(y_pos, x)
plt.show()
# to trigger the proess_and_plt function when a new file comes in directory
class ExampleHandler(FileSystemEventHandler):
def on_created(self, event):
print event.src_path
process_and_plot(event.src_path)
event_handler = ExampleHandler()
observer.schedule(event_handler, path='path/to/directory')
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
答案 0 :(得分:2)
要使代码正常工作,我唯一需要做的就是将plt.show()
替换为plt.pause(.001)
,这是非阻塞性的,会在暂停之前进行更新并显示该数字(请参阅docs )。
关于SO的最佳答案似乎是this。有一些建议使用plt.show(False)
或plt.ion()
来使plt.show()
无阻塞;都不适合使用Matplotlib 2.2.4。
这是完整的代码,因为问题中的代码省略了几行:
import matplotlib.pyplot as plt, time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def process_and_plot(test_file):
#y, x = getresults(test_file) # function which returns results on image file
y, x = [2, 4, 3], [0, 1, 2]
y_pos = range(len(y))
plt.figure(num=1,figsize=(20,10))
plt.title(test_file)
plt.bar(y_pos, y, align='center')
plt.xticks(y_pos, x)
plt.pause(.001)
# to trigger the proess_and_plt function when a new file comes in directory
class ExampleHandler(FileSystemEventHandler):
def on_created(self, event):
print event.src_path
process_and_plot(event.src_path)
event_handler = ExampleHandler()
observer = Observer()
observer.schedule(event_handler, path='/path/to/directory')
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()