1

I am trying to create a module init and a module mydaemon in Python 2.7 under Debian 7.

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.

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

import mydaemon, threading

print 'start'
t = threading.Thread( target = mydaemon.start, args = () )
t.daemon = True # error here
t.start()

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
B--rian
  • 5,578
  • 10
  • 38
  • 89
sheepy
  • 56
  • 6

2 Answers2

0

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:

...
t.start()

import time
time.sleep(1)

This is discussed in more detail at 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()
CasualDemon
  • 5,790
  • 2
  • 21
  • 39
  • 1
    Hi, the logging still fail, but the file is created. – sheepy Feb 06 '14 at 08:24
  • Ah, sorry tried this on a windows system not debian. The issue is because when it's made as a thread, the thread will die as soon as the main program dies. So it doesn't have enough time to write to the file before the main program exists. I will update my answer. – CasualDemon Feb 06 '14 at 18:23
  • A concise and helpful starting point (in German) is https://www.thomaschristlieb.de/ein-python-script-mit-systemd-als-daemon-systemd-tut-garnicht-weh/ [Auto-Translatation](https://translate.google.de/translate?sl=auto&tl=en&u=https%3A%2F%2Fwww.thomaschristlieb.de%2Fein-python-script-mit-systemd-als-daemon-systemd-tut-garnicht-weh%2F) – B--rian Mar 07 '19 at 15:09
0

My collage found another method with external Daemon module (python-daemon)

http://www.gavinj.net/2012/06/building-python-daemon-process.html

In the tutorial have some error but read comments ;-)

sheepy
  • 56
  • 6