简体   繁体   中英

python time.sleep() doesn't work linux service

Hello I'm trying to make a linux ubuntu arm64 service in python. My problem is quite simple. I called the service 'bob'

My code for the service is:

import time
for i in range(0,99999999):
    print("hello", i)
    time.sleep(5)

在此处输入图像描述 Then in terminal:

systemctl restart bob
systemctl status bob

What i want to see is the information about the active service and the service saying hello [number] every 5 seconds but instead it shows nothing but the information about the active service 'working correctly'.

When i try it without the sleep function:

import time
for i in range(0,99999999):
    print("hello", i)

在此处输入图像描述 It works perfectly fine. Both status and 'hello 41234'. But with it, it doesn't. No errors show up anywhere and the cpu seems to be used by the service but no output.

You should use sys.stdout.flush() to flush the buffer and print the things to the terminal.

Eg,

import sys
import time
  
for i in range(10):
    print(i, end =' ')
    sys.stdout.flush()
    time.sleep(1)

Without sys.stdout.flush() , it will wait until the 10th second and at that time, it will print everything to the terminal.

More details here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM