更新终端中的行,同时在Python中的最后一行上做其他事情?

时间:2017-09-11 16:11:15

标签: python terminal console console-application scheduling

我正在尝试编写一个跟踪股票市场价格的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上运行)。

1 个答案:

答案 0 :(得分:0)

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)