title: Argparse Subparsers, and linking to Classes
body: <p>We have a simple Python program to manage various types of in-house servers, using argparse:</p>
  
  <pre><code>manage_servers.py &lt;operation&gt; &lt;type_of_server&gt; 
  </code></pre>
  
  <p>Operations are things like check, build, deploy, configure, verify etc.</p>
  
  <p>Types of server are just different types of inhouse servers we use.</p>
  
  <p>We have a generic server class, then specific types that inherit from that:</p>
  
  <pre><code>class Server
      def configure_logging(self, loggin_file):
          ...
      def check(self):
          ...
      def deploy(self):
          ...
      def configure(self):
          ...
      def __init__(self, hostname):
          self.hostname = hostname
          logging = self.configure_logging(LOG_FILENAME)
  class SpamServer(Server):
      def check(self):
          ...
  class HamServer(Server):
      def deploy(self):
          ...
  </code></pre>
  
  <p>My question is how to link that all up to argparse?</p>
  
  <p>Originally, I was using argparse subparses for the operations (check, build, deploy) and another argument for the type.</p>
  
  <pre><code>subparsers = parser.add_subparsers(help='The operation that you want to run on the server.')
  parser_check = subparsers.add_parser('check', help='Check that the server has been setup correctly.')
  parser_build = subparsers.add_parser('build', help='Download and build a copy of the execution stack.')
  parser_build.add_argument('-r', '--revision', help='SVN revision to build from.')
  ...
  parser.add_argument('type_of_server', action='store', choices=types_of_servers,
                      help='The type of server you wish to create.')
  </code></pre>
  
  <p>Normally, you'd link each subparse to a method - and then pass in the type_of_server as an argument. However, that's slightly backwards due to the classes- I need to create an instance of the appropriate Server class, then call the operation method inside of that.</p>
  
  <p>Any ideas of how I could achieve the above? Perhaps a different design pattern for Servers? Or a way to still use argparse as is?</p>
  
  <p>Cheers,
  Victor</p>