在Python中的后台连续运行函数

我想与我的主进程并行运行函数continuoulsy。我该如何在python?multiprocessing?线程或线程模块中执行? 我是新来的python.Any帮助非常感谢。


如果目标是捕获stderr并执行一些操作,则可以简单地使用自定义对象替换sys.stderr

>>> 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

如果你想处理回溯和异常,你可以使用sys.excepthook

如果你想捕获日志模块创建的logging你可以实现你自己的Handler类,类似于上面的Logger但是重新实现emit方法。

一个更有趣但不太实际的解决方案是使用某种调度器和生成器来模拟并行执行,而不实际创建线程(在互联网上搜索会产生一些关于此的好结果)


它绝对取决于你的目标,但我建议看看线程模块。 关于使用threadingmultithreading有很多好的StackOverflow问题(例如,多进程与线程Python)。

以下是我的一个项目的简要介绍:

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/55211.html

上一篇: continuosly running function in background in python

下一篇: jython multithreading