Input from a file as a command line argument

Thomas Guettler pan-newsreader at thomas-guettler.de
Sat Apr 5 09:31:02 EST 2003


On Sat, 05 Apr 2003 15:36:26 +0200, Teemu Luojola wrote:

> I have read through Python documentation and tried several searches, but
> I can't find a simple answer to this question.
> 
> If I make an executable script in linux environment, how can I pass
> input to that script from a file on command line? Like the following:
> 
> $ script.py input.txt

do it like this:

import sys
input_txt=sys.argv[1]

> $ script.py < input.txt

import sys
lines=sys.stdin.readlines() # or .read() to get it in one string
for line in lines:
    .....

since the above code reads everything from stdin first and the enters
the loop, you might prefere an interation:

import sys
for line in sys.stdin.xreadlines():
    print line
    
 thomas

-- 
Thomas Guettler <guettli at thomas-guettler.de>
http://www.thomas-guettler.de




More information about the Python-list mailing list