[Tutor] Argparse functions with N parameters

Peter Otten __peter__ at web.de
Fri Jun 7 09:58:39 CEST 2013


Danilo Chilene wrote:

> Hello,
> 
> It's ok to revive a old thread? :)
> 
> I finished my script (https://github.com/bicofino/Pyora) using argparse.
> 
> But I have a question, today I'm connecting to the database outside the
> class Check, what's the best way to connect passing the arguments using
> argparse and run a function.
> 
> Today it work like this:
> 
> # Check Oracle version
> 0: python pyora.py version
> Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
> 
> 
> I was thinking that is better pass the database
> arguments(username,password,address,database)
> 
> it would run like this:
> python pyora.py username,password,address,database version
> 
> Any thoughts?

Untested:

> class Main(Checks):
>     def __init__(self):
>         parser = argparse.ArgumentParser()

          parser.add_argument("username")
          parser.add_argument("--password")
          parser.add_argument("address")
          ...
>         subparsers = parser.add_subparsers()
> 
>         for name in dir(self):
>             if not name.startswith("_"):
>                 p = subparsers.add_parser(name)
>                 method = getattr(self, name)
>                 argnames = inspect.getargspec(method).args[1:]
>                 for argname in argnames:
>                     p.add_argument(argname)
>                 p.set_defaults(func=method, argnames=argnames)
>         self.args = parser.parse_args()

      def db_connect(self):
           a = self.args
           username = a.username
           password = a.password
           if password is None:
               password = getpass.getpass()
           ...
           self.db = cx_oracle.connect(...)
           self.cur = self.db.cursor()

      def db_close(self):
          self.db.close()

>     def __call__(self):
>         a = self.args
>         callargs = [getattr(a, name) for name in a.argnames]
          self.db_connect()
          try:
              return self.args.func(*callargs)
          finally:
              self.db_close()

Of course you have to modify your methods to use self.cur instead of a 
global cur.




More information about the Tutor mailing list