我的python程序通过ssh获取邮件日志数据。当我尝试用
换行时每行with text as f:
for line in f:
try:
.... regex stuff....
我收到错误:
Traceback (most recent call last):
File "xxxxxxxxxxxxxxxxxxxxxxxx", line 90, in <module>
start()
File "xxxxxxxxxxxxxxxxxxxxxxxx", line 64, in start
with text as f:
AttributeError: __exit__
这不起作用,对我有用的唯一解决方案如下。当我将文本保存为文件并再次打开时。但该文件大约1.24 MB,这不必要地减慢程序。有谁知道如何摆脱额外的储蓄?
....
stdin, stdout, stderr = ssh.exec_command('sudo cat /var/log/mailing.log')
text = ''.join(stdout.readlines())
text_file = open('mail.log', 'w')
text_file.write(text)
text_file.close()
ssh.close()
with open('mail.log') as f:
for line in f:
try:
.... regex stuff....
答案 0 :(得分:1)
text
是包含数据的字符串。你无法打开它。而不是打开它,你应该只是循环它
for line in text.splitlines():
try:
.... regex stuff....
答案 1 :(得分:1)
您可能希望从标准库中查看StringIO,这会使字符串看起来或多或少像文件。
或者,你可以说
for line in f.split('\n'):
try:
<regex stuff>