954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read from /dev/zero

I'm curious why this bit of code doesn't work. When run it returns a blank line. Note: this is making use of a linux device file so it should not be expected to run properly on Windows.

#!/usr/bin/env python
import os

infile = os.open("/dev/zero", os.O_RDONLY)
charout = os.read(infile,1)
os.close(infile)
print charout


I'm pretty new to Python so I might be way off base. I appreciate any suggestions.

mn_kthompson
Junior Poster
148 posts since Nov 2007
Reputation Points: 16
Solved Threads: 35
 

OK, I have been able to verify that something is being read from my device file, but nothing is printable. I have modified the code to read as follows

#!/usr/bin/env python
import os

charout = "XXX"
print len(charout)
infile = os.open("/dev/zero", os.O_RDONLY)
charout = os.read(infile,51)
os.close(infile)
print charout
print len(charout)


And here is the output: kevin@MSU1375020:~$ python read.py
3

51

So you can see that the charout file is getting 51 bytes of data, but it still wont print anything but a blank line. Does this give anyone any clues as to why I'm not getting a bunch of zeros on my screen?

mn_kthompson
Junior Poster
148 posts since Nov 2007
Reputation Points: 16
Solved Threads: 35
 

They are not printable characters (probably) and so who knows where they come from. To test this, try printing the decimal value of each character. It might just be a bunch of decimal zeroes (which is zero, the printable zero is decimal 48), or EOFs, or garbage created by some sort of "noise".

for each_char in charout:
     print ord(each_char),
print
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

Hey that worked for me, I got the zeros I was expecting. I guess when you read characters from a device file you might not be getting printable characters. I thought that python would have casted the characters into strings
Thanks!

mn_kthompson
Junior Poster
148 posts since Nov 2007
Reputation Points: 16
Solved Threads: 35
 

Zero evidently means that nothing was read and it will probably continue trying to read until you tell it to stop, which is why there are multiple zeros.

woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You