向pycharm控制台写回车时,整行都被删除了吗? [英] When writing carriage return to a pycharm console the whole line is deleted?

查看:32
本文介绍了向pycharm控制台写回车时,整行都被删除了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Python 程序,它广泛使用换行符来产生更新控制台行(特别是进度条)的效果.

I have a program in Python that makes extensive use of the line feed character to produce the effect of an updating console line (specifically a progress bar).

当我尝试在 PyCharm 中调试代码时,我看到进度条在完成之前不会被打印出来.

When trying to debug the code in PyCharm I saw that the progress bar doesn't get printed until it's done.

进一步检查发现,当打印回车( )时,整行被删除.

Upon further inspection it turned out that when a carriage return ( ) is printed, the whole line is deleted.

因为库本身写入格式为 ({line} ) 的字符串,所以我总是得到一个空行.

Because the library itself writes strings of the form ({line} ), I always get an empty line.

有没有办法使用 PyCharm 解决这个问题?目前我要做的是将 stdout 替换为记录当前行并在收到回车后重新打印它的版本.不过我更希望有一个简单的方法来做到这一点.

Is there any way to solve this using PyCharm? Currently what I'll be doing is replacing stdout with a version that records the current line and reprints it after a carriage return is received. However I'd much rather have a simple way to do it.

示例代码:

import sys
sys.stdout.write('xxx')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('
ZZ')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('yyy
')
sys.stdout.flush()

time.sleep(1)

print ('===')

我的跑步是这样的:
1. 'xxx' 被打印出来
[1 秒后]
2. 'ZZ' 被打印出来
[1 秒后]
3.线路被删除
[1 秒后]
4. '===' 被打印出来,程序终止

My run looks like this:
1. 'xxx' is printed
[After 1 second]
2. 'ZZ' is printed
[After 1 second]
3. The line is deleted
[After 1 second]
4. '===' is printed and the program terminates

在运行此脚本时,调试和运行控制台都会发生这种情况.

This happens both in the debug and the run console when running this script.

推荐答案

我最近遇到了同样的问题,并找到了解决方案.答案实际上在您的帖子中.正如你所说,回车删除整行.为避免此问题,请仅在打印新行时打印回车,如下所示:

I recently ran into the same problem, and found a solution. The answer is actually in your post. As you said, the carriage return deletes the whole line. To avoid the issue, print the carriage return only when you print the new line, like so:

打印每一行,在开始时使用回车符,并且没有默认的 end=' '.不需要冲洗,虽然我没有做太多测试.

Print each line with the carriage return at the start, and without the default end=' '. Didn't need the flush, though I didn't do much testing.

print('
xxx', end='')
# sys.stdout.flush()
time.sleep(1)

这样继续……

print('
ZZ', end='')
time.sleep(1)

print('
yyy', end='')
time.sleep(1)

要保留最后的打印输出,请保留默认结束.

To keep the last printout, keep the default end.

print('
===')

希望这对你有用.

弗兰克

这篇关于向pycharm控制台写回车时,整行都被删除了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆