【发布时间】:2016-06-20 02:14:46
【问题描述】:
我尝试了 3 种在启动时启动 python 脚本的方法:
- 将包含完整路径的脚本行添加到 python3 bin 和脚本到 rc.local(验证权限是否可执行)
此选项将执行 shell 脚本和其他命令,但由于某种原因它只是不执行我的 python 脚本。实际上,它看起来可能会,但它永远不会完成,因为我没有得到显示它工作的输出文件。
添加到 /etc/init.d 并创建符号链接
在 cron 中添加 @reboot
使用 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