Click here to Skip to main content
16,020,673 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i'm trying to take an argument from the user to connect to a specific port number

while trying to take the argument
Python
import argparse

args = argparse.ArgumentParser()
args.add_argument("-p", "-port", help="Please enter the port number",action="store_true")
if args.port:
    print("You entered this [" + str(args.port) + "] port number are you sure ??")


i got this error


if args.port:
AttributeError: 'ArgumentParser' object has no attribute 'port'

What I have tried:

Python
import argparse

args = argparse.ArgumentParser()
args.add_argument("-p", "-port", help="Please enter the port number",action="store_true")
if args.port:
    print("You entered this [" + str(args.port) + "] port number are you sure ??")
Posted
Updated 7-Dec-18 23:02pm

1 solution

You need to call parse_args() after adding your arguments, and also a double -- in front of the argument name. Try:
Python
import argparse
args = argparse.ArgumentParser()
args.add_argument("-p", "--port", help="Please enter the port number",action="store_true")
args.parse_args()

Also note that this parser will not accept any argument value, since port is defined as "store_true"
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900