Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unix 如何将/dev/tty与stdin、stdout、stderr区分开来?_Unix_Python 3.x_Console Application - Fatal编程技术网

Unix 如何将/dev/tty与stdin、stdout、stderr区分开来?

Unix 如何将/dev/tty与stdin、stdout、stderr区分开来?,unix,python-3.x,console-application,Unix,Python 3.x,Console Application,我用Python3试试这个: import os fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY) print(fd) 它总是在Linux中打印3。/dev/tty文件描述符总是3吗 我想用stdin、stdout、stderr区分/dev/tty。我最初的尝试是检查文件描述符,因为stdin、stdout、stderr返回0、1或2 我问这个问题的原因是,为了用Python编写/dev/tty,我必须使用字节而不是字符串,而对于stdin、std

我用Python3试试这个:

import os
fd = os.open('/dev/tty', os.O_RDWR|os.O_NOCTTY)
print(fd)
它总是在Linux中打印3。/dev/tty文件描述符总是3吗

我想用stdin、stdout、stderr区分/dev/tty。我最初的尝试是检查文件描述符,因为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

有更好的方法吗?

当您调用open时,会得到一个新的文件描述符。进程启动时,0、1、2已打开。所以3是一个新创建的文件描述符。在现有文件对象上使用.fileno()可以查看文件描述符编号;fd=os.open('/dev/tty',os.O|RDWR | os.O|nocty);a=os.fdopen(fd,“wb+”,缓冲=0);如果(a.fileno()==3)其他打印('no,它不是/dev/tty'),则打印('it is/dev/tty')?所以在所有UNIX平台上,在所有情况下/dev/tty文件描述符都将是3?不,你没有抓住要点。在UNIX中,默认情况下总是:stdin==0、stdout==1和stderr==2。忘记3。三个是不存在的。它是您的代码的产物。你在用什么操作系统?如果有/proc文件系统,则可以查看进程的打开文件/dev/tty是一个设备(实际上是一个文件),它不是一个文件描述符。打开文件时,您可以创建文件描述符(1,2,3,4…)。不要打开任何文件。在stdin上使用fileno(),而不是/dev/tty。我想我理解你的意思。如果我的函数接受file对象作为参数,并且我们希望检查此参数是否为/dev/tty,那么我只需确保参数的fileno不是0,1,2,并且file对象是tty。是吗?/de/tty是控制终端。这是进程内部控制终端设备的名称。isatty可以为stdin、stdout和stderr返回true。因为这三个都已经打开了/dev/tty。并非所有进程都有控制终端。