无法解析 Python 中的命令行参数
Unable to parse Command line argument in Python
我正在尝试创建一个接受命令行参数并根据输入调用相关函数的脚本。
这是我的主要功能的样子:
from lib.updatefeed import gather
#stdlib imports
import argparse
def main():
print "test"
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-ip', type=str, nargs='+', help="Search for a single IP")
parser.add_argument('-list', type=str, nargs='?', help="Search for a list of IP")
parser.add_argument('-update', type=str, nargs='?', help='Update the local storage')
args = parser.parse_args()
if args.ip:
if len(args.ip) > 4:
print "Too many"
sys.exit(1)
parse_ip(args.ip)
if args.list:
parse_ipList(list)
if args.update:
print "updating"
gather()
if __name__ == '__main__':
main()
所有其他参数都工作正常并且正在调用相应的函数。唯一的问题是 "update" 参数。
出于某种原因,传递 -update arg 时 gather()
函数未被调用。我还在函数调用之前添加了一个打印语句,但也没有打印出来。
谁能帮我找出根本原因。
这也是我收集功能的一部分:
def gather(self):
if not os.path.exists('New'):
os.mkdir('New')
print "Starting feed update process"
parser.add_argument('-update', type=str, nargs='?', help='Update the local storage')
将选项 -update
声明为采用单个可选参数 (nargs='?'
);选项的值将是参数(如果提供)或 default
键的值。但是,您没有提供 default
键,默认的 default
是 None
.
所以如果你只提供 command-line 选项 -update
而没有参数,那么 args.update
的值将是 None
,测试:
if args.update:
print "updating"
gather()
会失败,所以什么都不做。
显然,您只关心 command-line 中是否存在 -update
,因此它不应该带任何参数。要处理这种情况,请将选项定义为具有操作 store_true
,并省略 type
和 nargs
参数:
parser.add_argument('-update', action='store_true', help='Update the local storage')
我正在尝试创建一个接受命令行参数并根据输入调用相关函数的脚本。 这是我的主要功能的样子:
from lib.updatefeed import gather
#stdlib imports
import argparse
def main():
print "test"
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-ip', type=str, nargs='+', help="Search for a single IP")
parser.add_argument('-list', type=str, nargs='?', help="Search for a list of IP")
parser.add_argument('-update', type=str, nargs='?', help='Update the local storage')
args = parser.parse_args()
if args.ip:
if len(args.ip) > 4:
print "Too many"
sys.exit(1)
parse_ip(args.ip)
if args.list:
parse_ipList(list)
if args.update:
print "updating"
gather()
if __name__ == '__main__':
main()
所有其他参数都工作正常并且正在调用相应的函数。唯一的问题是 "update" 参数。
出于某种原因,传递 -update arg 时 gather()
函数未被调用。我还在函数调用之前添加了一个打印语句,但也没有打印出来。
谁能帮我找出根本原因。
这也是我收集功能的一部分:
def gather(self):
if not os.path.exists('New'):
os.mkdir('New')
print "Starting feed update process"
parser.add_argument('-update', type=str, nargs='?', help='Update the local storage')
将选项 -update
声明为采用单个可选参数 (nargs='?'
);选项的值将是参数(如果提供)或 default
键的值。但是,您没有提供 default
键,默认的 default
是 None
.
所以如果你只提供 command-line 选项 -update
而没有参数,那么 args.update
的值将是 None
,测试:
if args.update:
print "updating"
gather()
会失败,所以什么都不做。
显然,您只关心 command-line 中是否存在 -update
,因此它不应该带任何参数。要处理这种情况,请将选项定义为具有操作 store_true
,并省略 type
和 nargs
参数:
parser.add_argument('-update', action='store_true', help='Update the local storage')