Home > Software design >  python how to easly check a command from specs
python how to easly check a command from specs

Time:04-25

I normally check input commands using statements, but sometimes I want to check commands from a pattern of commands like this:

command = input()
check_command(command)

Where in put can be the following:

CREATE USER <var1 -> int> <var2 -> string>

CREATE ADMIN <var1 -> int> <var2 -> string> <var3 -> boolean>

CREATE <var1 -> string> <var2 -> string>

etc... 100x

Is there a lazy way of doing this?

CodePudding user response:

You can use regular expressions and groups (defined by "()") for each line in the input.

First, you can split the input by doing

lines = input().split("\n")

and then match a certain pattern for every line

Your code for matching could look like this:


pattern = r"(?P<command>[A-Z ] ) <(?P<varname>[a-z0-9_] )->((?P<vartype>[a-z] ))>"...
for line in lines:
    b = re.match(pattern,line)

for the line CREATE USER <var1 -> int> it would match the group command to be "CREATE USER", the group varname to be "var1" and the group "vartype" to be int. You can access the values of these groups via b.group(groupname), for example b.group("command") would give you "CREATE USER"

CodePudding user response:

It seems that you want to have a CLI in your program.

Perhaps using the built-in argparse module may be helpful.

  • Related