繁体   English   中英

如何使用try异常块同时运行两个功能

[英]How to run two function in the same time with using try exception block

Make 2函数通过使用线程同时运行 它可以同时执行两个功能。 是否可以在try除了块中用线程调用函数?

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

这我的代码不起作用,我需要用try除了块分别运行两个功能。 我该怎么办?

我认为这可能是您要寻找的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM