目前有一个脚本,脚本功能就是通过ssh读取远端的日志,然后tail似输出.脚本如下:
from sshtail import SSHTailer ,load_rss_key
from time import sleep
pkey=load_rsa_key('id_rsa')
tailer = SSHTailer('[email protected]', '/var/log/mytest.log',private_key=pkey)
while 1:
for line in tailer.tail():
print line
sleep(1)
脚本在正常情况下可以正常运行,但是当那个日志文件不存在的时候,就会raise 一个ioerror exception,
于是我改脚本,思路是当碰到这个ioerror 的时候我不退出脚本,取而代之的是sleep 5秒(5s 内我会自己去创建那个mytest.log文件)然后再继续干活.
于是改成如下:
#!/usr/bin/python
from sshtail import SSHTailer ,load_rsa_key
from time import sleep
pkey=load_rsa_key('id_rsa')
tailer = SSHTailer('[email protected]', '/var/log/mytest.log',private_key=pkey)
try:
while 1:
for line in tailer.tail():
print line
sleep(1)
except IOError, e:
print "error: %s"%e
print 'catch an io error'
#tailer.disconnect()
sleep(5.0)
while 1:
for line in tailer.tail():
print line
sleep(1)
最后发现还是会退出脚本。报错如下:
error: [Errno 2] No such file
catch an io error
Traceback (most recent call last):
File "/home/wumin/1.py", line 24, in <module>
for line in tailer.tail():
File "/usr/local/lib/python2.7/site-packages/sshtail/tailers.py", line 57, in tail
fstat = self.sftp_client.stat(self.remote_filename)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 413, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 729, in _request
return self._read_response(num)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 776, in _read_response
self._convert_status(msg)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 802, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
我的目的就是要在我这个脚本里面实现,发现 ioerror exception 不退出脚本,而是sleep ,然后等那个/var/log/mytest.log生成了以后还是继续干活.
这个该怎么处理这个exception呢.要改sshtail这个库或者 paramiko里面的代码才能做到吗?一定要在所有涉及到的代码里面都处理这个ioerror exception才能做到吗?
求教
1
ri0day OP v2ex 怎么让代码保持格式.
|
4
yangtukun1412 2015-06-23 17:38:41 +08:00
while True:
try: do_something() except IOError, e: log_error() 把 try catch 写在循环里面。 |
5
yangtukun1412 2015-06-23 17:40:09 +08:00
| while True:
| try: | do_something() | except IOError, e: | log_error() 这样子格式应该不会乱掉了吧... |
6
ri0day OP @yangtukun1412 谢谢 ,问题解决了。
try确实要写在while true 里面. |
7
dalang 2015-06-24 13:10:41 +08:00
我觉得是因为你 sleep 了 5s 后,那个文件仍然没有创建,于是又 raise ioerrror。
|