小编Wed*_*ood的帖子

为什么这个argparse代码在Python 2和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)
Run Code Online (Sandbox Code Playgroud)

Python 2.7.6的输出是:

me@computer$ python test.py 
usage: test.py [-h] {subcommand} ...
test.py: error: too few arguments
Run Code Online (Sandbox Code Playgroud)

在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 …
Run Code Online (Sandbox Code Playgroud)

python python-2.x argparse python-3.x

13
推荐指数
1
解决办法
3159
查看次数

XML-RPC 方法可以在 Python 中按名称(作为字符串)调用吗?

在 python 中,调用 XML-RPC 方法涉及调用代理对象上的方法:

from xmlrpclib import ServerProxy
print ServerProxy('https://example.com/rpc').api.hello_there('John')
Run Code Online (Sandbox Code Playgroud)

在其他一些语言中,例如 perl,您可以将方法名称作为方法参数传递。

use Frontier::Client;
$p = Frontier::Client->new(url => 'https://example.com/rpc');
$result = $p->call('api.hello_there', 'John');
print $result;
Run Code Online (Sandbox Code Playgroud)

有没有办法在 Python 中按名称(作为字符串)调用 XML-RPC 方法?

python xml-rpc xmlrpclib call getattr

5
推荐指数
1
解决办法
1579
查看次数

标签 统计

python ×2

argparse ×1

call ×1

getattr ×1

python-2.x ×1

python-3.x ×1

xml-rpc ×1

xmlrpclib ×1