Python Glossary Русский

all Python 3osfunction

os.urandom

os — system

Return n cryptographically strong random bytes from the OS.

Syntax

os.urandom(n)

It is suitable for cryptography: keys, tokens, salts. The random module is not — it is predictable. Application code is better served by the secrets module built on the same source: secrets.token_hex(16) yields a string right away. It returns bytes, not a number or a string.

Examples

import os
print(len(os.urandom(8)))   # → 8
print(os.urandom(0))   # → b''
token = os.urandom(16)
print(len(token.hex()))   # → 32, по два hex-символа на байт — типовой способ получить токен
print(os.urandom(4) == os.urandom(4))   # → False, каждый вызов даёт новые байты
print(os.urandom(-1))   # → ValueError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy