views:

145

answers:

2

I need to execute a script in the background through a service.

The service kicks off the script using Popen.

p = Popen('/path/to/script/script.py', shell=True)

Why doesn't the following script work when I include the file writes in the for loop?

#!/usr/bin/python

import os
import time

def run():
    fd = open('/home/dilleyjrr/testOutput.txt', 'w')

    fd.write('Start:\n')
    fd.flush()

    for x in (1,2,3,4,5):
        fd.write(x + '\n')
        fd.flush()
        time.sleep(1)

    fd.write('Done!!!!\n')
    fd.flush()

    fd.close()

if __name__ == '__main__':
    run()
A: 

What error are you getting? It's hard to see the problem without the error. Is there anyway that the file is opened somewhere else?

Dan Lorenc
I don't see any errors. The script is executed in the background of the service. The file isn't open with any other application.I'm new to writing services/mod_python/apache if there should be errors some where, can you point out the log files?Thanks.
Ron
+1  A: 

Here's your bug:

for x in (1,2,3,4,5):
    fd.write(x + '\n')

You cannot sum an int to a string. Use instead (e.g.)

for x in (1,2,3,4,5):
    fd.write('%s\n' % x)
Alex Martelli
I have permissions on the file as 777.I just switched it to /tmp, your right that would be better for this testing.The results are the same if I comment out the loop file writes the output is...Start:Done!!!!With them includes the output is...Start:
Ron
Tx Ron for checking the permissions issue -- prompted me to do a thorough code review and spot your bug, see my just-edited answer.
Alex Martelli
Thanks --- I'm too new to python yet I keep forgetting you can't do that like you can in perl. Now that that is solved I can get on to my problems with the real script. (Think they are environment related.) I'm going to use this one to spit out the environment.
Ron