我在我的 python 脚本中使用一个子进程来打开一个 .bat
文件。这个 .bat
文件生成了很长的行,我想实时打印到控制台。
问题是这些行有时很长,以至于它们不适合缓冲区。无论如何,我该怎么做才能打印这些行?如果逐行打印,是否可以逐字打印?
这是我所做的:
p = subprocess.Popen("testfile.bat", stdin=subprocess.PIPE)
p.stdin.write("\r\n") # Some basic setup (simulated keypress)
p.stdin.close()
# The actual print loop
for line in iter(p.stdout.readline, ''):
line = line.replace('\r', '').replace('\n', '')
print(line)
sys.stdout.flush()
最佳答案
您可以删除此行,不需要它:
line = line.replace('\r', '').replace('\n', '')
如果您想逐字打印,请执行以下操作:
for line in iter(p.stdout.readline, ''):
for word in line.split():
print(word)
sys.stdout.flush()
关于python - 如何在python中实时打印长行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18766297/