Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6380041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T02:12:58+00:00 2026-05-25T02:12:58+00:00

I’m creating a small Python script to manage different classes of servers (FTP, HTTP,

  • 0

I’m creating a small Python script to manage different classes of servers (FTP, HTTP, SSH, etc.)

On each type of server, we can perform different types of actions (deploy, configure, check, etc.)

I have a base Server class, then a separate class for each type of server that inherits from this:

class Server:
    ...
    def check():
        ...

class HTTPServer(Server):
    def check():
        super(HTTPServer, self).check()
        ...
class FTPServer(Server):
    def check():
        super(FTPServer, self).check()
        ...

A sample command line might be:

my_program deploy http

From the command-line, the two mandatory arguments I need are:

  1. Operation to perform
  2. Type of server to create/manage

Previously, I was using argparse and the store operation, and using a dict to match the command-line option to the actual class and function name. For example:

types_of_servers = {
    'http': 'HTTPServer',
    'ftp': 'FTPServer',
    ...
}

valid_operations = {
    'check': 'check',
    'build': 'build',
    'deploy': 'deploy',
    'configure': 'configure',
    'verify': 'verify',
}

(In my actual code, valid_operations wasn’t quite a naive 1:1 mapping.)

And then using rather horrible code to create the right type of object, and call the right class.

Then I thought I’d use argparse’s subparsers feature to do it instead. So I’ve made each operation (check, build, deploy, etc.) a subparser.

Normally, I could link each sub-command to a particular function, and have it call it. However, I don’t want to just call a generic check() function – I need to create the correct type of object first, and then call the appropriate function within that object.

Is there a good, or pythonic way to do this? Preferably one that doesn’t involve a lot of hardcoding, or badly designed if/else loops?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T02:12:59+00:00Added an answer on May 25, 2026 at 2:12 am

    If you are set on using a subparser for each command I would do something like this. Use argparse’s type support to call a function that lookups the class you want to instantiate and returns it.

    Then call the method on that instance dynamically with getattr()

    import argparse
    
    class Server:
        def check(self):
            return self.__class__.__name__
    
    class FooServer(Server):
        pass
    
    class BarServer(Server):
        pass
    
    
    def get_server(server):
        try:
            klass = globals()[server.capitalize()+'Server']
            if not issubclass(klass, Server):
                raise KeyError
    
            return klass()
        except KeyError:
            raise argparse.ArgumentTypeError("%s is not a valid server." % server)
    
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers(dest='command')
    
        check = subparsers.add_parser('check')
        check.add_argument('server', type=get_server)
    
        args = parser.parse_args()
    
        print getattr(args.server, args.command)()
    

    Output looks something like this:

    $ python ./a.py check foo
    FooServer
    $ python ./a.py check bar
    BarServer
    $ python ./a.py check baz
    usage: a.py check [-h] server
    a.py check: error: argument server: baz is not a valid server.
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
Basically, what I'm trying to create is a page of div tags, each has
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
I am trying to understand how to use SyndicationItem to display feed which is
I have a jquery bug and I've been looking for hours now, I can't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.