Python finds stdin file path on Linux

How can I specify a file (or tty) attached to my stdios?

Sort of:

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

I could look in proc:

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

But it looks like there should be an inline way?

+5
source share
2 answers

Got it!

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

It raise OSError: [Errno 22] Invalid argumentif stdin is not TTY; but it's easy enough to check withisatty()

+1
source

Objects sys.std * standard file Python objects , so they have nameand isattymethod :

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

In short, exactly what you have on a TTY device is that the API extension is offered by Python.

+2
source

All Articles