Python 3.0+osfunction
os.device_encoding
os — terminals and devices
Return the encoding of the device tied to a file descriptor, or None.
Syntax
os.device_encoding(fd)
For a descriptor not attached to a terminal — a file, pipe or redirected output — it returns None. So it cannot tell the output encoding of a program run with redirection; in UTF-8 mode (since Python 3.7) the standard streams use UTF-8 regardless of the terminal. sys.stdout.encoding is the simpler way to check the current encoding.
Examples
import os
enc = os.device_encoding(0)
print(enc is None or isinstance(enc, str)) # → True (в терминале это кодировка вроде 'UTF-8', в консоли Windows 'cp866'; None, если stdin перенаправлен из файла или пайпа)
fd = os.open('demo.txt', os.O_CREAT | os.O_WRONLY)
print(os.device_encoding(fd)) # → None (обычный файл не терминал)
os.close(fd)
print(os.device_encoding(999)) # → None (для неверного дескриптора исключения не будет)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy