繁体   English   中英

在没有外壳的情况下执行python脚本

[英]Execute a python script without the shell

#!/usr/bin/python
import time , os
def execute():
    while True :        
        if not os.path.isfile("hello.txt"):
            fo = open("hello.txt","w");

execute()

上面的代码在使用python filename.py命令执行时正常工作,但是在关闭外壳程序后立即停止执行。 我想知道有没有方法可以在不使用外壳的情况下执行此脚本(并连续执行)。 我不需要为此任务使用cronjobs。

谢谢

方法有很多。

  1. 您可以使用:
    nohup python filename.py和

  2. setsid python filename.py

  3. 使用“屏幕”

听起来您正在尝试创建守护程序,该守护程序在启动时会在后台分离并运行。

如果这是您想要的,那么有很多细节需要正确处理。 PEP 3143对其进行了解释。 幸运的是,有一个python-daemon参考库可以为您处理所有细节。 如果安装了该程序,那么您要做的就是示例中显示的内容:

#!/usr/bin/python
import time , os
import daemon

def execute():
    while True :        
        if not os.path.isfile("hello.txt"):
            fo = open("hello.txt","w");

with daemon.DaemonContext():
    execute()

该示例显示一个与from spam import main_program分开的包装脚本的原因是,它非常方便(至少对于调试而言)能够作为守护程序和前景脚本运行同一程序。 但是,如果您不希望这样做,则可以在一个脚本中完成所有操作。

(如果这不是您要的,而您只是想知道如何在Unix下在后台运行任何程序,那么对于SuperUser而言,这比StackOverflow更具问题。)

我知道有两个可用的选项,我个人在生产中使用。

更简单的选项: http : //www.tecmint.com/screen-command-examples-to-manage-linux-terminals/

您希望在程序崩溃或系统重新启动时自动重新启动的更好选择: http : //supervisord.org/running.html#adding-a-program

暂无
暂无

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

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