简体   繁体   English

python程序将不会在后台运行

[英]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. 将永久运行,或者每秒使用100%的处理器,然后休眠一秒钟,然后继续永久运行。 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. 我可以判断它是否继续运行,因为顶级或系统监视器显示程序在100%处理器使用率和正常系统使用率之间循环。

* 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. *编辑以澄清*这不是我将要运行的实际程序,在这里发布的时间太长了,但是它的运行方式类似,花费5分钟左右或非常活跃,然后几分钟不执行任何操作。 It continues this pattern forever. 它永远延续这种模式。

You need to daemonize the process. 您需要daemonize进程。 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. 当您按原样运行时,它将保留其控制端子,并在该端子关闭时通过信号SIGHUP退出。 A pure Python implementation of a daemonize module has the function daemonize . 一的纯Python实现守护进程模块具有的功能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). 打开终端的一种好方法是将程序另存为*.pyw或使用pythonw.exe (windows)运行。 In order to terminal the program you could use the PID: 为了终止程序,您可以使用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. 我不使用OSX的Linux,但我想它会类似。

The program "gnu screen" is how this is done. 程序“ gnu屏幕”就是这样做的。 You can start a screen session, run a program, then detach from the session using Ctrl-a followed by d. 您可以启动屏幕会话,运行程序,然后使用Ctrl-a和d脱离会话。 To reattach, run screen -r. 要重新连接,请运行screen -r。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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