当方法名称仅在运行时已知时,如何使用 Python 调用 XML RPC 方法



我在下面有一些调用XML RPC方法的Python代码:

from xmlrpclib import ServerProxy
s = ServerProxy("http://localhost:8000")
s.SomeMethod('parameter')

但是,当方法的名称(SomeMethod)仅在运行时知道时会发生什么?当方法名称在变量中时,有什么方法可以调用方法吗?

我尝试了以下方法,但没有一个有效:

s['SomeMethod']('parameter')
s.__getattr__('SomeMethod')('parameter')
getattr(s, 'SomeMethod')('parameter')

它们都返回:

xmlrpclib.Fault: <Fault -32601: 'Method not found'>

进一步编辑:这开始变得非常奇怪。当我使用 s['SomeMethod']('parameter') 时,远程服务器报告我尝试调用 XML 方法__getattr__

getattr

预期工作。如果我尝试获取返回值的repr,它会失败,因为 ServerProxy 类不会公开"repr"方法。因此,如果从交互式提示中,我只键入:

>>> getattr(proxy, "is_even")
Traceback (most recent call last):
(...)
xmlrpclib.Fault: <Fault 1: '<type 'exceptions.Exception'>:method "is_even.__repr__" is not supported'>

但我可以这样做:

>>> a = getattr(proxy, "is_even")
>>> a(5)
False
>>> 

(使用的服务器端截图是 Python 的 cmlrpc 文档中的截图:http://docs.python.org/library/xmlrpclib.html )