Python cron 作业 returns 与手动执行不同的输出

Python cron job returns different output than manual execution

我的 python 脚本在 运行 通过 cron 时切断字符串。

我有一个 python 脚本,它捕获 unix“top”命令的输出,遍历以找到我需要的指标并将它们打印到输出文件。我想每 15 分钟捕获一次这些指标,因此我已将脚本添加到用户 crontab。

但是,通过 cron 执行的脚本会产生不同的输出。

命令行输出(期望):

User       %CPU    %MEM    Time_Running    Command
-------------------------------------------------------------------------------------------------------
hpc        977.8   12.1    19689:06        ./mix99s
3tb        94.4    0.1     0:06.67         python -c import sys;
3tb        94.4    2.2     50:57.58        /apps/anaconda3/bin/python3 Cross_Platform_Validation.py
fhpc       16.7    0.0     0:00.05         top -b -c -n1
---------------------------------------------------------------------------------------------------------

Cron 作业输出:

User       %CPU    %MEM    Time_Running    Command
-------------------------------------------------------------------------------------------------------
hpc        977.8   12.1    19689:06        ./mix99s
3tb        94.4    0.1     0:06.67         python -c+
3tb        94.4    2.2     50:57.58        /apps/ana+
fhpc       16.7    0.0     0:00.05         top -b -c+
---------------------------------------------------------------------------------------------------------

cron 作业总是切断任何长度超过 10 个字符的字段(请参阅上面的“命令”) 我认为这可能是由于子进程 Popen 中的缓冲区大小所致,但更改 bufsize=-1 没有影响。

我脚本的重要部分是:

# Get Top command output
top_out = subprocess.Popen(['top', '-b', '-c', '-n1'], bufsize=-1, stdout=subprocess.PIPE).stdout
...

    # Task output always starts on line 7
    elif i > 6:
        # sep=None ie. split by whitespace. Max 11 splits
        cols = line.split(None, 11)

        user = cols[1]
        cpu = cols[8]
        mem = cols[9]
        time_run = cols[10]
        command = cols[11]

        outfile.write('{}'.format(user))
        outfile.write('{}'.format(cpu))
        outfile.write('{}'.format(mem))
        outfile.write('{}'.format(time_run))
        outfile.write('{}'.format(command))

问题是当通过 cron 运行 时 top 命令输出被 t运行 限制为 80 个字符,如下所述:https://unix.stackexchange.com/questions/95877/output-of-top-gets-truncated-to-80-columns-when-run-by-cron

更改我的 cron 作业以包含 COLUMNS 选项解决了问题

原创

# Run monitor script every 15 minutes
*/15 * * * * /mnt/active/monitor_cluster/monitor.py

工作

# Run monitor script every 15 minutes
*/15 * * * * COLUMNS=200 /mnt/active/monitor_cluster/monitor.py