I am trying to make my code executable via terminal with certain arguments passed to it. I could not find any questions or answers dealing with a similar situation. The problem is that the order in which the arguments are processed is also a little ambiguous. I tried giving all the options but then it says the -p option requires integer vales and discards the one provided right after -p. Instead, it is pointing at the hostname provided as the reason for failure.
The python script should execute when I run the following:
./Talktoserver -p <portnumber> [hostname] [message]
In this, if -p and hostname are not provided, the program should take default values. But the message must be provided.
I have tried using argparse and tried topers all arguments and reuse them in the code but the order in which they are then is completely messed up.
The expected result is that the code should execute if the user inputs any of the following:
./Talktoserver -p 22 anysite.com Message
./Talktoserver Message
./Talktoserver -p 22 Message
It should show help text if: The message is missing -p is given but no valid int value is given.
In all other cases, it should substitute default values. (Say, google.com for hostname, port number 22)
parser.add_argument('-p', metavar='N', type=int, nargs='+', default= 27995,
help='Use if you want to specify a custom port number.')
parser.add_argument('hostname', action='store', type = str, default= 'any site.com',
help='Use if you want to provide a custom hostname.')
parser.add_argument('message', dest = '', action='store', type = str, required=True,
help='Please provide a message')
args = parser.parse_args()
print(args.accumulate(args.integers))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creating a socket object.
port = parser['num']
hostname = parser['hostname']
message = parser['message']
equ = 'Hello There\n'# Readying the greeting message to be sent to the server.
s.connect((hostname, port))