File name from file descriptor?
Chris Gonnerman
chris.gonnerman at newcenturycomputers.net
Tue Jun 26 08:59:44 EDT 2001
----- Original Message -----
From: <piet at cs.uu.nl>
> >>>>> Carsten Gaebler <clpy at snakefarm.org> (CG) writes:
>
> CG> The problem is this: I have a script that is called like
>
> CG> ./myscript.py < somefile
>
> CG> where somefile is a text file which may or may not be gzipped. To
> CG> determine whether or not the data is gzipped I read in one byte via
the
> CG> gzip module. If that raises an exception I know the data is not
gzipped.
> CG> But I'd miss the first byte if it is gzipped. Yes, I could store this
byte
> CG> somewhere and then pass it around somehow, but ... you know? :-) So
I'd
> CG> like to open a second 'instance' of the file for reading but I only
have
> CG> sys.stdin's file descriptor.
>
> If you are sure that stdin will be a real file you can use:
>
> sys.stdin.seek(0,0)
Somewhere around here <rummage, rummage> I have an old C program I wrote
that does something like this (translated):
fp = sys.stdin
try:
fp.seek(0)
except IOError:
tmp = open("tempfile", "w+b")
tmp.write(fp.read())
tmp.seek(0)
fp.close()
fp = tmp
but then you have to remember to clean up the tempfile afterwards. If you
are on a Unixoid OS you can add:
os.unlink("tempfile")
right after the open() call, and the file will be "garbage collected" by
the OS after the interpreter exits. Don't try that on any OS from Redmond!
More information about the Python-list
mailing list