I need help with this issue, I want to take an argument from user input using argparse
save it to a variable and print out the result
Example: Message to send:
-t Greeting -m hello guys how are you
prints out:
greeting hello guys how are you
this is my code:
import argparse, shlex
parser = argparse.ArgumentParser()
parser.add_argument('-t', action='store', dest='title')
parser.add_argument('-m', action='store', dest='msg')
command = raw_input('message to send')
args = parser.parse_args(shlex.split(command))
title = args.title
msg = args.msg
print title, msg
when you enter, -t hi -m hello
, it works fine but when you enter more then one word, it doesn't work. Why?
Usually, when you declare a command line switch via the add_argument method, python considers that only the next world/value should be stored inside the resulting variable. That is why the following works fine:
-t hello -m world
While the following:
-t greetings -m hello world
returns something like:
greetings hello
Using nargs, you can tell python how many values should be stored in the final variable. For example, in your code if you declare your command line switches as:
parser.add_argument('-t', action='store', dest='title', nargs='*', type=str, required=True)
parser.add_argument('-m', action='store', dest='msg', nargs='*', type=str, required=True)
Python knows that all values following the -t switch should be stored in a list called title. The same goes for the -m switch and the msg variable. Here I also added the type and required arguments to indicate what type of value is expected and that both switches have to be present in the command line.
Fixing your entire script so far:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', action='store', dest='title', nargs='*', type=str, required=True)
parser.add_argument('-m', action='store', dest='msg', nargs='*', type=str, required=True)
args = parser.parse_args()
print(" ".join(args.title), " ".join(args.msg))
All you have to do is call your script as follow:
python3 your_script.py -t greetings -m hello world
This should print:
greetings hello world
as a result.