[英]Python module threading as daemon with logging
I am trying to create a module init
and a module mydaemon
in Python 2.7 under Debian 7. 我正在尝试在Debian 7下的Python 2.7中创建模块
init
和模块mydaemon
。
The module init
checks the requirements such as db connections etc. Then, mydaemon
runs in a thread and uses the database to do things and write a logfile. 模块
init
检查诸如数据库连接之类的要求。然后, mydaemon
在线程中运行,并使用数据库来做事并编写日志文件。
The problem when setting up the thread daemon is that the logging and function call fails. 设置线程守护程序时的问题是日志记录和函数调用失败。 But if the thread not daemon working fine...
但是如果线程没有守护程序正常工作...
Where am I wrong or what will be a better approach? 我在哪里错了?有什么更好的方法?
init.py init.py
import mydaemon, threading
print 'start'
t = threading.Thread( target = mydaemon.start, args = () )
t.daemon = True # error here
t.start()
mydaemon.py mydaemon.py
import logging
def start():
work()
return
def work():
logging.basicConfig( filename = 'mylog.log', level = logging.DEBUG )
logging.info('foo log')
print 'foo console'
return
Making it as a deamon means the background thread dies as soon as the main app closes. 将其设置为守护进程意味着后台线程在主应用程序关闭时立即死亡。 Your code 'works' as is, simply add a pause to init.py to model this behavior:
您的代码按原样“工作”,只需在init.py中添加一个暂停即可对这种行为进行建模:
...
t.start()
import time
time.sleep(1)
This is discussed in more detail at http://pymotw.com/2/threading/#daemon-vs-non-daemon-threads . 有关详细信息,请参见http://pymotw.com/2/threading/#daemon-vs-non-daemon-threads 。
The simply way to fix this is to join the thread. 解决此问题的简单方法是加入线程。
import mydaemon, threading
print 'start'
t = threading.Thread( target = mydaemon.start, args = () )
t.daemon = True # error here
t.start()
t.join()
My collage found another method with external Daemon module (python-daemon) 我的拼贴找到了另一种使用外部守护程序模块(python-daemon)的方法
http://www.gavinj.net/2012/06/building-python-daemon-process.html http://www.gavinj.net/2012/06/building-python-daemon-process.html
In the tutorial have some error but read comments ;-) 在教程中有一些错误,但请阅读注释;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.