如何使用try exception b同时运行两个函数

2024-10-03 11:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

Make 2 functions run at the same time使用线程。它可以同时实现两种功能。是否可以在try except块中使用线程调用函数?你知道吗

import threading
from threading import Thread
import time

def queryRepeatedly():
    while True:
        while True:
            try:
                Thread(target = foo).start()
                Thread(target = bar).start()
                print ''
            except:
                continue
            else:
                break

def foo():
      print 'foo'
      time.sleep(1)
def bar():
      print 'bar'
      time.sleep(3)

queryRepeatedly()

这是我的代码不工作,我需要运行两个功能分别尝试除了块。我该怎么办?你知道吗


Tags: import功能truefootimedefbar线程
1条回答
网友
1楼 · 发布于 2024-10-03 11:22:09

我想这可能就是你想要的:

import threading
from threading import Thread
import time

def queryRepeatedly():
   Thread(target = foo).start()
   Thread(target = bar).start()

def foo():
    while True:
        try:
            print 'foo'
        except : #catch your error here
           pass # handle your error here
        finally:
           time.sleep(1)
def bar():
    While True:
        try:
           print 'bar'
        except : #catch your error here
           pass # handle your error here
        finally:
           time.sleep(3)

queryRepeatedly()

相关问题 更多 >