如何暂停一个函数? - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yellowtail
V2EX    Python

如何暂停一个函数?

  •  
  •   yellowtail 2021-01-26 00:46:28 +08:00 1745 次点击
    这是一个创建于 1779 天前的主题,其中的信息可能已经有所发展或是发生改变。

    代码在 jupyternotebook 里写的,奇怪的是在办公室能用,家里不能用了... 整个功能就是用 apscheduler 定时运行生成随机数然后在 tkinter 里可视化 现在想保留原代码里 root.after 功能(因为直接用 root.after,按现在做法定时函数就没用了,因为 root.after 是循环的) 感觉可以用锁的方法,但是水平捉急写不出来,求指教。。

    ''' import datetime from apscheduler.schedulers.background import BackgroundScheduler import random import numpy as np from tkinter import * from tkinter import messagebox import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import multiprocessing from threading import Thread import time

    root = Tk() root.title("tkinter + Matplotlib") root.geometry('700x750') plt.rcParams['axes.unicode_minus']=False plt.rcParams['font.sans-serif'] = ['SimHei'] fig = plt.figure() ax1 = fig.add_subplot(1, 1, 1) ax2 = ax1.twinx() ax1.set_title('随机生成数') ax1.set_ylim() ax2.set_ylim() ax1.set_xlim(0, 200) ax2.set_xlim(0, 200) ax1.grid(True) ax1.set_xlabel("time") ax1.set_ylabel("随机数 1") ax2.set_ylabel("随机数 2") canvas = FigureCanvasTkAgg(fig, master=root) canvas.draw() canvas.get_tk_widget().pack() x = 0 ran1 = [] ran2 = [] times = [] def drawImg(): global ran1 global ran2 global times global x global ax1 global ax2 v1 = float(random.randint(-5, 5)) r1 = float(random.randint(-10, 10)) ran1.append(v1) ran2.append(r1) times.append(x) x += 1 ax1.clear() ax2.clear() ax1.axes.set_ylim(min(ran1)-5, 5+max(ran1)) ax2.axes.set_ylim(min(ran2)-5, 5+max(ran2)) ax1.axes.set_xlim(x-200+200, x+20) ax2.axes.set_xlim(x-200+20, x+20) ax1.plot(times, ran1,'y') ax2.plot(times, ran2,'r') canvas.draw() #global afterHandler #afterHandler = root.after(10, drawImg) #print(datetime.datetime.now()) def sub_task(): drawImg() def task_(time): def task__(): temp = BackgroundScheduler() temp.add_job(sub_task,'interval',secOnds= 1,end_date =str(datetime.datetime.now())[:17]+time) temp.start() return task__ sche_fn = BackgroundScheduler() sche_fn.add_job(task_('25'),'cron',day_of_week = 'mon-fri',hour = '*',minute = '*',secOnd= '0' ) sche_fn.start() sche_an = BackgroundScheduler() sche_an.add_job(task_('55'),'cron',day_of_week = 'mon-fri',hour = '*',minute = '*',secOnd= '30' ) sche_an.start() def on_closing(): sche_an.shutdown() sche_fn.shutdown() #root.after_cancel(afterHandler) answer = messagebox.askokcancel("退出", "确定退出吗?") if answer: plt.close('all') root.destroy() else: root.after(1000, drawImg) root.protocol("WM_DELETE_WINDOW", on_closing) root.mainloop() 
    shniubobo
        1
    shniubobo  
       2021-01-27 09:39:42 +08:00 via Android   1
    如果要暂停函数的话可以考虑`yield`。函数里有`yield`的话,调用函数会返回一个生成器。`next(生成器)`会让函数运行到`yield`处中断,并返回`yield`的值,这样就相当于暂停了函数。有关`yield`见 python 文档语言参考部分,`next`见标准库参考部分。
    还有就是考虑协程了,见标准库的`asyncio`。python 早期的协程其实也是基于上面说的生成器的。
    yellowtail
        2
    yellowtail  
    OP
       2021-01-30 17:50:31 +08:00
    @shniubobo 感谢回复。
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     979 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 22ms UTC 22:50 PVG 06:50 LAX 14:50 JFK 17:50
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86