stdin or optional fileinput

Fredrik Lundh fredrik at pythonware.com
Wed Mar 15 19:23:34 CET 2006


"the.theorist" wrote:

> 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.

so use your own open function:

    def myopen(file):
        if isinstance(file, basestring):
            return open(file)
        return file

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


or perhaps

    def myopen(file):
        if hasattr(file, "read"):
            return file
        return open(file)

    ...

or perhaps

    if not args:
        args = [ "-" ]

    def myopen(file):
        if file == "-":
            return sys.stdin
        return open(file)

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

(the "-" = stdin convention is quite common)

</F>






More information about the Python-list mailing list