Python| os.device_encoding() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。
Python中的os.device_encoding()
方法用于获取与指定文件描述符关联的设备的编码,如果它连接到终端。如果指定的文件描述符未连接到终端,则此方法返回 None。
注意:此方法仅适用于某些版本的 UNIX。
Syntax: os.device_encoding(fd)
Parameter:
fd: A file descriptor, whose device encoding is to be queried.
Return Type: This method returns a string value which represents the encoding of the device associated with the specified file descriptor if it is connected to a terminal, otherwise None.
代码:使用 os.device_encoding() 方法获取与给定文件描述符关联的设备的编码
# Python program to explain os.device_encoding() method
# importing os module
import os
# File path
path = "/home/ihritik/Desktop/file.txt"
# Open the file and get
# the file descriptor associated
# with it using os.open() method
fd = os.open(path, os.O_RDWR | os.O_CREAT)
# Check if file descriptor fd
# is open and connected
# to a terminal using os.isatty() method
print("Connected to a terminal:", os.isatty(fd))
# Print the encoding of
# the device associated with
# the file descriptor fd
# using os.device_encoding() method
print("Device encoding:", os.device_encoding(fd))
# Open a new pseudo-terminal pair
# using os.openpty() method
# It will return master and slave
# file descriptor for
# pty ( pseudo terminal device) and
# tty ( native terminal device) respectively
master, slave = os.openpty()
# Check if file descriptor master
# is open and connected
# to a terminal using os.isatty() method
print("Connected to a terminal:", os.isatty(master))
# Print the encoding of
# the device associated with
# the file descriptor master
# using os.device_encoding() method
print("Device encoding:", os.device_encoding(master))
输出:
Connected to a terminal: False
Device encoding: None
Connected to a terminal: True
Device encoding: UTF-8