2013-02-28 70 views
3

我正在学习使用扭曲(最新的12.3.0版本),作为为移动应用程序做一些简单的服务器端处理的一种方式。twisted使用进程

我的第一个分配基本上是在日志文件上运行'tail'命令,并将后处理的发现行传送给移动应用程序。这应该是容易...

现在在TwistedMatrix网站上的文档有一个“使用流程”页面,在这里我得到了下面的代码:


from twisted.internet import protocol, utils, reactor 
from twisted.python import failure 
from cStringIO import StringIO 

class CommandRunner(protocol.Protocol): 

    #command = "ls /" 
    command = "tail -n 100 /var/log/system.log" 

    def connectionMade(self): 
     output = utils.getProcessOutput(self.command) 
     output.addCallbacks(self.writeResponse, self.noResponse) 

    def writeResponse(self, resp): 
     self.transport.write(resp) 
     self.transport.loseConnection() 

    def noResponse(self, err): 

     print err 
     self.transport.write("Houston, we have an error!\n") 
     self.transport.loseConnection() 


if __name__ == '__main__': 
    f = protocol.Factory() 
    f.protocol = CommandRunner 
    reactor.listenTCP(10999, f) 
    reactor.run() 

是99.9%相同发布到“简单易行”的发布代码片段中。唯一的变化是应该执行扭曲的shell命令(在我的Mac上我似乎没有命运的命运)。

启动示例代码,当我尝试在10999端口上从通过telnet第二终端连接后,我得到这个错误:

[Failure instance: Traceback (failure with no frames): : got stderr: 'Upon execvpe tail -n 100 /var/log/system.log [\'tail -n 100 /var/log/system.log\'] in environment id 4315532016\n:Traceback (most recent call last):\n File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Twisted-12.3.0-py2.7-macosx-10.6-intel.egg/twisted/internet/process.py", line 420, in _fork\n executable, args, environment)\n File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Twisted-12.3.0-py2.7-macosx-10.6-intel.egg/twisted/internet/process.py", line 466, in _execChild\n os.execvpe(executable, args, environment)\n File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 353, in execvpe\n _execvpe(file, args, env)\n File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 368, in _execvpe\n func(file, *argrest)\nOSError: [Errno 2] No such file or directory\n']

我看不出有什么明显的原因代码应与文件[错误2]没有这样的文件或目录\ n']错误..

蒂亚

回答

5

要运行的程序是‘尾巴’。你想传递几个参数:“-n”,“100”和“/var/log/system.log”。

相反,你的代码所做的是运行程序“tail -n 100 /var/log/system.log”,这可能不存在于你的系统上(我不会期望它)。

正确使用getProcessOutput是从参数列表分别通过方案:

getProcessOutput("tail", ["-n", "100", "/var/log/system.log"]) 
+1

让·保罗,谢谢! 在Mac(或任何其他地方)显然没有“tail -n 100 /var/log/system.log”... 更正调用getProcessOutput的方法可修复问题! 谢谢,阿尔多 – aaberga 2013-02-28 17:34:16