Python每秒增加一个数字

时间:2015-12-21 17:12:00

标签: python python-3.x

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

import  threading

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

printit()

2 个答案:

答案 0 :(得分:3)

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

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

time.sleep(秒)

     

暂停执行给定的当前线程   秒数。

答案 1 :(得分: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>