1

我用 Python3 试试这个:

import os
fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
print(fd)

它总是在 Linux 中打印 3。/dev/tty 文件描述符总是 3 吗?

我想将 /dev/tty 与 stdin、stdout、stderr 区分开来。我最初的尝试是检查文件描述符,因为 stdin、stdout、stderr 返回 0、1 或 2。

我问这个的原因是因为要在 Python 中写入 /dev/tty,我必须使用字节而不是字符串,而使用 stdin、stderr、stdout,我必须使用字符串。

所以我的第二次尝试是:

try:
    if file.isatty() and file not in [sys.stdout,sys.stdin,sys.stderr]:
        use_bytes = True
    else:
        use_bytes = False
except AttributeError:
    use_bytes = False

有没有更好的方法来做到这一点?

4

0 回答 0