简体   繁体   中英

Get the path of the current TTY in Python

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

Python has sys.stdin , sys.stdout and os.ttyname but you cannot pass either of the formers to the latter because it requires a file descriptor.

You can pass sys.stdout.fileno to os.ttyname :

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

This may have portability issues, but in most Unix-like environments /dev/stdout refers to the current terminal and is unique to each connection [windows, tabs, ssh, etc.] you have open. Given those assumptions you can use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM