Python中的参数解析(必需与可选)
我目前正在编写一个脚本,可以使用多个标志。我希望这样,无论最后一个参数是什么,都应该是“开始|停止|状态”Python中的参数解析(必需与可选),python,parsing,optparse,Python,Parsing,Optparse,我目前正在编写一个脚本,可以使用多个标志。我希望这样,无论最后一个参数是什么,都应该是“开始|停止|状态” #!/usr/bin/env python from argparse import ArgumentParser def argument_analysis(): """ This will analyze arguments, and return the region as a string, the filter as a dictionary, and the co
#!/usr/bin/env python
from argparse import ArgumentParser
def argument_analysis():
"""
This will analyze arguments, and return the region as a string, the filter as a dictionary, and the command as a string.
:return: region,filters,command
"""
parser_options = ArgumentParser()
parser_options.add_argument("-r", "--region", dest='region',
help="Filter by region.")
parser_options.add_argument("-n", "--name", dest='name',
help="Filter by hostname.")
parser_options.add_argument("-P", "--project", dest='project',
help="Filter by Project tag.")
parser_options.add_argument("-U", "--usage", dest='usage',
help="Filter by Usage tag.")
parser_options.add_argument("-i", "--instance_id", dest='instance_id',
help="Filter by instance_id.")
parser_options.add_argument("-t", "--type", dest='type',
help="Filter by instance_size.")
parser_options.add_argument("-p", "--ip", dest='internal_ip',
help="Filter by internal_ip")
parser_options.add_argument("-c", "--command", dest='command',
help="stop/start, or check the status of instances.")
parser_options.add_argument("-a", "--all", dest='all', default=False, action='store_true',
help="No filter, display status of all servers.")
arguments = vars(parser_options.parse_args())
return arguments
if __name__ == '__main__':
print argument_analysis()
我希望./argument_analysis_script.py在结尾处需要一个“stop | start | status”。我在ARgumentParser()方面没有得到多少帮助。如果有人有任何建议,那将非常有帮助
提前感谢您抽出时间
注意:如果未输入[stop | start | restart | status],我希望脚本停止,并解释需要[stop | start | restart | status] **更新****更新****更新** 在做了更多的挖掘之后,为了能够分析/使用命令行选项和参数,我偶然发现了OptionParser,我避免使用它。无论如何,因为这是我能找到的唯一能给我想要的东西,下面是我得到的更新:
#!/usr/bin/env python
from optparse import OptionParser
def argument_analysis():
"""
This will analyze arguments, and return the region as a string, the filter as a dictionary, and the command as a string.
:return: region,filters,command
"""
parser = OptionParser()
parser.add_option("-r", "--region", dest='region',
help="Filter by region.")
parser.add_option("-n", "--name", dest='name',
help="Filter by hostname.")
parser.add_option("-P", "--project", dest='project',
help="Filter by Project tag.")
parser.add_option("-U", "--usage", dest='usage',
help="Filter by Usage tag.")
parser.add_option("-i", "--instance_id", dest='instance_id',
help="Filter by instance_id.")
parser.add_option("-t", "--type", dest='type',
help="Filter by instance_size.")
parser.add_option("-p", "--ip", dest='internal_ip',
help="Filter by internal_ip")
parser.add_option("-c", "--command", dest='command',
help="stop/start, or check the status of instances.")
parser.add_option("-a", "--all", dest='all', default=False, action='store_true',
help="No filter, display status of all servers.")
(options, args) = parser.parse_args() # Grab Options specifed from above, as well as actual Arguments.
options = vars(options) # Convert 'options' into dictionary: key=dest_name, value=dest_value
# Getting variables for dictionary below.
region_filter = options['region']
name_filter = options['name']
project_filter = options['project']
usage_filter = options['usage']
instance_filter = options['instance_id']
type_filter = options['type']
ip_filter = options['internal_ip']
all_filter = options['all']
region = region_filter if region_filter else 'us-east-1' # Return 'us-east-1' region is not specified.
filters = {'tag:Name': name_filter, 'tag:Project': project_filter, 'tag:Usage': usage_filter,
'instance-id': instance_filter, 'instance_type': type_filter, 'private-ip-address': ip_filter,
'all': all_filter}
command = 'No commands.' if not args else args #Return "No commands" if no command is specified.
return region, filters, command
if __name__ == '__main__':
opts_and_args = argument_analysis()
print "Region: " + str(opts_and_args[0])
print "Filters: " + str(opts_and_args[1])
print "Command: " + str(opts_and_args[2])
如您所见,您可以基于返回的对象或在定义中应用任何您想要的逻辑。感谢大家在这方面的帮助。也许您可以使用argparse来完成这项工作,但另一个选项是使用
sys
模块
import sys
print sys.argv # prints command line arguments
sys.argv
在一个列表中有命令行参数,因此您可以检查最后一个:
if sys.argv[-1] != 'start':
print "Error, expected <something>"
// quit
如果系统argv[-1]!='开始':
打印“错误,应为”
//退出
也许您可以使用argparse执行此操作,但另一个选项是使用sys
模块
import sys
print sys.argv # prints command line arguments
sys.argv
在一个列表中有命令行参数,因此您可以检查最后一个:
if sys.argv[-1] != 'start':
print "Error, expected <something>"
// quit
如果系统argv[-1]!='开始':
打印“错误,应为”
//退出
部分与Ben的答案相同,但扩展了regex
,以避免为每种情况声明if语句,例如start
,stop
import sys
import re
a = sys.argv[-1]
if not re.search(r"^(start|stop|restart|status)$", a):
raise Exception("start, stop, restart or status should be passed to this script instead of: \""+a+"\"")
部分与Ben的答案相同,但扩展了
regex
,以避免为每种情况声明if语句,例如start
,stop
import sys
import re
a = sys.argv[-1]
if not re.search(r"^(start|stop|restart|status)$", a):
raise Exception("start, stop, restart or status should be passed to this script instead of: \""+a+"\"")
我建议看一看。它不在标准库中,但它肯定更强大、更直观。例如,在您的情况下,您可以这样做:
docstring='''My Program.
Usage: my_prog [options] (flag1|flag2|flag3) (start|stop|restart|status)
Options:
-a stuff about this
-b more stuff
-c yet more stuff
-d finally stuff'''
from docopt import docopt
parsed = docopt(docstring)
我建议看一看。它不在标准库中,但它肯定更强大、更直观。例如,在您的情况下,您可以这样做:
docstring='''My Program.
Usage: my_prog [options] (flag1|flag2|flag3) (start|stop|restart|status)
Options:
-a stuff about this
-b more stuff
-c yet more stuff
-d finally stuff'''
from docopt import docopt
parsed = docopt(docstring)
您能否指出此脚本是否需要参数
start
、stop
或restart,如果不是这样,脚本运行失败,运行此脚本需要消息start、stop或restart
?如果未输入[stop | start | restart | status],我希望脚本停止,并解释需要[stop | start | restart | status]。你的意思是像/argument(参数)analysis(分析)script.py[-whatever]start
?你能指出这个脚本是否需要参数start
,stop
或restart吗?如果不是这样的话,脚本运行失败并显示一条消息start,运行此脚本需要停止或重新启动
?如果未输入[stop | start | restart | status],我希望脚本停止,并解释需要[stop | start | restart | status]。您的意思是像/argument | analysis | script py[-无论什么]start
,这肯定很有帮助。它可能最终成为最终答案。我真的希望ArgumentParser模块足够直观,可以有这样的功能:\是的,据我所知,argparse不存在顺序,但是在列表中包含参数也是非常有用的。谢谢你的帮助。我可能会使用argv,当我把一些可行的东西放在一起时,我会更新这篇文章。这绝对是有帮助的。它可能最终成为最终答案。我真的希望ArgumentParser模块足够直观,可以有这样的功能:\是的,据我所知,argparse不存在顺序,但是在列表中包含参数也是非常有用的。谢谢你的帮助。我可能会使用argv,当我把一些可行的东西放在一起时,我会更新这篇文章。