Question

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()
Was it helpful?

Solution

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)

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top