python - 从 Python 脚本调用以在 Linux 中重新启动 "service"在 crontab 条目中不起作用

标签 python linux cron

我有以下 python 测试脚本(从一个更大的 .py 文件中提取),我试图在 EC2 实例(haproxy OpsWorks 实例)上运行。

作为 cron 条目运行时应用的权限与作为 shell 中的 python 脚本运行时应用的权限之间似乎存在重大差异。

我在任何其他帖子中找到的最接近的是 here但这与 shell 脚本有关,并且考虑到我正在运行 python OK,应该(我希望)为 cronjob 充分配置路径。

环境: - Python 版本:2.6.8 - 环境:EC2 上的 OpsWorks HAProxy 实例。 - 以用户身份运行:root。

脚本

import subprocess
import boto
import logging

if __name__ == '__main__':
    logging.getLogger().setLevel(boto.logging.INFO)
    command = ['service', 'haproxy', 'reload'];
    logging.info('Executing: %s' % command)
    #shell=FALSE for sudo to work.
    subprocess.call(command, shell=False)

我也曾尝试使用以下方法调用子进程命令,但无济于事。

# subprocess.call("%s %s %s %s" % ('sudo', 'service', 'haproxy', 'reload'))

从命令行运行时的输出:

[root@lb1 ~]# python tester.py
INFO:root:Executing: ['service', 'haproxy', 'reload']
Reloading haproxy:
[root@lb1 ~]#

Crontab 条目:

[root@lb1 ~]# crontab -l
*/1 * * * * python ~/tester.py > ~/testlog 2>&1

作为 crontab 命令运行时的输出

[root@lb1 ~]# cat testlog
INFO:root:Executing: ['service', 'haproxy', 'reload']
Traceback (most recent call last):
  File "/root/tester.py", line 13, in <module>
    subprocess.call(command, shell=False)
  File "/usr/lib64/python2.6/subprocess.py", line 478, in call
    p = Popen(*popenargs, **kwargs)
  File "/usr/lib64/python2.6/subprocess.py", line 639, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1228, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

我很困惑为什么它会抛出“没有这样的文件或目录”错误!

谁能指点一下?顺便说一句,这是一个更大的 EC2 集成部分的一部分——因此引入了 boto [这是在此实例中获取日志记录的好方法]。它以 root 身份运行,因为从浏览 SO 来看,为使用 sudo 命令运行的用户帐户设置一个 cron 条目是不好的做法。

干杯,

最佳答案

在子进程中设置shell=True

subprocess.call(command, shell=True)

我认为你的问题会得到解决,但可能会出现 sudo 问题。

关于python - 从 Python 脚本调用以在 Linux 中重新启动 "service"在 crontab 条目中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21164334/

相关文章:

python - 如何清理文本数据中的\xc2\xa0\xc2\xa0.....

linux - Linux 中文件的剪切列

PHP Cronjob 不执行

python - 寻找一种更快的模糊字符串匹配方法

python - 将 Keras 与 Spearmint 集成的问题

python - Python shell 和程序中的不同行为

cron - 如何设置 cron 每 40 分钟/25 分钟运行一次我的脚本?

php - PHP 中的定时任务(类似 cron)

python - 语音转文本代码卡在 "say something":

linux - 在设置位置参数时使用 - 和 -- 作为要设置的选项之间的区别