首页 文章

Python每秒增加一个数字

提问于
浏览
1

我怎样才能每秒增加一个数字?我在考虑这样的事情 .

import  threading

def printit():
    second = 1
    while threading.Timer(1, printit).start(): #for every second that pass.
        print(second)
        second += 1

printit()

2 回答

  • 3

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

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

    time.sleep(secs)暂停执行当前线程达到给定的秒数 .

  • 1

    有几种方法可以做到这一点 . 其他人建议的第一个是

    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>
    

相关问题