如何解决如何在标准输入中使用 Python 诅咒?
我正在尝试编写一个 Python 程序,该程序使用 Curses 显示/编辑来自标准输入的文本。 我云实现编辑模块,但我无法将标准输入作为输入。
我该如何解决这个问题?
import curses
def main(stdscr):
while key := stdscr.getkey():
stdscr.addstr(0,key)
if __name__ == '__main__':
curses.wrapper(main)
echo "hello" | python edit.py
Traceback (most recent call last):
File "/path/to/edit.py",line 8,in <module>
curses.wrapper(main)
File "/path/to/.pyenv/versions/3.9.1/lib/python3.9/curses/__init__.py",line 94,in wrapper
return func(stdscr,*args,**kwds)
File "/path/to/edit.py",line 4,in main
while key := stdscr.getkey():
_curses.error: no input
并且python edit.py
(没有回声“hello”)成功完成。
解决方法
首先,您必须从 stdin 而不是从 curses.getkey() 中读取数据,因为它们是通过管道传输的。
所以你可以先读取标准输入然后初始化然后在curses中显示内容:
import sys
import curses
stdin_content = ()
def main(stdscr):
stdscr.clear() # and other curses init...
while True:
for i,line in enumerate(stdin_content):
stdscr.addstr(2 + i,2,"> " + line)
stdscr.refresh()
key = stdscr.getch()
stdscr.timeout(1000)
if key == ord('q'):
break
if __name__ == '__main__':
stdin_content = sys.stdin.readlines()
curses.wrapper(main)
您可以启动:
$ echo "hello" | python edit.py
一切都很好,您可以显示在 ncurses 中传递给脚本的一行或几行(如果您 cat
包含多行内容)。
但是如果您之前阅读过标准输入,则存在 getch() 不起作用的问题,因此即使它应该这样做,您也无法使用“q”退出。
@Frédéric Hamidi 在这里回答了这个问题: Linux: Pipe into Python (ncurses) script,stdin and termios 阅读他的回答以了解更多细节,但基本上你必须重复标准输入。
在 main 中读取 stdin 后立即添加此行:
os.dup2(3,0)
而不是这样调用:
$ echo "hello" | python edit.py
这样调用:
$ (echo "hello" | python edit.py) 3<&0
或者像这样生成子shell:
$ exec 3<&0
然后正常调用
$ echo "hello" | python edit.py
$ cat test.txt | python edit.py
您可以阅读链接的答案和文档以进一步了解。 无论如何,希望这会有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。