我怎么能并行运行一个函数,在主程序退出后,他仍然继续运行?

2024-05-12 17:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

TL;DR

如何使用多处理库或其他方式使并行进程独立于主进程运行?(示例代码现在使用fork)

历史悠久

好吧,我正在为我的古怪配置编写一个小脚本,其中一个是rss_parser.py,它获得一组标题/url并放入stdout。最近,我想知道,当RSS列表中出现新消息时,使用NotifyNotify激活新通知。在

但我有点问题。我设置了一个打开链接的操作,这样当我的通知启动时,我可以单击并打开浏览器。这部分代码需要等待用户单击或通知关闭才能完成,而这正是在一个适当的事件循环中运行的。但是,这与其他事情冲突:要更新我的conky,我需要我的主脚本完成,而不需要通知部分!我的想法是这样的。在

地狱的密码

我用完整的代码code(检查parallel_notify函数)尝试了这个方法

#!/usr/bin/env python
# coding=utf-8
#
#   Python Script
#
#   Copyleft © Manoel Vilela
#
#

import feedparser
from argparse import ArgumentParser
from string import ascii_letters as alphabet
from os import fork
import json
import sys
import webbrowser

import gi
gi.require_version('Notify', '0.7')
from gi.repository import GObject  # noqa
from gi.repository import Notify   # noqa


class RssNotifier(GObject.Object):
    Notify.init("rss_conky")
    notifications = []

    def __init__(self, label):
        self.label = label
        self.loop = GObject.MainLoop()
        super(RssNotifier, self).__init__()
        GObject.timeout_add(100, self.exit_when_empty)
        # lets initialise with the application name

    def send_notification(self, title, text, url, file_path_to_icon=""):

        n = Notify.Notification.new(title, text, file_path_to_icon)
        # print('put notification')
        self.notifications.append(n)
        n.add_action(url, 'open', self.open_webbrowser)
        n.connect('closed', self.close_notification, n)
        n.show()

    def send_rss(self, rss, url):
        self.send_notification(self.label, rss, url, 'rss')

    def open_webbrowser(self, n, url):
        # print(':: webbrowse opening')
        webbrowser.open(url)

    def close_notification(self, n, arg):
        self.notifications.remove(n)
        # print(':: remove notification')
        # print(':: notifications: ', self.notifications)

    def exit_when_empty(self):
        # print('exit check')
        if not any(RssNotifier.notifications):
            self.loop.quit()
            return False
        return True


CACHE_FILE = '.cache.json'

parser = ArgumentParser()
parser.add_argument(
    '-u', '--url',
    default="http://hackernews.demos.monkeylearn.com/feed.xml?",
    dest='url',
    type=str,
    help='The url to be parsed'
)
parser.add_argument(
    '-l', '--lines',
    default=10,
    dest='lines',
    type=int
)

parser.add_argument(
    '-w', '--width',
    default=80,
    dest='width',
    type=int,
    help='The horizontal limit'
)
parser.add_argument(
    '-p', '--prefix',
    default='- ',
    dest='prefix',
    type=str,
    help='A prefix attached each feed'

)

parser.add_argument(
    '-i', '--ignore',
    default='',
    dest='ignore',
    type=str,
    help='Useless string to remove'
)

parser.add_argument(
    '-n', '--disable-notifications',
    default=True,
    dest='notifications',
    action='store_false',
    help='Disable notifications (default True)'
)

parser.add_argument(
    '-r', '--rss-label',
    default='RSS',
    dest='rss_label',
    type=str,
    help='A simple label for what is fetching'

)


def get_label(entry):
    if entry.get('tags'):
        label = '{}: '.format(entry.get('tags').pop()['term'])
    else:
        label = ''
    return label


def long_title_clean(title):
    if len(title) > options.width:
        return (title[:options.width] + '\n' +
                ' ' * (len(options.prefix)) +
                long_title_clean(title[options.width:].strip()))
    return title


def translate_name(url):
    return '.' + ''.join([x for x in url if x in alphabet]) + '.cache'


def save_cache(new_cache, key):
    cache_file = get_cache_file()
    cache_file[key] = new_cache
    with open(CACHE_FILE, 'w') as f:
        json.dump(cache_file, f)


def get_cache(key):
    return get_cache_file()[key]


def get_cache_text(key):
    return '\n'.join((x for x, _ in get_cache(key)))


def get_cache_file():
    try:
        with open(CACHE_FILE, 'r') as f:
            return json.load(f)
    except:
        return {}


def notify(new_rss):
    notifier = RssNotifier(options.rss_label)
    for rss, url in new_rss:
        notifier.send_rss(rss, url)
    notifier.loop.run()


def ignore_pattern(title):
    return title.replace(options.ignore, '')


def parallel_notifications(new_rss):
    if any(new_rss) and options.notifications:
        if fork() == 0:
            notify(new_rss)


def parse_print_rss(feed):
    new_cache = []
    for entry in feed['entries']:
        if len(new_cache) >= options.lines:
            break
        label = get_label(entry)
        output = '{}{}{!s}'.format(options.prefix, label, entry.title)
        title = long_title_clean(ignore_pattern(output))
        if title not in new_cache:
            new_cache.append([title, entry['link']])
            print(title)

    return new_cache


if __name__ == '__main__':
    loop = GObject.MainLoop()
    options = parser.parse_args()
    feed = feedparser.parse(options.url)
    keyname = translate_name(options.url)
    if not any(feed['entries']):
        cache = get_cache_text(keyname)
        print(cache)
        sys.exit(0)

    new_cache = parse_print_rss(feed)
    old_cache = get_cache(keyname)
    new_rss = [x for x in new_cache if x not in old_cache]
    new_rss = new_cache  # force use the new_cache
    # the paralell part going here
    parallel_notifications(new_rss)
    save_cache(new_cache, keyname)

懒人守则

^{pr2}$

附言:在康基身上,从来没有“较短”是发送,因为这从来没有发生过,他等待孩子!(或类似的东西)

遭受的企图

在第一次尝试中,我使用multprocessinglib将一个新进程设置为守护进程(主程序不期望完成),但这不起作用。顺便说一句,这就造成了另一个问题:当主程序完成时,进程并行完成,而现在我没有更多的通知(或者简单的click例程不起作用,因为进程已经完成)!!!D:

编辑-1

如果我尝试在终端中运行,使用fork就可以了!但我真的有个问题要跑!为什么这样?此外,在sublime中,我有相同的行为:父进程只在子进程退出时退出。在


Tags: importselfparserurlcachenewgetreturn
1条回答
网友
1楼 · 发布于 2024-05-12 17:27:30

简单回答:对线程进行守护

我以前在其他线程中运行的片段,我只是把它放在这里(正如瓦伦丁·洛伦兹建议的那样)

from daemon import DaemonContext
with DaemonContext():
      paralell_notifications(new_rss)

总是很好,但是,只有在终点站和崇高。我的主要问题是谁的问题,我仍然有同样的问题。看来是个小虫子。在

为什么这样?因为他said

a daemon is a background, non-interactive program. It is detached from the keyboard and display of any interactive user. The word daemon for denoting a background program is from the Unix culture; it is not universal.

相关问题 更多 >