【问题标题】:Updating lines in terminal while doing other stuff on the last one in Python?在 Python 中对最后一行执行其他操作时更新终端中的行?
【发布时间】:2017-09-11 16:11:15
【问题描述】:

我正在尝试编写一个 Python 程序来跟踪股票市场的价格并将其输出给用户,通过 stderr 刷新同一行,这是代码的简化版本(使用 randint 只是为了检查程序是否正在执行东西):

import random
import schedule
import time
import sys

def printran():
    a = "\rFirst Line is: " + str(random.randint(1,10))
    sys.stderr.write(a)

schedule.every(2).seconds.do(printran)

while True:
    schedule.run_pending()
    time.sleep(1)

我的问题是:

a) 如何“刷新”多行的控制台输出?

我尝试过类似的东西:

a = "\rFirst Line is: " + str(random.randint(1,10)) + "\n\rSecond Line is: " + str(random.randint(2,20))

但输出是一团糟,显然 \n 命令总是会生成一个新行

b) 由于 while 函数并没有真正结束我不能做其他事情,我需要使用多线程吗?

c) 找到一个尽可能简单、便携且与操作系统无关的解决方案(必须在 Linux、OSX、Win 上工作)。

【问题讨论】:

    标签: python terminal console console-application scheduling


    【解决方案1】:
    import random
    import schedule
    import threading
    import time
    
    def printran():
        print("First Line is: " + str(random.randint(1,10)))
    
    
    def run():
        schedule.every(2).seconds.do(printran)
        while True:
            schedule.run_pending()
            time.sleep(1)
    
    
    if __name__ == "__main__":
        t = threading.Thread(target=run)
        t.start()
    

    另外,您可以使用APScheduler 但在下面的代码中,sched.start() 不会等待,它会在 main 中停止。

    import random
    from apscheduler.schedulers.background import BackgroundScheduler
    import time
    
    def printran():
        print("First Line is: " + str(random.randint(1,10)))
    
    
    if __name__ == "__main__":
        sched = BackgroundScheduler()
        sched.add_job(printran, 'interval', seconds=2)
        sched.start()
        # wait 10 seconds and exit
        time.sleep(10)
    

    应该是跨平台的(我没在Win、Mac上查过,但是在linux上可以)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      相关资源
      最近更新 更多