I am reading the source code of testinfra
in the Ansible module. I found the following lines of code:
# Ansible return an unicode object but this is bytes ...
# A simple test case is:
# >>> assert File("/bin/true").content == open("/bin/true").read()
stdout_bytes = b"".join((chr(ord(c)) for c in out['stdout']))
stderr_bytes = b"".join((chr(ord(c)) for c in out['stderr']))
It iterates over stdout
, gets the integer ordinal of each character and converts it back to a one-character string. But what's the point?
Python chr() and ord() Python's built-in function chr() is used for converting an Integer to a Character, while the function ord() is used to do the reverse, i.e, convert a Character to an Integer.
The Python ord() function converts a character into an integer that represents the Unicode code of the character. Similarly, the chr() function converts a Unicode code character into the corresponding string.
Python ord() and chr() are built-in functions. They are used to convert a character to an int and vice versa. Python ord() and chr() functions are exactly opposite of each other.
The chr() function returns the character that represents the specified unicode.
When c
is unicode-specific character (cannot be encoded in ASCII):
>>> ord(u'\u2020')
8224
>>> chr(ord(u'\u2020'))
ValueError: chr() arg not in range(256)
This is only true in Python2, as in Python3, unichr is removed and chr acts as unichr. This seems to be unusual behavior for such a library, since it would routinely throw an unexpected error that's executable-specific for any non-English locale.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With