簡體   English   中英

為什么這個argparse代碼在Python 2和3之間表現不同?

[英]Why does this argparse code behave differently between Python 2 and 3?

下面的代碼,使用argparse的subparsers,在Python 3上失敗,但在Python 2中按預期運行。在比較文檔后,我仍然無法說明原因。

#!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser


def action(args):
    print(args)

if __name__ == '__main__':
    std = ArgumentParser(add_help=False)
    std.add_argument('standard')

    ap = ArgumentParser()
    sp = ap.add_subparsers()

    cmd = sp.add_parser('subcommand', parents=[std], description='Do subcommand')
    cmd.add_argument('arg')
    cmd.set_defaults(do=action)

    args = ap.parse_args()
    args.do(args)

Python 2.7.6的輸出是:

me@computer$ python test.py 
usage: test.py [-h] {subcommand} ...
test.py: error: too few arguments

在Python 3.3.5中,我得到:

me@computer$ python3 test.py 
Traceback (most recent call last):
  File "test.py", line 21, in <module>
    args.do(args)
AttributeError: 'Namespace' object has no attribute 'do'

最新的argparse版本改變了它測試所需參數的方式,而subparsers則陷入了困境。 它們不再是“必需的”。 http://bugs.python.org/issue9253#msg186387

當你得到test.py: error: too few arguments ,它反對你沒有給它一個'子命令'參數。 在3.3.5中,它使它超過該步驟,並返回args

通過此更改,3.3.5應該與早期版本的行為相同:

ap = ArgumentParser()
sp = ap.add_subparsers(dest='parser')  # dest needed for error message
sp.required = True   # force 'required' testing

注意 - 需要設置destrequired dest需要在錯誤消息中為此參數指定名稱。


這個錯誤:

AttributeError: 'Namespace' object has no attribute 'do'

是因為cmd subparser沒有運行,並且沒有將其參數(默認或不是)放入命名空間。 您可以通過定義另一個subparser並查看生成的args來查看該效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM