Get path to current TTY in Python

How do you get the device path for the current TTY?

Python has sys.stdin, sys.stdoutand os.ttyname, but you cannot pass any of the shapers to the latter, because this requires a file descriptor.

+4
source share
2 answers

You can pass sys.stdout.filenoto os.ttyname:

In [3]: os.ttyname(sys.stdout.fileno())
Out[3]: '/dev/pts/24'
+5
source

This may have portability problems, but in most Unix-like environments it /dev/stdoutrefers to the current terminal and is unique to every connection [windows, tabs, ssh, etc.] that you opened. Given these assumptions, you can use:

with open('/dev/stdout') as fd:
    tty_path = os.ttyname(fd.fileno())
+1
source

All Articles