我正在开发一个Ubuntu Appindicator,它每X秒显示一次JSON API调用的值。
问题在于,它会随机停止调用self.loop
而不会出现任何错误或警告。我可以让它运行数天或数小时。我已经设置(开发中)调试语句,并且在调用loop
函数后它总是停止运行。
就好像我正在返回False
或者没有从函数返回,即使此代码中的逻辑应该总是返回True
。
以下是GObject.timeout_add
的{{3}}(对于GTK2,但原则是这样)。
我不确定它是否依赖于PyGTK版本。我已经在Ubuntu 16.04和Ubuntu 17.04中发生过它。
这是完整的课程。调用JSON API的位置为result = self.currency.query()
。我很乐意提供进一步的反馈。
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject
class QueryLoop():
"""QueryLoop accepts the indicator to which the result will be written and an currency to obtain the results from.
To define an currency you only need to implement the query method and return the results in a pre-determined
format so that it will be consistent."""
def __init__(self, indicator, currency, timeout=5000):
"""
Initialize the query loop with the indicator and the currency to get the data from.
:param indicator: An instance of an indicator
:param currency: An instance of an currency to get the information from
:param timeout The interval between requests to the currency API
"""
self.indicator = indicator
self.currency = currency
self.timeout = timeout
self.last_known = {"last": "0.00"}
def loop(self):
"""Loop calls it-self forever and ever and will consult the currency for the most current value and update
the indicator's label content."""
result = self.currency.query()
if result is not None:
self.indicator.set_label("{} {}".format(result["last"], self.currency.get_ticker()))
self.last_known = result
else:
self.indicator.set_label("Last Known: {} EUR (Error)".format(self.last_known["last"]))
return True
def start(self):
"""Starts the query loop it does not do anything else. It's merely a matter of naming because
when initializing the loop in the main() point of entry."""
GObject.timeout_add(self.timeout, self.loop)
self.loop()