在Gnome Shell中带通知的Python程序无法运行。

3

我正在编写一个Python程序,该程序从网页中获取信息并在Gnome Shell的通知中显示出来。我使用的是Arch,因此我希望在启动时启动此程序,并且如果网页上有任何更改,它将通知我。以下是我的代码:

import time
import webbrowser
import requests
from bs4 import BeautifulSoup
from gi.repository import Notify, GLib


IPS = {'Mobifone': True, 'Viettel': False, 'Vinaphone': False}
LINK = "https://id.vtc.vn/tin-tuc/chuyen-muc-49/tin-khuyen-mai.html"


def set_ips_state(ips_name, state):
    global IPS
    for key in IPS.iterkeys():
        if key == ips_name:
            IPS[key] = state


def call_webbrowser(notification, action_name, link):
    webbrowser.get('firefox').open_new_tab(link)


def create_notify(summary, body, link):
    Notify.init("Offer")
    noti = Notify.Notification.new(summary, body, 'dialog-information')
    noti.add_action('action_click', 'Read more...', call_webbrowser, link)
    noti.show()
    # GLib.MainLoop().run()


def save_to_file(path_to_file, string):
    file = open(path_to_file, 'w')
    file.write(string)
    file.close()


def main():
    global IPS
    global LINK

    result = []

    offer_news = open('offer_news.txt')
    tag_in_file = BeautifulSoup(offer_news.readline(), 'html.parser')
    tag = tag_in_file.a
    offer_news.close()

    page = requests.get(LINK)
    soup = BeautifulSoup(page.text, 'html.parser')
    for div in soup.find_all('div', 'tt_dong1'):
        # first_a = div.a
        # main_content = first_a.find_next_subling('a')
        main_content = div.find_all('a')[1]
        for k, v in IPS.iteritems():
            if v:
                if main_content.text.find(k) != -1:
                    result.append(main_content)
    print result[1].encode('utf-8')
    if tag_in_file == '':
        pass
    else:
        try:
            old_news_index = result.index(tag)
            print old_news_index
            for idx in range(old_news_index):
                create_notify('Offer News', result[idx].text.encode('utf-8'), result[idx].get('href'))
            print "I'm here"
        except ValueError:
            pass
    offer_news = open('offer_news.txt', 'w')
    offer_news.write(result[0].__str__())
    offer_news.close()


if __name__ == '__main__':
    while 1:
        main()
        time.sleep(10)

问题是当我点击通知中的“阅读更多...”按钮时,它不会打开Firefox,除非我在create_notify函数中取消注释GLib.MainLoop().run(),但这会使程序冻结。有谁能帮忙吗?

1个回答

8
GUI 应用程序通常使用三个主要组件:小部件、事件循环和回调函数。启动应用程序时,会创建小部件、注册回调函数并启动事件循环。事件循环是一个无限循环,它查找来自小部件的事件(例如“单击按钮”),并触发相应的回调函数。
现在,在您的应用程序中有另一个无限循环,所以这两个循环将不能协同工作。相反,应该利用 GLib.MainLoop().run() 来触发事件。可以使用GLib.timeout_add_seconds 触发定期事件,如每10秒钟一次。
第二个问题是您需要保留对调用回调函数的通知的引用。之所以在 noti.show() 后添加 GLib.MainLoop().run() 时它能正常工作的原因是仍然存在对 noti 的引用,但如果按照我之前建议的进行更改则不起作用。如果您确定始终只会有一个通知处于活动状态,则可以保存对最后一个通知的引用。否则,您需要一个列表,并定期清理它或类似的操作。
下面的示例应该能为您指明正确的方向:
from gi.repository import GLib, Notify


class App():
    def __init__(self):
        self.last_notification = None
        Notify.init('Test')
        self.check()

    def check(self):
        self.last_notification = Notify.Notification.new('Test')
        self.last_notification.add_action('clicked', 'Action', 
                                          self.notification_callback, None)
        self.last_notification.show()
        GLib.timeout_add_seconds(10, self.check)

    def notification_callback(self, notification, action_name, data):
        print(action_name)


app = App()
GLib.MainLoop().run()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接