Store argparse input to use as variable

Question:

I am using argparse to require input from the user for a hardware id to then be called later on, I cannot work out how to get it so the user types

<command> --id <id>

Please help me see where I’m going wrong! Thanks

parser = argparse.ArgumentParser(description='Return a list of useful information after specifying a hardare/asset ID')
parser.add_argument('--id', type=str, required=True, help ='A hardware/asset id to provide information on')
args = vars(parser.parse_args())
args = parser.parse_args()

def main():
    hardware_id = hardware_id_input
    host = get_host_information(hardware_id)
    print(host["hostname"])
    print(host["hardware_id"])
Asked By: yellowledbetterown

||

Answers:

Ditch the call to vars. You would have your argument stored as args.id after parsing. You would then call your main with the args.id as input.

Edit: added a code sample

def main(hw_id):
    print(hw_id)

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Description.')
    parser.add_argument('--id', type=str, help='The hardware id.', required=True)
    args = parser.parse_args()

    main(args.id)
Answered By: stg77
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.