Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我怎样才能并行运行一个函数,并且在主程序退出后,他仍然继续运行? TL;博士_Python_Parallel Processing_Multiprocessing_Pygtk - Fatal编程技术网

Python 我怎样才能并行运行一个函数,并且在主程序退出后,他仍然继续运行? TL;博士

Python 我怎样才能并行运行一个函数,并且在主程序退出后,他仍然继续运行? TL;博士,python,parallel-processing,multiprocessing,pygtk,Python,Parallel Processing,Multiprocessing,Pygtk,如何使用多处理库或其他方式保持并行进程独立于主进程运行?(示例代码现在正在使用fork) 悠久的历史 嗯,我正在为conky配置的后端编写一个小脚本,其中一个是rss\u parser.py,它获取一组标题/URL并放在标准输出上。最近,我想知道当RSS列表上出现新内容时,如何使用GTK的Notify激活新通知 但我这里有些问题。我设置了一个打开链接的操作,因此当我的通知发出时,我可以单击并打开浏览器。这部分代码需要等待用户单击或通知接近完成,这是在一个适当的事件循环中运行的。但是,这与其他内容

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

悠久的历史 嗯,我正在为conky配置的后端编写一个小脚本,其中一个是
rss\u parser.py
,它获取一组标题/URL并放在标准输出上。最近,我想知道当RSS列表上出现新内容时,如何使用
GTK的
Notify
激活新通知

但我这里有些问题。我设置了一个打开链接的操作,因此当我的通知发出时,我可以单击并打开浏览器。这部分代码需要等待用户单击或通知接近完成,这是在一个适当的事件循环中运行的。但是,这与其他内容冲突:要更新我的conky我需要在不需要通知部分的情况下完成我的主脚本!所以我的想法是把通知放在平行的位置

来自地狱的密码 我用完整的代码尝试了这一点:(检查
parallel\u notify
功能)

懒人代码 注:在康基身上,从来没有“短”这个词,因为这从来没有发生过,他在等孩子!(或诸如此类)

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

编辑-1
如果我尝试在终端中运行,使用
fork
效果很好!但我真的有一个问题在康奇跑!为什么会这样?此外,在
sublime
中,我有同样的行为:父进程只有在子进程退出时才会退出

简短回答:对线程进行后台监控

我以前在其他线程中运行的代码片段,我只是把它放在这里(正如Valentin Lorentz所建议的)

而且总是很好,然而,只有在终端和崇高。我的主要问题是谁的问题,我仍然有同样的问题。似乎是康基上的一只虫子

为什么会这样?因为他:

守护进程是一个后台的非交互式程序。它是分离的 从任何交互式用户的键盘和显示器。守护进程这个词 表示后台程序来自Unix文化;事实并非如此 普遍的


使用这个库:你能给我一个例子来解决我的问题吗?谢谢
#!/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)
import os
if os.fork() == 0:
     os.setsid()
     while True:
         pass
print('shorter')
from daemon import DaemonContext
with DaemonContext():
      paralell_notifications(new_rss)