Python | os.getrandom() method

OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.

os.getrandom() method is used to generate a string of size random bytes suitable for cryptographic use or we can say this method generates a string containing random characters. It can also be used to seed user-space random number generators. It can return less bytes than requested.

Syntax: os.getrandom(size, flag)



Parameter:
size: It is the size of string random bytes
flag: It is a bit mask that can contain zero or more flags ORed together. Flags are os.GRND_RANDOM and GRND_NONBLOCK.

Return Value: This method returns a string which represents random bytes suitable for cryptographic use.

Flags –

os.GRND_NONBLOCK: If this flag is set then getrandom() does not block but instead immediately raises BlockingIOError if no random bytes are available to read.

os.GRND_RANDOM: If this bit is set then random bytes are drawn from the /dev/random pool.

Example #1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to explain os.getrandom() method 
          
# importing os module 
import os 
      
# Declaring size
size = 5
  
# Using os.getrandom() method
# Using os.GRND_NONBLOCK flag
result = os.getrandom(size, os.GRND_NONBLOCK) 
      
# Print the random bytes string
# Output will be different everytime
print(result) 

chevron_right


Output:

b'5\n\xe0\x98\x15'

Example #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to explain os.getrandom() method 
          
# importing os module 
import os 
      
# Declaring size
size = 5
  
# Using os.getrandom() method
# Using os.GRND_RANDOM flag
result = os.getrandom(size, os.GRND_RANDOM) 
      
# Print the random bytes string
# Output will be different everytime
print(result) 

chevron_right


Output:

b'\xce\xc8\xf3\x95%'


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.