鱼C论坛

 找回密码
 立即注册
查看: 3467|回复: 4

[已解决]如何设置某段代码运行超过10秒抛出异常?

[复制链接]
发表于 2016-6-28 15:39:18 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. with open(filename, "wb") as file:
  2.             file.write(data)
复制代码

请教各位怎么设置?
最佳答案
2016-6-29 10:35:52
import threading
import time
#import os

flag=0#定义一个标志,用来判定方法是否执行完

def testfunc():#主要方法
    time.sleep(5)
#    with open(filename, "wb") as file:
#        file.write(data)
    global flag
    flag=1
   

def timefunc():#计时抛出异常方法
    if(flag==0):
        print('error')
    else:
        print('ok')

def mainfunc():
    t=threading.Timer(3.0, timefunc)#计时线程
    t.start()
#    t1=threading.Timer(4.0, testfunc)
#    t1.start()
    testfunc()
   

mainfunc()#测试

这个应该是要用多线程的方式,python我也刚了解,大家帮忙改改。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-6-28 21:08:14 | 显示全部楼层
import time
star=time.clock()
with open(filename, "wb") as file:
            file.write(data)
en=time.clock()
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-6-29 09:12:16 | 显示全部楼层
时间控制?没用过,过来学习一下,冒个泡
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-6-29 09:18:16 | 显示全部楼层
1324901134 发表于 2016-6-28 21:08
import time
star=time.clock()
with open(filename, "wb") as file:

你这不对啊,如果open一直打开就不会执行后面,得到第二个时间
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-6-29 10:35:52 | 显示全部楼层    本楼为最佳答案   
import threading
import time
#import os

flag=0#定义一个标志,用来判定方法是否执行完

def testfunc():#主要方法
    time.sleep(5)
#    with open(filename, "wb") as file:
#        file.write(data)
    global flag
    flag=1
   

def timefunc():#计时抛出异常方法
    if(flag==0):
        print('error')
    else:
        print('ok')

def mainfunc():
    t=threading.Timer(3.0, timefunc)#计时线程
    t.start()
#    t1=threading.Timer(4.0, testfunc)
#    t1.start()
    testfunc()
   

mainfunc()#测试

这个应该是要用多线程的方式,python我也刚了解,大家帮忙改改。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-21 12:18

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表