Python os.device_encoding() Method
-
Syntax of Python
os.device_encoding()
Method -
Example 1: Use
os.device_encoding()
When Connected to a Terminal -
Example 2: Use
os.device_encoding()
When Not Connected to a Terminal

The device_encoding()
method belongs to the os
module. The os
module is a built-in module in Python that offers various robust and simple utilities to interact with the operating system.
The device_encoding()
method returns the encoding of the device that is connected to the passed file descriptor.
Syntax of Python os.device_encoding()
Method
os.device_encoding(fd)
Parameters
Parameter | Type | Description |
---|---|---|
fd |
integer | A file descriptor associated with a valid resource. |
Returns
The device_encoding()
method returns a string value. It returns the encoding of the device linked to the fd
file descriptor.
The device_encoding()
method returns a valid output only if fd
is connected with a terminal. Otherwise, it returns None
.
This means that connection with a terminal is mandatory to get a valid encoding.
Example 1: Use os.device_encoding()
When Connected to a Terminal
import os
master, slave = os.openpty()
print("Status:", os.isatty(master))
print("Device Encoding:", os.device_encoding(master))
Output:
Status: True
Device Encoding: UTF-8
The Python code above first creates a pseudo-terminal pair or, in simple terms, a terminal with the help of the openpty()
method. Note that this feature is specific to UNIX-based systems.
Hence, it will not work on Windows operating system. Next, we use the isatty()
method to check the terminal’s status.
This method returns True
if a file descriptor is connected to a terminal. Next, we retrieve the device encoding with the help of the device_encoding()
method.
Example 2: Use os.device_encoding()
When Not Connected to a Terminal
import os
fd = os.open("a.txt", os.O_RDONLY)
print("Status:", os.isatty(fd))
print("Device Encoding:", os.device_encoding(fd))
Output:
Status: False
Device Encoding: None
The Python code above first opens a text file. Since the fd
file descriptor point to a text file and not a terminal, the status is False
, and the device encoding is None
.
Related Article - Python OS
- Python os.set_handle_inheritable() Method
- Python os.set_inheritable() Method
- Python os.stat_result Class
- Python os.renames() Method
- Python os.get_handle_inheritable Method
- Python os.get_inheritable Method