无法逐行输出:print(var,end='')

2024-10-01 07:48:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我在跨平台系统上为ping主机编写了一个代码。你知道吗

代码内容如下:

import psutil
import subprocess

proc = subprocess.Popen(["ping -c 5 8.8.8.8"],shell=True)
for x in range(5):
    getLoading = psutil.cpu_percent(interval=1)
    print(str(getLoading),end='<--')

print('done')

我希望我能得到如下结果:

64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
5.0<--
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
4.5<--
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
4.1<--
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
3.5<--    
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
4.0<--
done

我在Windows7/python3.4.3上得到了预期的结果,但在centos6.5/python3.4.3上没有得到结果。 Linux上的结果如下所示:

64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
64 bytes from 8.8.8.8: icmp_seq=1 ttl=128 time=5ms
5.0<--4.5<--4.1<--3.5<--4.0<--done

有哪位python专家能帮我找出根本原因吗? 谢谢。你知道吗


Tags: 代码fromimportbytestime跨平台pingseq
2条回答

这让我想起了打印函数“缓冲”一些数据,然后再写入。 我在代码中使用print时也遇到过类似的问题。为了避免这种问题,我会使用一个记录器,这将立即打印代码

import logging
FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(
    format=FORMAT, level=logging.DEBUG, datefmt='%Y/%m/%d %H:%M:%S')
logger = logging.getLogger('MyLogger')
logger.setLevel(logging.INFO)


import psutil
import subprocess

proc = subprocess.Popen(["ping -c 5 8.8.8.8"], shell=True)
for x in range(5):
    getLoading = psutil.cpu_percent(interval=1)
    logger.info(str(getLoading) + '< ')

logger.info('done')

您需要读取进程的标准输出,并对其进行一些控制,这样您就可以在线打印“进程加载”。你知道吗

示例:

#!/usr/bin/env python

from __future__ import print_function

import sys
import psutil
import subprocess

try:
    range = xrange
except NameError:
    pass


p = subprocess.Popen(["ping",  "-c", "5", "8.8.8.8"], stdout=subprocess.PIPE)

encoding = sys.getdefaultencoding()

for line in p.stdout:
    load = psutil.cpu_percent(interval=1)
    print("{0:s}{1:0.2f}< ".format(line.decode(encoding), load))
print("done")

输出:

$ ./foo.py 
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
21.10< 
64 bytes from 8.8.8.8: icmp_seq=1 ttl=52 time=15.6 ms
15.40< 
64 bytes from 8.8.8.8: icmp_seq=2 ttl=52 time=15.6 ms
13.20< 
64 bytes from 8.8.8.8: icmp_seq=3 ttl=52 time=15.6 ms
20.70< 
64 bytes from 8.8.8.8: icmp_seq=4 ttl=52 time=15.5 ms
19.90< 
64 bytes from 8.8.8.8: icmp_seq=5 ttl=52 time=15.6 ms
11.00< 

19.50< 
 - 8.8.8.8 ping statistics  -
17.40< 
5 packets transmitted, 5 received, 0% packet loss, time 4007ms
12.90< 
rtt min/avg/max/mdev = 15.596/15.629/15.669/0.114 ms
16.60< 
done

NB:这是为了与Python 2/3兼容而编写的。你知道吗

相关问题 更多 >