检索控制台上的最后一个打印字符

时间:2015-01-21 23:09:18

标签: python

我想在python中获取控制台上写的最后一个字符。 例如,我可能有多个线程在控制台上写入,然后在每个线程中我需要知道其他线程写入控制台的最后一个字符。有什么办法吗?

e.g: >> print 'Hello' 在这种情况下,最后一个字符是'\ n' 或

Thread A:
>>> print 'Hello'
Thread B:
>>> print 'Bye'
Thread C:
>>> What is the last written character?

很明显,除非我们以某种方式询问控制台,否则我们无法在线程C中确定答案。

2 个答案:

答案 0 :(得分:1)

取决于您写信的位置。如果您正在写入标准输出sys.stdout(通常情况下) - 它无法阅读。所以技术上没有。你可以做的是使用输出管道输出到其他人并在stdout已经刷新它之后抓住它。

这是Ubuntu OS下的一个示例,但在任何操作系统中都可能存在等价物:

示例脚本(p.py):

print "hello"

取最后一个两个字符中的第一个从\n跳过换行符(print):

reut@sharabani:~$ python p.py | tail -c2 | head -c1
o

编辑:

如果您无法访问headtail,则在python中执行此操作应该很简单:

编写脚本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]

现在只需使用:

python p.py | python take_last_char.py

答案 1 :(得分:0)

除非您在计划中更改end功能的print参数,否则它始终为\n

相关问题