continuosly running function in background in python

I want to run a function continuoulsy in parallel to my main process.How do i do it in python?multiprocessing?threading or thread module? I am new to python.Any help much appreciated.


If the aim is to capture stderr and do some action you can simply replace sys.stderr by a custom object:

>>> import sys
>>> class MyLogger(object):
...     def __init__(self, callback):
...             self._callback = callback
...     def write(self, text):
...             if 'log' in text:
...                     self._callback(text)
...             sys.__stderr__.write(text)   # continue writing to normal stderr
... 
>>> def the_callback(s):
...     print('Stderr: %r' % s)
... 
>>> sys.stderr = MyLogger(the_callback)
>>> sys.stderr.write('Some log messagen')
Stderr: 'Some log message'
Some log message
>>> 
>>> sys.stderr.write('Another messagen')
Another message

If you want to handle tracebacks and exceptions you can use sys.excepthook .

If you want to capture logs created by the logging module you can implement your own Handler class similar to the above Logger but reimplementing the emit method.

A more interesting, but less practical solution would be to use some kind of scheduler and generators to simulate parallel execution without actually creating threads(searching on the internet will yield some nice results about this)


It definitely depends on your aim, but I'd suggest looking at the threading module. There are many good StackOverflow questions on the use of threading and multithreading (eg, Multiprocessing vs Threading Python).

Here's a brief skeleton from one of my projects:

import threading  # Threading module itself 
import Queue      # A handy way to pass tasks to your thread 

job_queue = Queue.Queue()
job_queue.append('one job to do')

# This is the function that we want to keep running while our program does its thing
def function_to_run_in_background():
    # Do something...here is one form of flow control 
    while True:
        job_to_do = job_queue.get()  # Get the task from the Queue
        print job_to_do              # Print what it was we fetched 
        job_queue.task_done()        # Signal that we've finished with that queue item

# Launch the thread...
t = threadingThread(target=function_to_run_in_background, args=(args_to_pass,)) 
t.daemon = True  # YOU MAY NOT WANT THIS: Only use this line if you want the program to exit without waiting for the thread to finish 
t.start()        # Starts the thread 
t.setName('threadName') # Makes it easier to interact with the thread later 

# Do other stuff 
sleep(5)
print "I am still here..."
job_queue.append('Here is another job for the thread...')

# Wait for everything in job_queue to finish. Since the thread is a daemon, the program will now exit, killing the thread. 
job_queue.join()

如果你只是想在同一个进程中在后台运行一个函数,可以这样做:

import thread

def function(a):
    pass

thread.start_new(function, (1,)) # a is 1 then
链接地址: http://www.djcxy.com/p/55212.html

上一篇: 扫描网站的内容(快速)

下一篇: 在Python中的后台连续运行函数