Search code examples
pythonargparse

How can I pass an IP address used in a function as command line argument to argument parser?


I have this function that is pinging a server to get its response. I want to to able to give the IP address used in the function to argument parser as a command line argument instead of hardcoding it or taking it as user input. Currently the function looks like:

def get_sipresponse():
        var = input("Enter Opensips IP: ")
        p = sys.path.append("/home/asad.javed/")
        response = sip.ping(var)
        response.get('Status')
        print(response)
        return p, response

My main function where I am using argument parser looks like:

def main():
        parser = ap.ArgumentParser()
        parser.add_argument('-s', '--start', help='start script', action='store_true')
        parser.add_argument('--getOSresponse', help='Opensips response', action='store_true')

        args = parser.parse_args()

        elif args.start
                for k,v in reversed_dictionary.items():
                        print(v, "=", k);time.sleep(5);
                        proc = subprocess.call([k], shell=True);time.sleep(5);
                        if proc != 0:
                                if proc < 0:
                                        print("Killed by signal!", -proc)
                                else:
                                        print("\nReturn code: \n", proc)
                        else:
                                print("\nSuccess\n");get_sipresponse()

        elif args.getOSresponse:
                get_sipresponse()

Solution

  • In your main, under the setup for other arguments in the arg parser, add this line:

    parser.add_argument('--ip')
    

    Then change get_sipresponse() to this:

    def get_sipresponse(ip):
            p = sys.path.append("/home/asad.javed/")
            response = sip.ping(ip)
            response.get('Status')
            print(response)
            return p, response
    

    Lastly from main, you can call get_sipresponse like this:

    get_sipresponse(args.ip)