coryn
coryn

Reputation: 35

python raw_input "flags"

I'm building a python script that uses raw_input to communicate with the user in the console. Now, I'm just wondering if there is an easy way to use argument flags (similar to other console/cmd scripts) e.g.:

The command "foo" that the user inputs could be followed by a flag such as: "foo -a" and my script can take action accordingly. From my understanding Python has an argparser module, but that is for when the script is run, isn't it?

I guess it can be done manually, by splitting the input at whitespace and then switching the flag, but is there an elegant way?

Thanks in advance!

Upvotes: 0

Views: 357

Answers (2)

pandita
pandita

Reputation: 4989

a=raw_input()

...

b=a.split()
if b[1]=="-a":
    # your code
elif b[1]=="-b":
    #your code
else:
    print("Don't know the argument")

Other than that I think argparse would be the elegant way.

Upvotes: 1

user2725093
user2725093

Reputation: 221

If I can understand you correctly you want to parse arguments coming from "raw_input". Am I correct? If yes in this case you can also use ArgumentParser for solving your problem:

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('-a', help='execution -a option', action='store_true')
>>> args = parser.parse_args(raw_input().split())
-a # Here I entered `-a`
>>> args.a
True

Upvotes: 1

Related Questions