以启动服务ubuntu 12.04运行python脚本

以启动服务ubuntu 12.04运行python脚本,python,ubuntu,Python,Ubuntu,我的python脚本将多个目录作为用户的输入,我希望用户只输入一次目录,然后即使在系统引导之后,程序也应在相同的目录上连续运行,而无需再次询问用户。我想使用管理器配置来设置此设置。任何帮助???您可以将其添加到您的crontab crontab -e 添加以下行,该行将在计算机启动时执行: @reboot python /path/to/your/script.py 确保末尾至少有一条空行。 至于从脚本停止的地方重新启动,您必须将其编程到应用程序逻辑中。制作cron作业或创建服务初始化脚本(

我的python脚本将多个目录作为用户的输入,我希望用户只输入一次目录,然后即使在系统引导之后,程序也应在相同的目录上连续运行,而无需再次询问用户。我想使用管理器配置来设置此设置。任何帮助???

您可以将其添加到您的crontab

crontab -e
添加以下行,该行将在计算机启动时执行:

@reboot python /path/to/your/script.py
确保末尾至少有一条空行。
至于从脚本停止的地方重新启动,您必须将其编程到应用程序逻辑中。

制作cron作业或创建服务初始化脚本(有关如何在当前Ubuntu版本下编写初始化脚本的信息,请参阅手册)

做一份工作:

EDITOR=nano; crontab -e
@reboot cd /home/user/place_where_script_is; python3 myscript.py param1 param2
用户没有有效的方法向启动脚本输入数据,主要是因为它们在根环境中运行。 cron作业总是在您调用
crontab-e
(希望是用户环境)的环境中运行,但即便如此。。 您无法与它交互,因为它在单独的“shell”中运行

Unix套接字? 在脚本中,在unix套接字上添加侦听套接字。
.bashrc
脚本中(不确定Ubuntu的post X启动脚本在哪里),调用连接到unix套接字并在那里发送指令的
callMyScript.py

通过这种方式,您可以与cronjob/service脚本交互

下面是您如何跟踪服务是否失效的方法 PID文件是关键:

#!/usr/bin/python3
pidfile = '/var/run/MyApplication.pid'

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if pid < 0:
        return False
    try:
        os.kill(pid, 0)
    except OSError, e:
        return e.errno == errno.EPERM
    else:
        return True

if isfile(pidfile):
    with open(pidfile) as fh:
        thepid = fh.read()

    pidnr = int(thepid)
    if pid_exists(pidnr):
        exit(1) # The previous instance is still running
    else:
        remove(pidfile) # Prev instance is dead, remove pidfile

# Create a pid-file with the active PID written in it
with open(pidfile, 'w') as fh:
    fh.write(str(getpid()))

## Your code goes here...

remove(pidfile)
它将每分钟运行脚本,如果脚本已停止或未启动,脚本将再次启动


如果您编写了init脚本,init脚本将检查PID文件(您必须在init脚本中编写此脚本,并像上面的Python代码一样亲自检查PID)然后查看进程是否已停止。

即使用户未登录,在系统引导后您是否真的需要它,或者在用户作为后台任务登录后自动运行脚本是否足够?我想使用supervisor配置使脚本按引导前的状态运行。帮助??我想继续使用supervisor运行脚本。建议???@kraken2242建议如何在Python中解决它,在bash中使用类似的方法(检查PID),并编写自己的init脚本。我使用的是
systemd
,这是一种与init脚本完全不同的方法,因此我无法在那里测试我的代码,因为我无法为您编写代码。
EDITOR=nano; crontab -e
* * * */1 cd /home/user/place_where_script_is; python3 myscript.py param1 param2