You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Crontab显示执行成功但无法运行Python3脚本问题求助

问题:Crontab执行Python脚本日志显示成功但未实际运行

位于/opt/send-message/目录下的Python3脚本,手动运行可正常推送消息至Hangouts Chat,但通过Crontab执行时,系统日志显示任务已执行,却未触发预期的消息推送。

脚本代码

from json import dumps
from httplib2 import Http
workdir="/opt/send-message/"
"""Hangouts Chat incoming webhook quickstart."""
url = 'https://chat.googleapis.com/v1/spaces/AAAA-JXmA-c/messages?key=' \
      '<key>&token=' \
      '<token>'
txt=open(workdir+"a.txt",'r')
txt=txt.read()
lista_cac=['"','{','}','[',']',',','description']
for c in lista_cac:
    txt=txt.replace(c,"")
txt=txt.split("\\n")
print(txt)
for i in txt:
    troca=i.replace("id:","Ofensa: " + " ")
    if troca.find("P5") != -1:
        bot_message = {'text':'*'+troca+'*'}
        message_headers = {'Content-Type': 'application/json; charset=UTF-8'}
        http_obj = Http()
        print(dumps(bot_message))
        response = http_obj.request(
                uri=url,
                method='POST',
                headers=message_headers,
                body=dumps(bot_message),
        )
        print(response)
# [END hangouts_python_webhook]

当前Crontab配置与执行日志

Crontab配置:

*/1 * * * * /usr/bin/python3 /opt/send-message/run.py

系统执行日志:

Jun  5 18:26:01 machine-linux CROND[7419]: (root) CMD (/usr/bin/python3 /opt/send-message/run.py)

已尝试的方案

  • 使用nuitka3生成可执行文件执行
  • 创建virtualenv并在虚拟环境中运行脚本
  • 将脚本中的httplib2库替换为requests库
  • 更换Linux发行版(从RHEL切换到Debian)
    以上方案均为手动运行正常,但Crontab执行仍无效。

解决思路

  1. 消除Crontab与手动环境的变量差异
    Crontab的执行环境缺少用户登录时的大部分环境变量(如PATH、网络代理变量等),可在Crontab命令中显式指定环境:

    */1 * * * * PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /usr/bin/python3 /opt/send-message/run.py
    

    若脚本依赖代理,需在Crontab中添加http_proxy、https_proxy变量:

    */1 * * * * http_proxy=http://proxy.example.com:8080 https_proxy=http://proxy.example.com:8080 /usr/bin/python3 /opt/send-message/run.py
    
  2. 捕获脚本执行日志
    修改Crontab配置,将脚本的标准输出和错误输出重定向到日志文件,排查具体执行问题:

    */1 * * * * /usr/bin/python3 /opt/send-message/run.py >> /opt/send-message/cron_exec.log 2>&1
    

    查看日志文件,确认是否存在文件读取失败、权限不足、网络请求报错等问题。

  3. 验证文件路径与权限
    确认Crontab执行用户(此处为root)对/opt/send-message/目录及a.txt文件有读写权限,避免因权限问题导致脚本无法读取文件。

  4. 测试Crontab环境下的网络连通性
    在Crontab中添加测试命令,验证目标URL的可达性:

    */1 * * * * curl -v https://chat.googleapis.com/v1/spaces/AAAA-JXmA-c/messages?key=<key>&token=<token> >> /opt/send-message/network_test.log 2>&1
    

    若网络不通,需检查Crontab环境的网络配置(如代理、防火墙规则)。

  5. 添加脚本内部调试日志
    在脚本中增加关键步骤的日志输出,确认逻辑是否正常执行:

    import logging
    logging.basicConfig(filename='/opt/send-message/script_debug.log', level=logging.INFO, format='%(asctime)s - %(message)s')
    
    # 读取文件后添加日志
    txt=open(workdir+"a.txt",'r').read()
    logging.info(f"读取到的a.txt内容: {txt}")
    
    # 循环处理时添加日志
    for i in txt.split("\\n"):
        troca=i.replace("id:","Ofensa: ")
        logging.info(f"处理后的内容: {troca}")
        if troca.find("P5") != -1:
            logging.info("检测到P5标识,准备发送消息")
            # 原发送逻辑...
    

    通过查看script_debug.log,确认是否进入消息发送分支,以及变量值是否符合预期。


内容的提问来源于stack exchange,提问作者Romulo Soares

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:40:19