为了账号安全,请及时绑定邮箱和手机立即绑定

将计时器添加到此脚本中的这些文件中的 1 个

将计时器添加到此脚本中的这些文件中的 1 个

温温酱 2022-05-19 18:45:35
我有 2 个文件同时打印在同一行。我想将 time.sleep() 添加到 1 个文本文件中。我想延迟此脚本中 1 个文本文件与其他 1 个文本文件打印的时间。我想让文件创建新行,而不是在它们都打印时打印相同的组合。在哪里添加 time.sleep()?from itertools import izip_longestimport timewith open("file1") as textfile1, open("file2") as textfile2:for x, y in izip_longest(textfile1, textfile2, fillvalue=""):    x = x.strip()    y = y.strip()    print("{0}{1}".format(x, y))
查看完整描述

2 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

您只能打印 x(不带换行符),然后休眠并打印 y。


Python 2 解决方案:


import time

from itertools import izip_longest

import sys


with open("file1") as textfile1, open("file2") as textfile2:

    for x, y in izip_longest(textfile1, textfile2, fillvalue=""):

        x = x.strip()

        sys.stdout.write("{0}".format(x))

        sys.stdout.flush()

        time.sleep(1)

        y = y.strip()

        sys.stdout.write("{0}".format(y))

        sys.stdout.write("\n")

        sys.stdout.flush()

Python 3 解决方案


from itertools import zip_longest

import time


with open("file1") as textfile1, open("file2") as textfile2:

    for x, y in zip_longest(textfile1, textfile2, fillvalue=""):

        x = x.strip()

        print("{0}".format(x), end='')

        time.sleep(1)

        y = y.strip()

        print("{0}".format(y))


查看完整回答
反对 回复 2022-05-19
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

目前尚不清楚你想要什么,但我想它是这样的


#! /usr/bin/env python3


from rx import from_, interval, merge, zip

from rx.scheduler import ThreadPoolScheduler


pool = ThreadPoolScheduler(10)



f1 = from_(open('f1.txt'))

f2 = from_(open('f2.txt'))


o1 = merge(

    f1,

    zip(interval(1.0), f2)

    )


o1.subscribe(print, scheduler=pool)

o1.run()

它使用RxPy。并且像这样工作:

  1. 为文件 1 创建 observable

  2. 为文件 2 创建 observable

  3. 创建另一个合并 f1 和 f2 的 observable,它以 1 秒的间隔发射

  4. 订阅和打印

  5. 等到它完成


查看完整回答
反对 回复 2022-05-19
  • 2 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号