我正在尝试在python中创建一个守护进程,我遇到了python-daemon包.有趣的是,我看到它使用的最常见的方式甚至不是那些非常稀疏的文档告诉你做的事情
import os
import grp
import signal
import daemon
import lockfile
from spam import (
initial_program_setup,
do_main_program,
program_cleanup,
reload_program_config,
)
context = daemon.DaemonContext(
working_directory='/var/lib/foo',
umask=0o002,
pidfile=lockfile.FileLock('/var/run/spam.pid'),
)
context.signal_map = {
signal.SIGTERM: program_cleanup,
signal.SIGHUP: 'terminate',
signal.SIGUSR1: reload_program_config,
}
mail_gid = grp.getgrnam('mail').gr_gid
context.gid = mail_gid
important_file = open('spam.data', 'w')
interesting_file = open('eggs.data', 'w')
context.files_preserve = [important_file, interesting_file]
initial_program_setup()
with context:
do_main_program()
Run Code Online (Sandbox Code Playgroud)
相反,人们使用它像这样:
#!/usr/bin/python
import time
from daemon import runner
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path …Run Code Online (Sandbox Code Playgroud) 我正在使用python-daemon,并且遇到的问题是,当我kill -9进行处理时,它会留下一个pid文件(ok),并且下次运行我的程序时它不起作用,除非我已经手动删除了pidfile(不是好).
我按照context.close()在终止之前调用的顺序捕获所有异常- 当发生这种情况时(例如在a上kill),删除/var/run/mydaemon.pid*文件并且后续守护程序运行成功.但是,使用SIGKILL(kill -9)时,我没有机会调用context.close(),并且/ var/run文件仍然存在.在这个例子中,下次我运行我的程序时它没有成功启动 - 原始进程返回,但是守护进程阻塞了context.open().
似乎python-daemon应该注意到有一个不再存在的进程的pidfile,并清除它,但这不会发生.我应该用手做这个吗?
注意:我没有使用,with因为此代码在Python 2.4上运行
from daemon import DaemonContext
from daemon.pidlockfile import PIDLockFile
context = DaemonContext(pidfile = PIDLockFile("/var/run/mydaemon.pid"))
context.open()
try:
retry_main_loop()
except Exception, e:
pass
context.close()
Run Code Online (Sandbox Code Playgroud) 我正在使用python-daemon包在python中编写一个守护进程.守护进程在启动时(init.d)启动,需要访问各种设备.守护进程是在运行ubuntu 的嵌入式系统(beaglebone)上运行的.
现在我的问题是我想将守护进程作为非特权用户运行而不是(例如mydaemon)root.
为了允许守护进程访问设备,我将该用户添加到所需的组中.在我使用的python代码中daemon.DaemonContext(uid=uidofmydamon).
该过程由rootdaemonizes很好地启动,并由正确的用户拥有,但在尝试访问设备时,我获得了权限被拒绝的错误.我写了一个小的测试应用程序,似乎该进程没有继承用户的组成员身份.
#!/usr/bin/python
import logging, daemon, os
if __name__ == '__main__':
lh=logging.StreamHandler()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(lh)
uid=1001 ## UID of the daemon user
with daemon.DaemonContext(uid=uid,
files_preserve=[lh.stream],
stderr=lh.stream):
logger.warn("UID : %s" % str(os.getuid()))
logger.warn("groups: %s" % str(os.getgroups()))
Run Code Online (Sandbox Code Playgroud)
当我以uid = 1001的用户运行上面的代码时,我得到类似的东西
$ ./testdaemon.py
UID: 1001
groups: [29,107,1001]
Run Code Online (Sandbox Code Playgroud)
而当我以root(或su)运行上面的代码时,我得到:
$ sudo ./testdaemon.py
UID: 1001
groups: [0]
Run Code Online (Sandbox Code Playgroud)
如何创建由root启动的守护程序进程,但具有不同的有效uid 和完整的组成员身份?
嗨,我尝试在python中创建一个守护进程,以便在Ubuntu服务器上运行.下面的代码是我遇到问题的代码.
import sys
import time
import threading
import logging
import logging.handlers
from daemon import runner
class Main(object):
def run(self):
my_logger = logging.getLogger('NameGeneratorDeamon')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address=('192.168.0.69', 514),facility=LOG_DAEMON)
my_logger.addHandler(handler)
try:
my_logger.info('Started')
while True:
pass
except Exception as inst:
#Send error to syslog server
my_logger.critical(inst)
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/null'
self.stderr_path = '/dev/null'
self.pidfile_path = '/tmp/foo.pid'
self.pidfile_timeout = 5
def run(self):
service = Main()
service.run()
app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()
Run Code Online (Sandbox Code Playgroud)
我运行代码时收到的错误消息如下:
File "Main.py", line 35, …Run Code Online (Sandbox Code Playgroud) 你们对以下应用程序使用哪些 python 模块有任何建议:我想创建一个运行 2 个线程的守护进程,两个线程都带有while True:循环。
任何例子将不胜感激!提前致谢。
更新:这是我想出的,但行为不是我所期望的。
import time
import threading
class AddDaemon(object):
def __init__(self):
self.stuff = 'hi there this is AddDaemon'
def add(self):
while True:
print self.stuff
time.sleep(5)
class RemoveDaemon(object):
def __init__(self):
self.stuff = 'hi this is RemoveDaemon'
def rem(self):
while True:
print self.stuff
time.sleep(1)
def run():
a = AddDaemon()
r = RemoveDaemon()
t1 = threading.Thread(target=r.rem())
t2 = threading.Thread(target=a.add())
t1.setDaemon(True)
t2.setDaemon(True)
t1.start()
t2.start()
while True:
pass
run()
Run Code Online (Sandbox Code Playgroud)
输出
Connected to pydev debugger (build 163.10154.50)
hi this …Run Code Online (Sandbox Code Playgroud) 我试图找出如何在运行".serve.forever()方法后在后台运行我重载的自定义BaseHTTPServer实例.
通常,当您运行该方法时,执行将挂起,直到您执行键盘中断,但我希望它在后台继续执行脚本时提供请求.请帮忙!
好的,我已经看过python-daemon,还有各种其他守护进程相关的代码配方.是否有任何"hello world"教程可以帮助我开始使用基于python的守护进程?
我在Ubuntu上有几个服务,它们将开始使用'upstart'.它们按照要求工作,但是当我使用'stop/start/restart {myservice}'时它将挂起(但会按要求执行).
我知道它与分叉有关.
我的服务是python脚本,它将在启动时创建新线程.一个脚本将创建1个新线程(并将继续在主线程上运行),第二个脚本将创建2个新线程并继续在主线程上运行,第三个将不创建新线程.
所有这些都挂在命令上.
所有在/ etc/init中使用相同的代码如下:
description "my service"
version "1.0"
author "my name, 2013"
expect fork
start on runlevel [2345]
stop on runlevel [!2345]
respawn
chdir <to script dir>
exec /usr/bin/python ./scriptname/
Run Code Online (Sandbox Code Playgroud)
您认为可能是什么问题?'fork'与创建新线程有什么关系吗?
I copied from here to run my Python code as a daemon. For extra uptime. I thought it would be a better Idea to use supervisor to keep this daemon running.
我这样做了。 python_deamon.conf
[program:python_deamon]
directory=/usr/local/python_deamon/
command=/usr/local/python_venv/bin/python daemon_runnner.py start
stderr_logfile=/var/log/gunicorn.log
stdout_logfile=/var/log/gunicorn.log
autostart=true
autorestart=true
Run Code Online (Sandbox Code Playgroud)
问题是,尽管主管成功启动了 python_daemon,但它一直在重试。
2015-09-23 16:10:45,592 CRIT Supervisor running as root (no user in config file)
2015-09-23 16:10:45,592 WARN Included extra file "/etc/supervisor/conf.d/python_daemon.conf" during parsing
2015-09-23 16:10:45,592 INFO RPC interface 'supervisor' initialized
2015-09-23 16:10:45,592 CRIT Server 'unix_http_server' running without any …Run Code Online (Sandbox Code Playgroud) 我已经下载了python-daemon包(https://pypi.python.org/pypi/python-daemon/)并尝试使用它安装它
python setup.py install
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误:
Traceback (most recent call last):
File "setup.py", line 22, in ?
main_module = __import__(main_module_name, fromlist=['version'])
TypeError: __import__() takes no keyword arguments
Run Code Online (Sandbox Code Playgroud)
我不确定是什么导致了这个.我尝试通过与下载的模块在同一目录中工作来解决它(在这种情况下我可以访问守护程序模块),但这导致了其他问题.
此外,我正在使用python 2.4.3,不幸的是更新不是一个选项.
我正在使用此处或此处引用的著名代码在 Python 中执行守护程序,如下所示:
import sys, daemon
class test(daemon.Daemon):
def run(self):
self.db = somedb.connect() # connect to a DB
self.blah = 127
with open('blah0.txt', 'w') as f:
f.write(self.blah)
# doing lots of things here, modifying self.blah
def before_stop(self):
self.db.close() # properly close the DB (sync to disk, etc.)
with open('blah1.txt', 'w') as f:
f.write(self.blah)
daemon = test(pidfile='_.pid')
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.before_stop() # AttributeError: test instance has no attribute …Run Code Online (Sandbox Code Playgroud) 他们似乎完成了管理流程的相同任务。Docker 和 Supervisor 有什么区别?
我有一个 python3.9 脚本,我想 24/7 运行。在其中,我使用python-daemon来保持它的运行,如下所示:
import daemon
with daemon.DaemonContext():
%%script%%
Run Code Online (Sandbox Code Playgroud)
它工作正常,但几个小时或几天后,它就会随机崩溃。我总是以以下方式启动它,sudo但我似乎无法弄清楚在哪里可以找到用于调试的守护进程进程的日志文件。我可以做什么来确保日志记录?如何让脚本保持运行或在崩溃后自动重新启动它?
您可以在此处找到完整的代码。
python-daemon ×13
python ×12
daemon ×7
linux ×2
python-3.x ×2
supervisord ×2
ubuntu ×2
centos ×1
docker ×1
process ×1
upstart ×1