0

my python program gets via ssh a mail log data. When I try to go over it line per line with

with text as f:
    for line in f:
        try:
             .... regex stuff....

I get the error:

Traceback (most recent call last):
  File "xxxxxxxxxxxxxxxxxxxxxxxx", line 90, in <module>
    start()
  File "xxxxxxxxxxxxxxxxxxxxxxxx", line 64, in start
    with text as f:
AttributeError: __exit__

That doesn't work, the only solution which works for me is the following. When I save the text as file and open it again. But the file is about 1.24 MB big, which slows the program unnecessarely. Anyone know how I can get rid of the extra saving?

....
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....
3
  • 1
    text is a not a context manager, why do you try to treat it as such? What is text in your original code? Commented Oct 17, 2013 at 10:40
  • Where does ssh.exec_command() come from? Commented Oct 17, 2013 at 10:41
  • the var 'text' is all the text in the file 'mailing.log'. I think I didn't understand the concept of a context manager.... 'ssh.exec_command()' comes from the module paramiko I use. Commented Oct 17, 2013 at 10:46

2 Answers 2

1

text is a string with data. You can't open that. Instead of opening it you should just loop over it

for line in text.splitlines(): 
    try:
         .... regex stuff....
Sign up to request clarification or add additional context in comments.

2 Comments

Take a look at str.splitlines() too.
@MartijnPieters Didn't know splitlines(), I usually use split(os.sep). I changed it now. Thanks!
1

You probably want to look at StringIO from the standard library, which makes a string look more or less like a file.

Or, you could just say

for line in f.split('\n'):
     try:
        <regex stuff>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.