简体   繁体   中英

python program will not run in background

The following program:

import time
import random
while True:
    t=time.time()+1.
    f=0.
    while time.time()<t:
        f+=random.random()-.5
    time.sleep(1.)

Will run forever, alternatively using 100% of processor for a second then sleep for a second and continue doing this forever. When I run the program from the command line it does exactly that. When I run the program from the command line followed by an & character it also does works as expected in the background - until I close the Terminal application that I used to launch it which causes it to exit. How can I prevent this behavior and allow it to keep running when I close the terminal? I'll be running something like this on a remote server and when I disconnect it also exits the program. I can tell if it continues to run because top or system monitor shows the program cycling between 100% processor usage and normal system usage.

* Edit to clarify * This is not the actual program I'll be running, it is far too long to post here, but it functions in a similar way, spend 5 minutes or so highly active then a few minutes where its doing nothing. It continues this pattern forever.

You need to daemonize the process. That means disconnect it from the controlling terminal. When you run it as you are it keeps its controlling terminal and exits via signal SIGHUP when that terminal closes. A pure Python implementation of a daemonize module has the function daemonize . You just call that, and you're running in the background, disconnected from the controlling terminal.

Well one way to get the terminal to open is to save your program as *.pyw , or run it using pythonw.exe (windows). In order to terminal the program you could use the PID:

import os

f = file('test.txt','w')
f.write(str(os.getpid()))
f.close()

Hope this helps. I don't use Linux of OSX but I would imagine it would be similar.

The program "gnu screen" is how this is done. You can start a screen session, run a program, then detach from the session using Ctrl-a followed by d. To reattach, run screen -r.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM