我如何在python子进程中使用睡眠功能

时间:2018-08-01 03:19:27

标签: python subprocess stdout sleep

executor.py

$regs = DB::table('registrations')
   ->select('createddatetime', DB::raw('COUNT(id) as count'))
   ->groupBy(DB::raw('DATEPART(hour, createddatetime)'), 'createddatetime')
   ->get();

starter.py

from time import sleep
if __name__ == "__main__"
for i in range(10):
    print(i)
    sleep(1)

在Shell中

from subprocess import Popen, PIPE

if __name__ == "__main__"
    process = Popen(['python', 'executor.py'], stdout=PIPE, universal_newlines=True)
    while process.poll() is None:
        output = process.stdout.readline()
        print(output)
    process.wait()

命令执行后的结果如下     #稍后10秒之后...     0     1个     2     3     4     5     6     7     8     9
    我要每个秒打印一次     我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

缓冲标准输出。您应该在每个print之后刷新缓冲区:

from time import sleep
import sys
if __name__ == "__main__":
    for i in range(10):
        print(i)
        sys.stdout.flush()
        sleep(1)