我正在尝试在BASH shell中尝试重定向,尽管这也可以在Windows命令提示符shell中使用Python的os.system
函数。我的问题是我试图将输出从Python脚本重定向到文本文件,并且Python脚本不会出于任何奇怪的语法原因而这样做。所以,我写了一个小的毫无意义的程序来试图理解这个问题。以下是我的源代码:
import os
for i in range(10):
os.system('ping -c 1 localhost')
print("finishing pinging the localhost - %d" % i)
当我在shell中运行它时:$ python scriptName.py程序打印:
--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.080/0.080/0.080/0.000 ms
finishing pinging the localhost - 0
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.073 ms
--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.073/0.073/0.073/0.000 ms
finishing pinging the localhost - 1
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.191 ms
--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.191/0.191/0.191/0.000 ms
finishing pinging the localhost - 2
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.076 ms
我只显示上面BASH shell的前三行输出。但是,当我使用某种类型的重定向运行程序时,我收到了这个不同的输出,从我的视图中也有更多不受欢迎的输出。所以,如果我像这样运行程序:$python myScript > out.txt
。我收到以下输出:
--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.076/0.076/0.076/0.000 ms
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.077 ms
--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.077/0.077/0.077/0.000 ms
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.082 ms
--- localhost ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.082/0.082/0.082/0.000 ms
finishing pinging the localhost - 0
finishing pinging the localhost - 1
finishing pinging the localhost - 2
finishing pinging the localhost - 3
finishing pinging the localhost - 4
finishing pinging the localhost - 5
finishing pinging the localhost - 6
finishing pinging the localhost - 7
finishing pinging the localhost - 8
finishing pinging the localhost - 9
我将文件的输出编辑为仅显示底部。底部显示打印的行,"完成ping本地主机 - #"在ping
程序的所有结果之后打印。这与脚本在shell中运行并且未重定向时原始程序和输出的逻辑完全不同。
有人知道为什么添加重定向时输出会有所不同吗?
答案 0 :(得分:1)
Python print语句的输出被缓冲,并在脚本完成时写入文件(或者当缓冲区已满时,在打印文本数量较大的情况下),而外部输出电话正在立刻写下来。当输出通过管道输送到终端以外的其他设备时会发生这种情况。
你需要flush
缓冲区来解决这个问题:
import os
for i in range(10):
os.system('ping -c 1 localhost')
print("finishing pinging the localhost - %d" % i, flush=True)
如果您不使用Python> 3.3,则需要执行以下操作:
import os
import sys
for i in range(10):
os.system('ping -c 1 localhost')
print("finishing pinging the localhost - %d" % i)
sys.stdout.flush()