昨天我正在做一个项目,我遇到了一个我以前没有遇到过的问题。我目前正在使用argparse请求输入文件名,并且我正在向我的程序添加对通过stdin传输文件的支持。我已经完成了所有的工作,除了我通过管道将文件传送到我的程序时遇到的termios问题,我想知道是否有人知道解决方案。我得到的确切错误是
old_settings = self.termios.tcgetattr(fd)
termios.error: (25, 'Inappropriate ioctl for device')这特别来自getkey模块,因为我需要一些非阻塞输入的东西(请随时通知我更好的选项)。我假设这是因为它的标准I/O流因为管道而没有连接到终端,但我不知道是否有方法可以真正解决这个问题,我在stackoverflow或Google上也找不到任何解决方案。下面是一个最小的可重现的例子:
# Assuming filename is test.py, running
# python3 test.py
# works, but running
# cat test.py | python3 test.py
# or
# python3 test.py < test.py
# results in an error
import sys
import termios
termios.tcgetattr(sys.stdin.fileno())发布于 2021-07-15 02:32:36
我想出了一个使用pty模块的解决方案,这是我以前不知道的。我给出的例子可以通过使用pty.fork()将孩子连接到一个新的伪终端来修复。这个程序似乎起作用了:
import pty
import sys, termios
pid = pty.fork()
if not pid:
# is child
termios.tcgetattr(sys.stdin.fileno())我还找到了一个解决方案,用于确定错误是否来自使用subprocess创建的新python进程。此版本利用pty.openpty()创建新的伪终端对。
import subprocess, pty, sys
# Create new tty to handle ioctl errors in termios
master_fd, slave_fd = pty.openpty()
proc = subprocess.Popen([sys.executable, 'my_program.py'], stdin=slave_fd)希望这对其他人有所帮助。
https://stackoverflow.com/questions/68352333
复制相似问题