python, argparse get argument from input- raw_input

≡放荡痞女 提交于 2019-12-24 22:09:57

问题


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?


回答1:


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.




回答2:


You have 2 options here. Either quote the argument with spaces like so:

-t Hi -m "Hello word1 word2"

or

use davinellulinvega's answer. To get back the entire string with nargs='*', you'd have to:

parser.add_argument('-t', action='store', dest='title', nargs='*')
parser.add_argument('-m', action='store', dest='msg', nargs='*')

....

title = ' '.join(args.title)
msg = ' '.join(args.msg)


来源:https://stackoverflow.com/questions/48431642/python-argparse-get-argument-from-input-raw-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!