Python os.urandom() Method

Musfirah Waseem Jan 30, 2023
  1. Syntax of os.urandom() Method
  2. Example 1: Use the os.urandom() Method in Python
  3. Example 2: Display the Result as a String in the os.urandom() Method
  4. Example 3: Difference Between random() and the os.urandom() Method
Python os.urandom() Method

Python os.urandom() method is an efficient way of generating random bytes of string from an OS-related randomness source. The string is used for cryptographic use.

Syntax of os.urandom() Method

os.urandom(string size)

Parameters

string size - It is the size of the string that needs to be created.

Return

The return type of this method is a string. A string made up of random characters is produced.

Example 1: Use the os.urandom() Method in Python

import os

size_string = 10

print(os.urandom(size_string))

Output:

b'\x99\xe6\x13\x87i\x1d\xa7\xc0\xcb\x92'

A unique string pattern will be generated on each execution of the above code.

Example 2: Display the Result as a String in the os.urandom() Method

import os

from base64 import b64encode

random = os.urandom(10)

print("The random characters are: ", random)

string = b64encode(random).decode("utf-8")

print("Now displaying the random characters as a string literal: ", string)

Output:

The random characters are:  b'\xc7\x85\xba\x92\xdfl\xdf\xdb#\x06'
Now displaying the random characters as a string literal:  x4W6kt9s39sjBg==

This method might raise the NotImplementedError exception on a Unix system because the random bytes are read from a specific library, which might not be available in that system.

Example 3: Difference Between random() and the os.urandom() Method

import time

import os

import random


def random_method(x):

    start_time = time.time()

    random_number = []

    for _ in range(x):

        random_number.append(random.randrange(1, 20, 1))

    end_time = time.time()

    print(end_time - start_time)


def urandom_method(y):

    start_time = time.time()

    random_number = []

    for _ in range(y):

        random_number.append(os.urandom(2))

    end_time = time.time()

    print(end_time - start_time)


random_method(10000)

urandom_method(10000)

Output:

0.007198333740234375
0.011803150177001953

The main difference between the random() and os.urandom() method is that the latter produces cryptographically secure numbers.

The random() method uses a pseudo-random number algorithm; on the other hand, os.urandom() uses OS-related sources for better random number generation.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS