如何使用多处理库或其他方式使并行进程独立于main运行? (示例代码现在使用fork)
好吧,我正在为我的conky配置编写一个后端的小脚本,其中一个是rss_parser.py
,它得到一组标题/网址并加上标准输出。最近,我想知道在RSS列表中出现新内容时,使用Notify
GTK
来激活新通知的内容。
但我在这里遇到了一些问题。我打开了一个操作来打开链接,所以当我的通知启动时,我可以点击并打开浏览器。代码的这一部分需要等待用户点击或接近完成的通知,其中正在以适当的事件循环运行。但是,这与其他事情冲突:更新我的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)
import os
if os.fork() == 0:
os.setsid()
while True:
pass
print('shorter')
ps:在conky上,从来没有'更短'发送,因为这从未发生过,他等着孩子! (或类似的东西)
在第一次尝试时,我使用多处理 lib来设置一个新进程作为守护进程(对主程序不希望完成),但这不起作用。顺便说一下,这又产生了另一个问题:当主程序完成时,Process并行完成,现在我没有更多的通知(或简单的点击例程不起作用,因为该过程已经结束)! d:
如果我尝试在终端中运行,使用fork
可以正常工作!但我有一个真正的问题在conky跑!为什么这个?在sublime
中,我也有同样的行为:父进程仅在子项退出时退出。
答案 0 :(得分:0)
简短回答:守护线程
我曾经在其他帖子中运行的片段,我只是把它(如Valentin Lorentz建议的那样)
from daemon import DaemonContext
with DaemonContext():
paralell_notifications(new_rss)
然而,总是工作正常,只有在终端和崇高。我的主要问题,是谁,他仍然有同样的问题。看起来像是一个错误。
为什么这样?因为他said:
守护进程是一种后台非交互式程序。它是独立的 从键盘和任何交互式用户的显示。单词守护进程 表示后台程序来自Unix文化;它不是 通用