[Tutor] Pass variable on command line

Andreas Kostyrka andreas at kostyrka.org
Thu Jul 26 21:47:52 CEST 2007


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Alternatively, I prefer something nicer:

import optparse
p = optparse.OptionParser(usage="%prog [options]")
p.add_option("--list1", action="store_const", const=["blue", "red",
"green"], dest="worklist", help="use the first setting")
p.add_option("--list2", action="store_const", const=["red", "yellow",
"orange"], dest="worklist", help="use the second setting")

opt, args = p.parse_args()
if opt.worklist is None or len(args) != 0:
    p.print_help()
    raise SystemExit(2)

This looks longer, but gives you a nice commandline parse that does not
bomb out if you do not provide any argument, that is easy to expand, etc.

[caveat: the code above is typed into my mailer, so untested, and from
memory :) ]

Andreas


Terry Carroll wrote:
> On Thu, 26 Jul 2007, jason wrote:
> 
>> Hello,
>>
>> I have a situation where I have 2 lists
>>
>> List1 = ['blue', 'red', green']
>> List2 = ['red', 'yellow', 'orange']
>>
>> And I would like to pass the list name on the command line like so
>>
>> ./test.py List1
>>
>> I know I can get the argument using sys.argv[1]
>>
>> But how can I then use the values in that list inside my program?
> 
> If you must do this, make a dictionary of the lists:
> 
>  d = {"List1": List1, "List2": List2}
> 
> and index into it from your argument:
> 
>  l = d[sys.argv[1]]
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGqPpoHJdudm4KnO0RAu7AAJwN6Zn4j7XcYQJvLAcEfA6G9l9IngCg4wBt
QqB35uZDGZrSoqvJ+TT/Gww=
=yOcf
-----END PGP SIGNATURE-----


More information about the Tutor mailing list