[Tutor] script question

Christopher Arndt chris.arndt at web.de
Mon Sep 26 14:56:25 CEST 2005


Chris Hallman schrieb:
> for i in passwordlist:
>     if i == port:
>         os.system("d:\\tnd\\bin\\cawto.exe -cat NetNet " + sys.argv[1] +
> " " + sys.argv[2] + " " + sys.argv[3] + " " + sys.argv[4])

1) The last line can be also expressed as:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(sys.argv[1:5]),))

sys.argv is a list of strings (from which we're only using elements 1-4), which
you can concatenate with the join() method of strings. Then use the '%' string
operator to add it to the command string.

If your command line arguments might contain spaces, you should quote them like
this:

os.system(r"d:\tnd\bin\cawto.exe -cat NetNet %s" % (" ".join(['"%s"' % x for x
in sys.argv[1:5]]),))

You'll find more information about these methods and operators in the standard
library docs section 2.3.

2) I also used a raw string (r'') to avoid having to use double backslashes in
windows paths all the time.

3) Assuming that sys.argv[3] (port) will only match one password in
passwordlist, you can also shorten the for/if construction to:

if port in passwordlist:
    os.system(...)

because you're not actually using any of the information from the ini file in
your command line.

4) As to your question regarding efficiency of the script, unfortunately the
ConfigParser module parses the whole INI file unconditionally. You could look
for other third-party configuration file parsers that might do this more
efficiently, but I can not help you there. Start looking a the Cheese shop
(www.python.org/pypi)

Chris


More information about the Tutor mailing list