首页 > 解决方案 > cron 作业中的子进程检查输出失败

问题描述

我正在运行一个 cronjob,它调用一个具有子进程检查输出的 python 脚本。

我尝试了一个简单的脚本来调试。

import subprocess
import os


command = "/home/sgadamse/history_checker/code/rg \"hello\""
try:
    result = subprocess.check_output(command,shell=True)
    print(result)
except subprocess.CalledProcessError as e:
    print(e)

在 shell 中运行时的输出:我得到了我需要的输出

[~/history_checker/code]$ python a.py                                                                                                                                 

a.py:command = "/home/sgadamse/history_checker/code/rg \"hello\""

我创建了一个 cron 作业以在 crontab -e 中运行

* * * * * python /home/sgadamse/history_checker/code/a.py

执行时出现此错误:

Command '/home/sgadamse/history_checker/code/rg "hello"' returned non-zero exit status 1

/home/sgadamse/history_checker/code/rg 是我下载并使用它的完整 rg 二进制路径。

我们是否需要为 cron 作业执行不同的子流程检查输出?

谢谢。

编辑:我试图调试 rg,它实际上正在运行命令,但它搜索的文件只是“stdin”,没有其他任何想法为什么会发生这种情况?

标签: pythonbashcronsubprocess

解决方案


这是man rg

ripgrep 将自动检测标准输入是否存在并在标准输入中搜索正则表达式模式,例如ls | rg foo. 在某些环境中,标准输入可能在不应该存在的情况下存在。要关闭标准输入检测,明确指定要搜索的目录,例如rg foo ./.

Vixie Cron 就是这样一种环境,因为无论出于何种原因,它将 stdin 设置为封闭管道,而不是更典型的从以下重定向/dev/null

        /* create some pipes to talk to our future child
         */  
        pipe(stdin_pipe);       /* child's stdin */ 

所以你应该能够在你的 shell 中重现它true | python .../a.py,并通过添加手册中建议的路径来修复它 ( rg "hello" ./)


推荐阅读