0

I have a running server with Django. After receiving a request I want to start a python script with parameters running in the background and not blocking the server. Also I want to write all the logs to a log file. A working command to start the script is:

python -u script.py --param1=value1 --param2=value2 > log.txt

But when I try to run the script from my server script with the same functionality it does not work. I tried os.system(), execfile() and various forms of subprocess.Popen() but nothing worked.

Examples:

Popen("python -u " + scriptPath + paramString + " > " + LOG_DIR + "\\log.txt", creationflags=CREATE_NEW_CONSOLE)

os.system("python -u " + scriptPath + paramString + " > " + LOG_DIR + "\\log.txt")

Sometimes the script is executed but the logging does not work and sometimes nothing works. Is there a solution to my problem?

Tobias
  • 95
  • 1
  • 2
  • 9
  • 5
    Celery is the solution. – Daniel Roseman Apr 30 '14 at 09:33
  • 1
    FWIW, you should be using `subprocess` instead of `os.system`. Also, depending in your use case, you may want to consider writing a daemon instead of launching processes from django. – loopbackbee Apr 30 '14 at 09:35
  • I really don't want to add something like celery. goncalopp I know that subprocess is the way to go but I just can't get it to work properly. As for daemons I'm running on windows. Is this working there? – Tobias Apr 30 '14 at 09:46
  • What happens if you run `p = Popen("python -u script.py --param1=value1 --param2=value2 > log.txt", shell=True)`? Call `p.poll()` to find out whether the process exits prematurely. You could also use `stdout` parameter, here's [code example](http://stackoverflow.com/a/12606327/4279) – jfs Apr 30 '14 at 13:43

0 Answers0