Reputation: 676
I'd like to get the last character written on the console in python. For example I may have several threads which write on the console then in each of the threads I need to know the last character that has been written to the console by other threads. Is there any way?
e.g:
>> print 'Hello'
the last character is '\n' in this case
or
Thread A:
>>> print 'Hello'
Thread B:
>>> print 'Bye'
Thread C:
>>> What is the last written character?
And it's obvious we can't determine the answer in thread C unless we ask the Console in some way.
Upvotes: 0
Views: 6036
Reputation: 31339
Depends on where you're writing to. If you're writing to standard output sys.stdout
(the usual case) - it's not open for reading. So technically no. What you could do is use a pipe the output to someone else and grab it after stdout already flushed it.
This is an example under Ubuntu OS, but there are probably equivalents in any OS:
And example script (p.py
):
print "hello"
Take the first of last two characters to skip newline (\n
) from print
:
reut@sharabani:~$ python p.py | tail -c2 | head -c1
o
If you do not have access to head
and tail
it should be simple to do this in python:
write the script take_last_char.py
:
import sys
# read whatever output the previous script piped here
# but only keep the last line (stripping the newline...)
for line in sys.stdin:
tmp = line.strip()
print tmp[-1]
And now simply use:
python p.py | python take_last_char.py
Upvotes: 3
Reputation: 4035
Unless you change end
parameter of print
function in your program, it'll be always \n
.
Upvotes: 0