如何实现每天用Jupyter写5分钟的日记

发布时间:2021-10-23 09:46:06 作者:iii
来源:亿速云 阅读:123

本篇内容介绍了“如何实现每天用Jupyter写5分钟的日记”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

导入 ipywidgets 模块

首先,你需要导入一堆东西,比如 ipywidgets 和 Twisted。Twisted 模块可以用来创建一个异步时间计数器:

import twisted.internet.asyncioreactortwisted.internet.asyncioreactor.install()from twisted.internet import reactor, taskimport ipywidgets, datetime, subprocess, functools, os

设置定时条目

用 Twisted 实现时间计数器是利用了 task.LoopingCall。然而,结束循环调用的唯一方法是用一个异常。倒计时时钟总会停止,所以你需要一个自定义的异常来指示“一切正常;计数器结束”:

class DoneError(Exception):    pass

现在你已经写好了异常,你可以写定时器了。第一步是创建一个 ipywidgets.Label 的文本标签组件。循环使用 divmod 计算出分和秒,然后设置标签的文本值:

def time_out_counter(reactor):    label = ipywidgets.Label("Time left: 5:00")    current_seconds = datetime.timedelta(minutes=5).total_seconds()    def decrement(count):        nonlocal current_seconds        current_seconds -= count        time_left = datetime.timedelta(seconds=max(current_seconds, 0))        minutes, left = divmod(time_left, minute)        seconds = int(left.total_seconds())        label.value = f"Time left: {minutes}:{seconds:02}"        if current_seconds < 0:            raise DoneError("finished")    minute = datetime.timedelta(minutes=1)    call = task.LoopingCall.withCount(decrement)    call.reactor = reactor    d = call.start(1)    d.addErrback(lambda f: f.trap(DoneError))    return d, label

从 Jupyter 组件中保存文本

下一步是写一些东西,将你输入的文字保存到一个文件中,并提交到 Git。另外,由于你要写 5 分钟的日记,你需要一个能给你提供写字区域的组件(滚动肯定是可以的,但一次能看到更多的文字就更好了)。

这就用到了组件 Textarea,这是一个你可以书写的文本字段,而 Output 则是用来给出反馈的。这一点很重要,因为 git push 可能会花点时间或失败,这取决于网络。如果备份失败,用反馈提醒用户很重要:

def editor(fname):    textarea = ipywidgets.Textarea(continuous_update=False)    textarea.rows = 20    output = ipywidgets.Output()    runner = functools.partial(subprocess.run, capture_output=True, text=True, check=True)    def save(_ignored):        with output:            with open(fname, "w") as fpout:                fpout.write(textarea.value)            print("Sending...", end='')            try:                runner(["git", "add", fname])                runner(["git", "commit", "-m", f"updated {fname}"])                runner(["git", "push"])            except subprocess.CalledProcessError as exc:                print("Could not send")                print(exc.stdout)                print(exc.stderr)            else:                 print("Done")    textarea.observe(save, names="value")    return textarea, output, save

continuous_update=False 是为了避免每个字符都保存一遍并发送至 Git。相反,只要脱离输入焦点,它就会保存。这个函数也返回 save 函数,所以可以明确地调用它。

创建一个布局

最后,你可以使用 ipywidgets.VBox 把这些东西放在一起。这是一个包含一些组件并垂直显示的东西。还有一些其他的方法来排列组件,但这足够简单:

def journal():    date = str(datetime.date.today())    title = f"Log: Startdate {date}"    filename = os.path.join(f"{date}.txt")    d, clock = time_out_counter(reactor)    textarea, output, save = editor(filename)    box = ipywidgets.VBox([        ipywidgets.Label(title),        textarea,        clock,        output    ])    d.addCallback(save)    return box

biu!你已经定义了一个写日记的函数了,所以是时候试试了。

journal()

如何实现每天用Jupyter写5分钟的日记

Jupyter journal

你现在可以写 5 分钟了!

“如何实现每天用Jupyter写5分钟的日记”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. PHP 每天用一点
  2. 用谷歌打开jupyter的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jupyter

上一篇:Windows事件追踪入门与使用方式是什么

下一篇:Windows中的zabbix agentd该怎么安装

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》