how to calculate the size of sys.stdin?
Robin Thomas
robin.thomas at starmedia.net
Wed Apr 11 19:15:02 EDT 2001
At 10:33 AM 4/12/01 +1200, Graham Guttocks wrote:
>Greetings,
>
>Is there a way to calculate the size (in bytes) of sys.stdin? I tried
>to use the "stat" module to accomplish this, but os.stat() seems to
>only accept the name of a file. (i.e, the following doesn't work):
sys.stdin is more like a pipe, and not a regular file. You can't ask a pipe
how many bytes it contains before you read from it. Instead, you can
yourself count how many bytes you read from the pipe before there are no
more to read:
import sys
bytes = sys.stdin.read()
size_of_stdin = len(bytes)
Note that sys.stdin.read() reads as many bytes as possible until the "end"
of the pipe. read() will "block", or wait indefinitely, until sys.stdin
says, "no more bytes left, because the process writing to me closed me".
This way, if sys.stdin is actually being produced by another process's
stdout, sys.stdin.read() will block until the other process finishes
writing to it. Try this:
# save as out.py
import sys, time
num = 0
while num < 5:
sys.stdout.write('a')
time.sleep(1)
num = num + 1
# save as in.py
import sys
bytes = sys.stdin.read()
print bytes
Then do this in the shell:
bash$ python out.py | python in.py
And you'll notice that in.py reads 5 bytes from sys.stdin, waiting
patiently for out.py to finish writing and close its end of the pipe.
Also try this:
bash$ python
Hi it's Python
>>> import sys
>>> bytes = sys.stdin.read()
And now Python will block, eating everything you type into the terminal,
until you indicate that you're done writing to the stdin pipe by typing
Ctrl-D. (Ctrl-D is a terminal control telling the terminal to close the
pipe; Ctrl-D present in a regular file does *not* mean end-of-file.)
Then try to read again:
>>> sys.stdin.read()
''
It returns immediately! You didn't even get a chance to type anything,
because sys.stdin thinks, "I'm at the end of the pipe, so there's nothing
more to read".
Then do:
>>> sys.stdin.seek(0)
which says, "rewind to the beginning of the file". Then:
>>> sys.stdin.read()
and Python blocks again, waiting for you to type Ctrl-D to finish. Lots of fun.
--
Robin Thomas
Engineering
StarMedia Network, Inc.
robin.thomas at starmedia.net
More information about the Python-list
mailing list