使用 argparser 运行 python 脚本
尝试使用 argparser 运行我的脚本,除非正确的参数到位,否则程序不会运行,但它似乎不起作用;
AttributeError: 'Namespace' object has no attribute 'func'
import sys
import argparse
from develop import Autogit as gt
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# Create argument command
parser_update = subparsers.add_parser('--sync', help='Sync local and remote repos')
parser_update.set_defaults(func=gt.run)
# Adding arguments
parser.add_argument('--sync', type=str, required=True)
if len(sys.argv) <= 1:
sys.argv.append('--help')
options = parser.parse_args()
options.func() # <--- Causes the error
if __name__ == '__main__':
main()
另外,当给出 --sync arg 时,它会要求另一个参数,然后当我再添加一个参数时。 SYNC,则返回属性错误。
编辑
尝试使程序运行develop.Autogit.run
工作..
还必须在我调用的运行函数中添加args作为参数。
Trying to run my script using argparser, where the program does not run, unless correct argument is in place, however it does not seem to work;
AttributeError: 'Namespace' object has no attribute 'func'
import sys
import argparse
from develop import Autogit as gt
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# Create argument command
parser_update = subparsers.add_parser('--sync', help='Sync local and remote repos')
parser_update.set_defaults(func=gt.run)
# Adding arguments
parser.add_argument('--sync', type=str, required=True)
if len(sys.argv) <= 1:
sys.argv.append('--help')
options = parser.parse_args()
options.func() # <--- Causes the error
if __name__ == '__main__':
main()
Also when the --sync arg is given it ask for another, then when I add one more argument. SYNC, then it returns attribute error.
Edit
Trying to make the program run the develop.Autogit.run
Working..
Had to also add args as argument in the run funciton i am calling.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您想要完成的是设置默认值,通常这是通过
ArgumentParser.set_defaults()
。您需要使用未初始化的函数来执行此操作。请参阅此示例:顺便说一句,当您在多个位置定义相同的参数 (
--sync
) 时,您的代码片段将会遇到更多问题。使用子解析器
时,习惯上使这些位置化(无前导--
),以便它们充当子命令。这是我将与子命令一起使用的典型命令行:
I think what you are trying to accomplish is setting a default, typically this is done with
ArgumentParser.set_defaults()
. You need to do this with the uninitialised function. See this example:As an aside, you will have more problems with your snippet as you are defining the same parameter (
--sync
) in multiple places. When usingsubparsers
it is customary to make these positional (no leading--
) so they act as subcommands.Here is a typical command line that I would use with subcommands: