【问题标题】:Python cron job returns different output than manual executionPython cron 作业返回与手动执行不同的输出
【发布时间】:2020-07-23 14:42:33
【问题描述】:

我的 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))

【问题讨论】:

    标签: python-2.7 cron subprocess popen top-command


    【解决方案1】:

    问题在于通过 cron 运行时顶部命令输出被截断为 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
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 2014-09-06
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      相关资源
      最近更新 更多