stdin or optional fileinput

T

the.theorist

I was writing a small script the other day with the following CLI
prog [options] [file]*

I've used getopt to parse out the possible options, so we'll ignore
that part, and assume for the rest of the discussion that args is a
list of file names (if any provided).

I used this bit of code to detect wether i want stdinput or not.

if len(args)==0:
args = [ sys.stdin ]

Now in my main loop I've written:

for file in args:
for line in open( file ):
#do stuff

The probelm occurs when I pass no arguments and python trys to open(
sys.stdin ).
open() customarily accepts a pathname, and returns a file object.
But this code is so elegant I thought that maybe, if open were passed
file object it could re-open that file in a new mode (if a mode was
provided different from the current mode) or simply return the file
object it was passed.

Anyhow, what do you guys think? There might be something about my idea
that makes this proposed behavior of open() unexpected, and I just
haven't thought of it.
 
S

Steven Bethard

the.theorist said:
I was writing a small script the other day with the following CLI
prog [options] [file]*

I've used getopt to parse out the possible options, so we'll ignore
that part, and assume for the rest of the discussion that args is a
list of file names (if any provided).

I used this bit of code to detect wether i want stdinput or not.

if len(args)==0:
args = [ sys.stdin ]

Now in my main loop I've written:

for file in args:
for line in open( file ):
#do stuff

You should probably write:

if not args: # note that len(args) == 0 is repetitively redundant, over
# and over again, in a reiterative manner
files = [sys.stdin]
else:
files = (open(filename) for filename in args)

....

for fileobj in files: # using the name 'file' is a bad idea since it
# shadows the builtin 'file'
for line in fileobj:
# do stuff


STeVe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top