【问题标题】:starting a python3 script in ubuntu at boot and wont execute properly using cron /etc/init.d rc.local systemd在启动时在 ubuntu 中启动 python 脚本,并且无法使用 cron /etc/init.d rc.local systemd 正确执行
【发布时间】:2016-06-20 02:14:46
【问题描述】:

我尝试了 3 种在启动时启动 python 脚本的方法:

  1. 将包含完整路径的脚本行添加到 python3 bin 和脚本到 rc.local(验证权限是否可执行)

此选项将执行 shell 脚本和其他命令,但由于某种原因它只是不执行我的 python 脚本。实际上,它看起来可能会,但它永远不会完成,因为我没有得到显示它工作的输出文件。

  1. 添加到 /etc/init.d 并创建符号链接

  2. 在 cron 中添加 @reboot

  3. 使用 systemd 创建服务并执行它

所有这些看起来都像是在触发脚本,但就像最后一个一样,我让脚本由 cron 启动,然后脚本删除了启动脚本的 cron 作业。当我从命令行正常执行脚本时,它可以完美运行。但是,当 cron 启动它时,它似乎部分执行,导致 /etc/crontab 文件被删除。

这是否与被删除文件的上下文有关?

我尝试将 2> 标记为上述几乎所有其他方法,以查看是否发生错误,但我在 stderr 文件中实际上一无所获。还将 stderr/print 添加到 rc.local。

这是我的脚本

#!/usr/bin/env python3
import time
import subprocess
import re

cron = open("/etc/crontab","r")
print("1")
cronText = cron.read()
cron.close
print("2")
cron = open("/etc/crontab","w")
print("3")
cron.write('')
print("4")
cronText = re.sub(r'\* \* \* \* \* root /usr/bin/env python3 /root/Desktop/test\.py 2\> /root/Desktop/err\.log','',cronText)
print("5")
cron.write(cronText)
cron.close
print("6")
subprocess.call("service cron restart",shell=True)
print("7")
file1 = open("thisWORKED.txt","w")
print("8")
file1.write("This totally worked")
file1.close
print("9")

这是 /etc/crontab 的样子

# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
* * * * * root /usr/bin/env python3 /root/Desktop/test.py > /root/Desktop/err.log 2>&1

err.log 字面上没有给出任何输出。当我尝试其他方法时,我尝试像任何地方一样标记 stderr。我主要是想弄清楚为什么我的脚本没有启动。

【问题讨论】:

    标签: python-3.x ubuntu cron boot init.d


    【解决方案1】:

    好吧,哈哈,我知道我做错了什么。我现在感觉自己像个假人。基本上,它在 root 用户的上下文中运行,因此成功的日志文件被转储到 /root 而不是运行脚本的 /home 中。因此,为什么在 stderr 中没有要报告或查看的错误。

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2010-12-06
      相关资源
      最近更新 更多