【问题标题】:Python finding stdin filepath on LinuxPython 在 Linux 上查找标准输入文件路径
【发布时间】:2011-09-05 16:02:34
【问题描述】:

我如何知道附加到我的 stdios 的文件(或 tty)?

类似:

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

我可以在 proc 中查看:

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

但似乎应该有一个内置的方式?

【问题讨论】:

    标签: python stdin filepath


    【解决方案1】:

    知道了!

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

    如果标准输入不是 TTY,则为 raises OSError: [Errno 22] Invalid argument;但这很容易用isatty()进行测试

    【讨论】:

      【解决方案2】:

      sys.std* 对象是standard Python file objects,所以它们有一个name attribute 和一个isatty method

      >>> 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 的扩展。

      【讨论】:

      • 请记住 stdout 等。人。可能是一个没有name 和/或isatty() 的类文件对象,所以你应该为这种情况做好准备。
      • 我希望找出我连接的 TTY 设备(如果 stdios 连接到 TTY)
      • @kindall:当然;对于标准输出,只需要一个write 方法。 @tMC:那么您所能做的就是检查“/proc”文件系统,或者如果操作系统通过库提供此类信息,请使用 ctypes 访问该信息。 AFAIC 没有进一步的 stdlib python API。
      猜你喜欢
      • 2022-06-11
      • 1970-01-01
      • 2021-06-24
      • 2021-02-06
      • 1970-01-01
      • 2017-06-10
      • 2016-06-15
      • 2022-07-19
      • 2018-05-25
      相关资源
      最近更新 更多