Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

python - When writing carriage return to a pycharm console the whole line is deleted?

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).

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.

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

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.

Sample code:

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 ('===')

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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)

Continue like this...

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

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

To keep the last printout, keep the default end.

print('
===')

Hope this works for you.

Frank


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...