Python printing character-by-character in OSX Terminal - python

I'm trying to have Python copy the contents of a .txt file into the bash terminal on OS X (10.10), but the line does not print until every single character of the line has been printed to the line. Is there any way to have Python print each line character-by-character, instead of line-by-line? My code is designed to wait between characters, but each line simply takes a long time to print:
while True:
character = text_file.read(1)
if not character: break
else:
sys.stdout.write(character)
time.sleep(0.050)
When I run this code in IDLE, the characters print one at a time. In Terminal, lines take several seconds to print, and each line prints all at once. Is there any way to reproduce the behavior I'm seeing in IDLE in Terminal?

Add sys.stdout.flush() after sys.stdout.write(character)
The reason should be that the output of stdout is buffered.

if you want remove new line at the end of the line.
you can simply
print character,
will remove the new line(\n).

Related

End of File Input Python

I am trying to solve Kattis problem. The full problem is found in the link: https://open.kattis.com/problems/addingwords
The part of the problem that I'm confused with is : "Input is a sequence of up to 2000 commands, one per line, ending at end of file."
What would be the code for this input? I tried doing this:
import sys
for line in sys.stdin.readlines():
#print('something')
After this, I continued the program as normal within the indentation from above. My question is, how would I test whether the program is working in cmd? I want to test a few cases, but when I input something, the command prompt keeps waiting for other results instead of printing anything out. And when I press control C the program ends abruptly. How are we supposed to check whether the program is working while taking in user input till end of file?
The problem here is that readlines() is eager not lazy. That means it will read the entire file into memory (until EOF) and then split it into lines and return a list of those lines. So when working with interactive stdin, sys.stdin.readline() will wait until the end of stdin (Ctrl-D on linux/macOS, Ctrl+Z on windows).
But there is no need for readlines() (and in fact, you almost should never use it). Iterating over a file object by default does so by lines:
for line in sys.stdin:
print('got line!')
The docs even admit that you should do this. If you do need all lines in a list, then just do list(sys.stdin).

Delete a complete line in python 3 output

How can I delete a complete line in the output screen of python?
Can I use the escape sequence '\b' for this?
What your asking is somewhat terminal-specific. However, the following solution should work in both Linux and Windows.
Write \r to return to the beginning of the current line.
Write as many spaces as needed to "cover" any previous content on the line.
Write \r to return to the beginning of the current line again.
Write the new text for this line.

What's behind sys.stdin.readlines()

Question 1:
I have a piece of code like this (Python2.7):
for line in sys.stdin.readlines():
print line
When I run this code, input a string in the terminal and press Enter key, nothing happens. 'print line' doesn't work.
So I imagine there is buffer for sys.stdin.readlines(), but I wonder how does it work? Can I flush it so every time a line is given, 'print line' can be executed imeediatly?
Question2: What's the difference between these two lines:
for line in sys.stdin:
for line in sys.stdin.readline():
I found their behavior is a little different. If I use ctrl+D to terminate the input, I have to press ctrl+D twice in the first case before it's really terminated. While in the second case, only one ctrl+D is enough.
CTRL-D sends the EOF (end of file) control character to stdin in an interactive shell. Usually, you feed a file to the stdin of a process via redirection (e.g. myprogram < myfile), but if you are interactively typing characters into stdin of a process, you need to tell it when to stop reading the "file" you are actively creating.
sys.stdin.readlines waits for stdin to complete (via an EOF control character), then conveniently splits the entire stdin contents (flushed) before the EOF into a list of tokens delimited by newline characters. When you hit ENTER, you send a \n character, which is rendered for you as a new line, but does NOT tell stdin to stop reading.
Regarding the other two lines, I think this might help:
Think of the sys.stdin object as a file. When you EOF, you save that file and then you are not allowed to edit it anymore because it leaves your hands and belongs to stdin. You can perform functions on that file, like readlines, which is a convenient way to say "I want a list, and each element is a line in that file". Or, you can just read one line from it with readline, in which case the for loop would be only iterating over the characters in that line.
What's going on behind the scenes?
Internally, the reference to sys.stdin blocks execution until EOF is received in sys.stdin. Then it becomes a file-like object stored in memory with a read pointer pointing to the beginning.
When you call just readline, the pointer reads until it hits a \n character, returns to you what it just traversed over, and stays put, waiting for you to move it again. Calling readline again will cause the pointer to move until the next \n, if it exists, else EOF.
readlines is really telling the pointer to traverse all the way (\n is functionally meaningless) from its current position (not necessarily beginning of file) until it sees EOF.
Try it out!
Trying it out is the best way to learn.
To see this behavior in action, try making a file with 10 lines, then redirect it to the stdin of a python script that prints sys.stdin.readline 3 times, then print sys.stdin.readlines. You'll see 3 lines printed out then a list containing 7 elements :)

Eclipse/PyDev treats newlines pasted into its console as instructions, but I want it to parse them as part of a long string

I am working on a Python script to automate some repetitive text-fiddling tasks I need to do. I use PyDev as a plugin for Eclipse as my IDE.
I need the script to accept user input pasted from the clipboard. The input will typically be many lines long, with many newline characters included.
I currently have the script asking for input as follows:
oldTableString = raw_input('Paste text of old table here:\n')
The console correctly displays the prompt and waits for user input. However, once I paste text into the console, it appears to interpret any newline characters in the pasted text as presses of the enter button, and executes the code as if the only input it received was the first line of the pasted text (before the first newline character), followed by a press of the enter key (which it interprets as a cue that I'm done giving it input).
I've confirmed that it's only reading the first line of the input via the following line:
print oldTableString
...which, as expected, prints out only the first line of whatever I paste into the console.
How can I get Eclipse to recognize that I want it to parse the entirety of what I paste into the console, newlines included, as a single string?
Thanks!
text = ""
tmp = raw_input("Enter text:\n")
while tmp != "":
text += tmp + "\n"
tmp = raw_input()
print text
This works but you have to press enter one more time.
What about reading directly from the clipboard or looping over every line until it receives a termination symbol or times out. Also, is it important to make it work under Eclipse? Does it work when executed directly?

Terminal screen coordinates in python

I'm newbie in using curses lib. I want to make a python program (running in a DOS terminal) that can return the cursor to the start of the current line allowing subsequent output to overwrite what was previously written there. I tried to call a shellscript from python to do it, but I beleive it may exist a better way for doing it.
If all you want to do is rewrite the current line, just print a return char "\r". For example, this prints "ABCdef":
# print 'abcdef' then backup to start of line, then print 'ABC'
# (then print the normal cr/lf that 'print' always does)
print "abcdef\rABC"
(Also helpful to know that you can suppress the cr/lf by ending your print with a trailing comma...)
.

Categories

Resources