Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is sys.stdin.fileno() in python

I am sorry if it's very basic or already asked before (I googled but couldn't find a simple & satisfactory explanation).

I want to know what sys.stdin.fileno() is?

I saw it in a code and didn't understand what it does. Here's the actual code block,

fileno = sys.stdin.fileno()
if fileno is not None:
    new_stdin = os.fdopen(os.dup(fileno))

I just executed print sys.stdin.fileno() in my python command line and it returned 0.

I also searched google, and this (nullage.com) is the reference I could find, but it also only says,

fileno() -> integer "file descriptor".

This is needed for lower-level file interfaces, such os.read().

So, what exactly does it mean?

like image 223
Codebender Avatar asked Aug 25 '15 08:08

Codebender


People also ask

What is fileno() in python?

The fileno() method returns the file descriptor of the stream, as a number. An error will occur if the operator system does not use a file descriptor.

What is Stdin Fileno?

stdin is a default FILE pointer used to get input from none other than standard in. STDIN_FILENO is the default standard input file descriptor number which is 0 . It is essentially a defined directive for general use.

What is a file descriptor in c?

File descriptor is integer that uniquely identifies an open file of the process. File Descriptor table: File descriptor table is the collection of integer array indices that are file descriptors in which elements are pointers to file table entries.


3 Answers

File descriptor is a low-level concept, it's an integer that represents an open file. Each open file is given a unique file descriptor.

In Unix, by convention, the three file descriptors 0, 1, and 2 represent standard input, standard output, and standard error, respectively.

>>> import sys
>>> sys.stdin.fileno()
0
>>> sys.stdout.fileno()
1
>>> sys.stderr.fileno()
2
like image 184
Yu Hao Avatar answered Sep 21 '22 08:09

Yu Hao


On Unix-like systems when you open a file (or a "file-like" entity) the system uses a file descriptor - an integer - on which you operate.

There are three standard file descriptors - standard input, standard output and standard error - with file descriptors 0, 1, 2 respectively.

The fileno() method returns the file descriptor of a file-like object in python.

like image 24
scytale Avatar answered Sep 22 '22 08:09

scytale


File descriptors are not unique to python. It's part of the POSIX API -- every flavour of UNIX will have them. However, Windows has similar concept of handles that for the most part is synonymous with file descriptors. Thus in python, fileno is used to represent both. They are just an low-level abstract reference to streams of data your program has available to it.

Have a look at the at the wiki page on file descriptors for more.

like image 32
Dunes Avatar answered Sep 18 '22 08:09

Dunes