代码之家  ›  专栏  ›  技术社区  ›  Horai Nuri

Python每秒递增一个数字

  •  1
  • Horai Nuri  · 技术社区  · 10 年前

    如何每秒递增一个数字?我在想这样的事情。

    import  threading
    
    def printit():
        second = 1
        while threading.Timer(1, printit).start(): #for every second that pass.
            print(second)
            second += 1
    
    printit()
    
    2 回复  |  直到 10 年前
        1
  •  3
  •   Assem    10 年前

    我建议使用不同的方法 time.sleep(1) ,解决方案是:

    from time import sleep
    def printit():
    ...     cpt = 1
    ...     while True:
    ...         print cpt
    ...         sleep(1)
    ...         cpt+=1
    

    睡眠时间(秒)

    为给定的挂起当前线程的执行 秒数。

        2
  •  1
  •   DustinPianalto    10 年前

    有几种方法可以做到这一点。正如其他人所建议的,第一个是

    import time
    
    def print_second():
        second = 0
        while True:
            second += 1
            print(second)
            time.sleep(1)
    

    这个方法的问题是它会停止程序其余部分的执行(除非它在另一个线程中运行)。另一种方式允许您在同一个循环中执行其他过程,同时仍将第二个计数器定罪并每秒打印一次。

    import time
    
    def print_second_new():
        second = 0
        last_inc = time.time()
        while True:
            if time.time() >= last_inc + 1:
                second += 1
                print(second)
                last_inc = time.time()
     #       <other code to loop through>