3

I'm having an issue with my websocket script. Over time it consumes more and more CPU. One remedy I've discovered is to clear the associated logfile. This resolves the problem for a little while, but the CPU usuage builds up to 120% in little over a day or so. (using the top command on the linux server)

The part of the script that does the file write looks a bit odd to me. Here is the code:

 f = open(file, 'a')
 f.write(line+"\n")
 os.fsync(f.fileno())
 f.flush()
 f.close

I'm not a Python expert, but for starters, the last three things do rather the same in my opinion. The python manual states http://docs.python.org/2/library/os.html#os.fsync that f.flush and os.fsync should be in reverse order...

Can I just use:

 f = open(file, 'a')
 f.write(line+"\n")
 f.close

and should it not be: f.close()??

Any ideas?

2
  • 2
    You are never closing your file, yes it should be f.close() Commented May 2, 2013 at 12:20
  • You're right in that a close() implies a flush(), and I've no idea what fsync() is meant to accomplish if you're already working on a file object and not on the raw handles. Commented May 2, 2013 at 12:25

1 Answer 1

4

Use this to open (and automatically close) your files:

with open(filename, 'a') as f:
    f.write(line+"\n")
Sign up to request clarification or add additional context in comments.

1 Comment

Even with this modification, the script still eats CPU like mad. It is the correct answer, so I'll accept it.

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.