在Linux上用Python查找stdin文件路径

5 投票
2 回答
1595 浏览
提问于 2025-04-16 18:41

我怎么才能知道我的标准输入输出(stdio)连接的是哪个文件(或者终端)呢?

类似于这样:

>>> import sys
>>> print sys.stdin.__path__
'/dev/tty1'
>>>

我可以查看proc文件夹:

import os, sys
os.readlink('/proc/self/fd/%s' % sys.stdin.fileno())

但似乎应该有一种内置的方法可以做到这一点吧?

2 个回答

2

sys.std* 对象是标准的 Python 文件对象,所以它们有一个name 属性和一个isatty 方法

>>> import sys
>>> sys.stdout.name
'<stdout>'
>>> sys.stdout.isatty()
True
>>> anotherfile = open('/etc/hosts', 'r')
>>> anotherfile.name
'/etc/hosts'
>>> anotherfile.isatty()
False

除了告诉你具体的 TTY 设备是什么,Python 提供的 API 就到此为止了。

1

明白了!

>>> import os
>>> import sys
>>> print os.ttyname(sys.stdin.fileno())
'/dev/pts/0'
>>>

如果标准输入(stdin)不是一个终端设备(TTY),那么会出现一个错误,提示是 OSError: [Errno 22] Invalid argument;不过这很容易检查,可以用 isatty() 来测试。

撰写回答