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