satoru
satoru

Reputation: 33225

How to read /dev/random in python

I read in a book that /dev/random is like an infinite file, but when I set up the following codes to see what the content look like, it prints nothing.

with open("/dev/random") as f:
    for i in xrange(10):
        print f.readline()

BTW, when I tried this with /dev/urandom, it worked.

Upvotes: 9

Views: 10623

Answers (3)

Raymond Hettinger
Raymond Hettinger

Reputation: 226486

FWIW, the preferred way of accessing this stream (or something like it) in a semi-portable way is os.urandom()

Upvotes: 19

tripleee
tripleee

Reputation: 189618

It is outputting random bytes, not random lines. You see nothing until you get a newline, which will only happen every 256 bytes on average. The reason /dev/urandom appears to work is simply that it operates faster. Wait longer, read less, or use /dev/urandom.

Upvotes: 9

Michael Lorton
Michael Lorton

Reputation: 44406

with open("/dev/random", 'rb') as f:
    print repr(f.read(10))

Upvotes: 9

Related Questions