繁体   English   中英

如何处理Python XML-RPC输出和异常?

[英]How do I handle Python XML-RPC output and exceptions?

我已经创建了一个简单的Python XML-RPC实现,主要基于这些示例。

但是,它发送如下输出:

foo.bar.com - - [13/Feb/2010 17:55:47] "POST /RPC2 HTTP/1.0" 200 -

...到终端,即使我使用>>>将标准输出和标准错误重定向到文件。 我正在使用以下行:

python foobar 2>&1 >> foobar.log

看起来它似乎不是标准输出,而是其他地方。

此外,当收到请求时发生异常时,整个应用程序崩溃时出现此错误:

----------------------------------------
Exception happened during processing of request from ('1.2.3.4', 51284)

我该如何处理这个异常? 我需要优雅地恢复,只记录异常消息而不是服务器崩溃。

我猜您正在使用示例中的SimpleXMLRPCServer类。 在这种情况下,只需在创建时提供参数logRequests

server = SimpleXMLRPCServer(("localhost", 8000), logRequests = False)

这将抑制请求记录。

至于异常,他们登录BaseServer (参见“SocketServer.py”的源代码):

def handle_error(self, request, client_address):
    """Handle an error gracefully.  May be overridden.

    The default is to print a traceback and continue.

    """
    print '-'*40
    print 'Exception happened during processing of request from',
    print client_address
    import traceback
    traceback.print_exc() # XXX But this goes to stderr!
    print '-'*40

如您所见,第一部分写入stdout,这就是为什么&2>1不能完全运行的原因。 如果要禁止它们,请覆盖或覆盖该方法。

这实际上是一个shell重定向问题,而不是python问题。 当你说

python foobar 2>&1 >> foobar.log

你是第一个重定向错误输出到标准输出,然后第二重定向标准输出到foob​​ar.log。 stderr不会自动重定向到foobar.log。 stderr仍然指向原来的标准输出。

所以改为:

python foobar >> foobar.log 2>&1 

另见http://bash-hackers.org/wiki/doku.php/syntax/redirection (搜索“多重重定向”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM