[Tutor] Command line args

Andreas Kostyrka andreas at kostyrka.org
Sat Apr 7 20:49:26 CEST 2007


* Teresa Stanton <tms43 at clearwire.net> [070407 18:52]:
>    If one argument to a script is provided I am to take the input from it.  I
>    figure that is presented like this:
> 
>    filename = sys.argv[1]
>    data = open(filename).read()
> 
>    But, if none are provided, input should come from standard input.  How do
>    I write that code?

if len(sys.argv) > 1:
     fp = file(sys.argv[1])
else:
     fp = sys.stdin
data = fp.read()
if fp is not sys.stdin:
     fp.close()

Andreas


More information about the Tutor mailing list