子进程检查输出在 cron 作业中失败

sub process check output fails in cron job

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

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

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\""

我在 crontab -e

中为 运行 创建了一个 cron 作业
* * * * * 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,它实际上是 运行ning 命令,但它搜索的文件只是“stdin”,没有别的 知道为什么会这样吗?

这里是man rg

ripgrep will automatically detect if stdin exists and search stdin for a regex pattern, e.g. ls | rg foo. In some environments, stdin may exist when it shouldn’t. To turn off stdin detection explicitly specify the directory to search, e.g. rg foo ./.

Vixie Cron 就是这样一种环境,因为无论出于何种原因 it sets stdin to a closed pipe 而不是来自 /dev/null 的更典型的重定向:

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

因此您应该能够在 shell 中使用 true | python .../a.py 重现它,并按照手册中的建议添加路径来修复它 (rg "hello" ./)