【问题标题】:how can i show two output in a same time in terminal with python?如何使用 python 在终端中同时显示两个输出?
【发布时间】:2014-06-04 14:56:01
【问题描述】:

我的程序中需要这个输出:

   from __future__ import print_function
   import time
   import threading

  def timer():
   for h in range(0, 24):
    for m in range(0, 60):
      for s in range(0, 60):
        time.sleep(1)
        print ("Elapsed time : %s:%s:%s" % (h, m, s), end="\r")

  def insert_record():
     #do insert record operation below code is sample     
        count = 0
        for i in range(1, 100):
           count += 1
           time.sleep(1)
           print ("Inserted records in mysql database : %s " % count, end="\r")

  if __name__ == "__main__":
    threading.Thread(target=insert_record()).start()
    threading.Thread(target=timer()).start()

直到 insert_record function() 工作,timer() 函数在下一行显示经过的时间。 但没有在终端显示经过的时间:-( 刚刚在终端中显示了 insert_record() 输出。

我想要这个输出:

在mysql数据库中插入记录:5456672

经过时间:20:15:30

请帮助我,抱歉英语口述不好。

【问题讨论】:

  • 您想在命令行循环中运行程序吗?或者你是在谈论程序中的一个循环,它应该显示每个循环的时间?你得说清楚,否则很难帮上忙。
  • 你能再次看到我的代码吗?

标签: python printing timer multiprocessing output


【解决方案1】:
  1. 通过给它函数来启动一个线程,不要立即调用该函数:)

  2. 默认输出是缓冲的。使用sys.stderrlogging 模块。

    未来 导入 print_function 导入系统,时间 导入线程

    定义计时器(): 对于范围内的 h (0, 24): 对于范围内的 m (0, 60): 对于范围内的 s (0, 60): 时间.sleep(1) sys.stderr.write( "已用时间 : %s:%s:%s\n" % (h, m, s) )

    定义插入记录(): #do 插入记录操作下面的代码是示例
    计数 = 0 对于范围内的 i (1, 100): 计数 += 1 时间.sleep(1) sys.stderr.write( "在 mysql 数据库中插入的记录 : %s\n" % count )

    如果 name == "ma​​in": 打印('开始') threading.Thread(target=insert_record).start() threading.Thread(target=timer).start()

    print('join')
    for t in threading.enumerate():
        if t != threading.current_thread():
            t.join()
    

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 2013-06-06
    • 2017-11-20
    • 2020-09-26
    • 2019-04-22
    • 2020-02-06
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多