0

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))

Ron Halden
  • 35
  • 5

1 Answers1

0

welcome to Stack Overflow :)

The following should be sufficient for your needs.

import argparse

parser = argparse.ArgumentParser(description="")

parser.add_argument(
    "-p",
    metavar="N",
    type=int,
    default=27995,
    help="Use if you want to specify a custom port number.",
)
parser.add_argument(
    "hostname",
    action="store",
    type=str,
    nargs="?",
    default="any site.com",
    help="Use if you want to provide a custom hostname.",
)
parser.add_argument(
    "message",
    action="store",
    type=str,
    help="Please provide a message",
)
args = parser.parse_args()
port = args.p
hostname = args.hostname
message = args.message
print(f"port: {port}, hostname: {hostname}, message: {message}")

The help text now looks like:

usage: Talktoserver [-h] [-p N] [hostname] message

positional arguments:
  hostname    Use if you want to provide a custom hostname.
  message     Please provide a message

optional arguments:
  -h, --help  show this help message and exit
  -p N        Use if you want to specify a custom port number.

If you haven't already, checkout the official argsparse docs for more detailed information where all the options are covered.

John Keyes
  • 5,479
  • 1
  • 29
  • 48
  • I tried this solution. But I'm getting an error File "./x", line 12, in parser = argparse.ArgumentParser(description = "Random text") NameError: name 'argparse' is not defined – Ron Halden Jan 30 '19 at 05:32
  • @RonHalden Have you imported argparse in your file? You could copy and paste my code above and if that works you can then start tweaking it. – John Keyes Jan 30 '19 at 05:55