user12459034
user12459034

Reputation:

Get user input with arguments in Python

TL;DR I need to get a user input that contains an argument in order to do something, I need my own script that gets user input, and acts like it's its own interpreter.

My goal is to make my own CLI with my own commands. What I need now is to get user input within a python script. The grammar for my CLI is below: (The thing I don't know how to do)

COMMAND + ARGUMENT1 + ARGUMENT2 + ARGUMENT3

Example of what I want to do:

say "hi this is a test"
hi this is a test

I have a plan for how I can make the commands with arguments, I make a folder named 'bin' and I put python scripts in them. Inside the python scripts are functions. Depending on the command type, either I call the functions do do something, or it prints a output.

But for now, I need to know HOW to get user input with ARGUMENTS

Upvotes: 0

Views: 3676

Answers (2)

user12459034
user12459034

Reputation:

I realize I already have a question that is answered.

You can find it here: How do you have an input statement with multiple arguments that are stored into a variable?

Here is the correct code:

def command_split(text:str) -> (str,str):
    """Split a string in a command and any optional arugments"""
    text = text.strip() # basic sanitize input
    space = text.find(' ')
    if space > 0:
        return text[:space],text[space+1:]
    return text,None

x = input(":>")
command,args = command_split(x)
# print (f'command: "{command:}", args: "{args}"')

if command == 'echo':
    if args == None:
        raise SyntaxError
    print (args)

A more simple way:

x = input(":>")
if x.split(" ")[0] == 'echo':
    echoreturn = ' '.join(x.split(" ")[1:])
    print(echoreturn)

My version to @rgov 's post: (Thank you!)

import argparse
import shlex

def do_say(args):
    print(args.what)

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
say_command = subparsers.add_parser('say')
say_command.add_argument('what')
say_command.set_defaults(func=do_say)

while True:
    try:

        command = input(":>")

        args = parser.parse_args(shlex.split(command))
        args.func(args)
    except SyntaxError:
        print("Syntax Error")
    except ValueError:
        print("Value Error")
    except:
        print("")

Upvotes: 1

rgov
rgov

Reputation: 4329

The built-in argparse module as @ToTheMax said can create complex command line interfaces.

By default argparse.ArgumentParser.parse_args() will read the command line arguments to your utility from sys.argv, but if you pass in an array, it will use it instead.

You can lex (split into an array of "words") a string just like the shell is using shlex.split() which is also built in. If you use quotation marks like in your example, the words between them won't be split apart, just as in the shell.

Here's a complete example. Refer to the documentation, because this is a bit of an advance usage of argparse. There is a section that talks about "subcommands" which is what this example is based on.

import argparse
import shlex

def do_say(args):
    print(args.what)

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
say_command = subparsers.add_parser('say')
say_command.add_argument('what')
say_command.set_defaults(func=do_say)

command = 'say "hi this is a test"'

args = parser.parse_args(shlex.split(command))
args.func(args)

The cmd module is another built-in way to make a command prompt, but it doesn't do the parsing for you, so you'd maybe combine it with argparse and shlex.

Upvotes: 1

Related Questions