两个 while 循环一次?

Luc*_*ips 2 python irc loops while-loop

我正在用 Python 制作一个 IRC 机器人。while每次从 IRC 服务器接收到数据时,都会有一个循环重复。我想有另一个while每分钟运行一次的循环,所以我想不出组合这些循环的方法。

有没有办法“背景”一个循环并允许程序的其余部分在它“做它的事情”时继续运行?

K D*_*awG 5

这个简单的例子应该让你开始,在这种情况下有两个 while 循环,time.sleep(seconds)用于模拟一些工作

import threading
import time

def func_1():
    i = 0
    while i<5:
        i += 1
        time.sleep(1.5) # Do some work for 1.5 seconds
        print 'func_1'

def func_2():
    i = 0
    while i<5:
        i += 1
        time.sleep(0.5) # Do some work for 0.5 seconds
        print 'func_2'

thread1 = threading.Thread(target=func_1)
thread1.start()
thread2 = threading.Thread(target=func_2)
thread2.start()
Run Code Online (Sandbox Code Playgroud)

产生:

func_2 #0.5 seconds elapsed
func_2 #1.0 seconds elapsed
func_1 #1.5 seconds elapsed finally func_1 :)
func_2 #1.5 threading is not mutithreading! ;)
func_2 #2.0 seconds elapsed
func_2 #2.5 seconds elapsed and since variable i is 5 func_2 is no more :(
func_1 #3.0 seconds elapsed
func_1 #4.5 seconds elapsed
func_1 #6.0 seconds elapsed
func_1 #7.5 seconds elapsed
Run Code Online (Sandbox Code Playgroud)

编辑:

我的意思是说threading is not mutithreading! ;),如果有任何机会,您认为func_1func_2并发执行1.5 seconds是不正确的,因为线程在同一内存空间中运行,但如果您使用multiprocessing 它们,则它们具有单独的内存空间并且会并发运行

最后,对于您的情况,您应该使用threading它,因为它更适合这些类型的任务