使用
pyshark
0.6 在 Ubuntu 22.04.4 上运行以下 python 3.10.12 代码似乎忽略了 python 的 try-except
语句:
capture = pyshark.FileCapture(filename)
try:
for packet in capture:
pass
except:
print("exception")
即使我将读取循环包含在
try-except
语句中,我也会得到以下输出:
exception
Exception ignored in: <function Capture.__del__ at 0x79b5be57c3a0>
Traceback (most recent call last):
File "/home/alex/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 405, in __del__
self.close()
File "/home/alex/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 393, in close
self.eventloop.run_until_complete(self.close_async())
File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/alex/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 397, in close_async
await self._cleanup_subprocess(process)
File "/home/alex/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 379, in _cleanup_subprocess
raise TSharkCrashException(f"TShark (pid {process.pid}) seems to have crashed (retcode: {process.returncode}).\n"
pyshark.capture.capture.TSharkCrashException: TShark (pid 8097) seems to have crashed (retcode: 2).
Last error line: tshark: The file "/home/alex/Work/Data/test.pcap" appears to have been cut short in the middle of a packet.
Try rerunning in debug mode [ capture_obj.set_debug() ] or try updating tshark.
如何抑制这个输出?
澄清一下:我没有兴趣修复任何问题或错误。我只是对抑制异常的输出感兴趣!
根据
issue:
https://github.com/KimiNewt/pyshark/issues/339
以及
pyshark
最新版本的源代码,在这里https://github.com/KimiNewt/pyshark/blob/master/src/pyshark/capture/capture.py
366
方法中的 _cleanup_subprocess
行代码如下所示:
async def _cleanup_subprocess(self, process):
"""Kill the given process and properly closes any pipes connected to it."""
self._log.debug(f"Cleanup Subprocess (pid {process.pid})")
if process.returncode is None:
try:
process.kill()
return await asyncio.wait_for(process.wait(), 1)
except asyncTimeoutError:
self._log.debug(
"Waiting for process to close failed, may have zombie process.")
except ProcessLookupError:
pass
except OSError:
if os.name != "nt":
raise
elif process.returncode > 0:
if process.returncode != 1 or self._eof_reached:
raise TSharkCrashException(f"TShark (pid {process.pid}) seems to have crashed (retcode: {process.returncode}).\n"
f"Last error line: {self._last_error_line}\n"
"Try rerunning in debug mode [ capture_obj.set_debug() ] or try updating tshark.")
我认为您正在处理
Exception
因为您正在终端中打印 exception
这个 Exception
出现了,但你没有注意到它在那之后发生
尝试用以下方式关闭您的capture
:
capture = pyshark.FileCapture(filename)
try:
for packet in capture:
pass
except:
print("exception")
capture.close()