gpt4 book ai didi

python - Python 中的参数解析(必需与可选)

转载 作者:行者123 更新时间:2023-11-28 22:48:40 25 4
gpt4 key购买 nike

我目前正在编写一个能够接受多个标志的脚本。我想要这样,无论最后一个参数是什么,都应该是“开始|停止|状态”。

#!/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 将在末尾需要一个“停止|开始|状态”。我没有多少运气获得 ARgumentParser() 方面的帮助。如果有人有任何建议,那将非常有帮助。

提前感谢您的宝贵时间。

注意:如果未输入 [stop|start|restart|status],我希望脚本停止,并说明需要 [stop|start|restart|status]。

**更新** **更新** **更新**

在做了更多挖掘之后,为了能够分析/使用命令行选项和参数,我偶然发现了 OptionParser,我将其避免为 docs.python.org表示它是 deprecated .不管怎样,因为这是我能找到的唯一能给我我想要的东西,这里是我所拥有的更新:

#!/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

关于python - Python 中的参数解析(必需与可选),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24833054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com