[Tutor] Command line args
Kirk Bailey
deliberatus at verizon.net
Tue Apr 10 04:28:59 CEST 2007
ok, try this:
Try:
filename=sys.arv[1]
except Exception, e:
if filename='':
filename='foo' # define a default value
else:
if foo: # detect one likely error
foobarcode
else:
if bar: # detect another one
morefoobarcode
else: # final catchall for things you
# did not anticipate
Print 'how the heck did you accomplish this?!? I QUIT~!
sys.exit(13)
i has something vauely like this in the wiki on the slab right now,
except it was addressing the query string. other than that, same problem.
another idea is simply detect that there IS a argument;
if sys.argv[1];
filename=sys.argv[1]
if condition:
do something
else:
do this instead
else:
filename="foo"
which avoids try altogether. Somehow I kinda like this way more.
Luke Paireepinart wrote:
> Kirk Bailey wrote:
>> Teresa Stanton wrote:
>>
>>> 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]
>>>
>> Try:
>>
> the 'try' keyword is not capitalized in Python.
>> filename=sys.arg[1]
>> except exception, E:
>>
> you should only catch the exception you expect, so you don't
> accidentally silence an unrelated error.
> so
> except IndexError:
> because you're trying to index into a list that might not have 2 or more
> elements.
>> filename='FooBar'
>>
> You said you wanted the input from standard input, so just put a
> raw_input here.
>
> so the new code is:
>
> try: filename = sys.argv[1]
> except IndexError: filename = raw_input("Prompt: ")
>
> HTH,
> -Luke
>
>
--
Salute!
-Kirk Bailey
Think
+-----+
| BOX |
+-----+
knihT
Fnord.
More information about the Tutor
mailing list