python实现tail命令,包含-f -n参数

本文介绍了一个Python脚本,该脚本能读取文件并输出指定行数的内容。此外,脚本还支持实时更新显示文件的最新内容,适用于监控日志文件等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
import sys
import time
def printlines(lines,line_start=0):
    if len(lines)>10:
        line_start= len(lines)-10
        while line_start<len(lines):
               print lines[line_start]
               line_start=line_start+1
    else:
        while line_start<10:
            print lines[line_start]
            line_start=line_start+1

          
def get_last_lines(filepath,f='',n=10):
    import os
    already_print_num=0
    if not os.path.exists(filepath):
        print 'no such file'
        sys.exit()
        return
    readfile = open(filepath,'r')
    lines = readfile.readlines()
    if f=='':
        printlines(lines)
       
    else:  #不会在复制了输入文件的最后的指定单元后终止
        while True:  #每隔一秒刷新一次
          if already_print_num<len(lines):
              printlines(lines)
          else:
              readfile = open(filepath,'r')
              lines = readfile.readlines()
              while already_print_num<len(lines):
                  print lines[already_print_num]
                  already_print_num=already_print_num+1
          already_print_num=len(lines)        
          time.sleep(1)
          
    readfile.close()

    
    
   

<think>我们需要在Python中执行一个bash命令,并且这个命令涉及到进程替换(Process Substitution),比如`diff <(command1) <(command2)`。在Linux的bash中,进程替换是通过`/dev/fd/`下的文件描述符来实现的,但是注意,在Python中直接使用`subprocess.run`执行这样的命令时,需要设置`shell=True`并且使用一个支持进程替换的shell(如bash)。 然而,需要注意的是,进程替换是bash的特性,在普通的sh中可能不支持。因此,在Python中执行这样的命令时,我们应该指定使用bash。 另外,我们还需要在bash命令执行完成后退出bash。 具体步骤: 1. 构建完整的bash命令字符串,包括要执行的diff命令和exit。 2. 使用Python的subprocess模块运行这个bash命令,并捕获输出。 但是,注意:我们执行的命令是`diff <( tail -n +5 new_top.log_tmp ) <( tail -n +5 new_top.log_tmp_1 )`,然后退出。 我们可以这样写: command = "diff <( tail -n +5 new_top.log_tmp ) <( tail -n +5 new_top.log_tmp_1 ); exit" 然后使用subprocess.Popen或者subprocess.run,并指定shell=True,且可执行文件为bash。 但是,由于我们可能希望获取diff命令的输出(包括标准输出和标准错误),我们需要捕获它们。 另外,注意:在子进程中,我们可能需要指定当前工作目录,如果文件路径不是当前目录,需要调整。 下面是一个示例代码: 注意:由于进程替换在非交互式shell中也是可用的,所以我们可以直接使用。 我们将使用subprocess.run,并传递一个字符串作为命令,设置shell=True,并指定使用bash。 同时,我们可以捕获标准输出和标准错误,然后打印出来。 如果两个文件相同,diff命令会没有任何输出,并且返回0;如果不同,返回1,并输出差异;如果出错,返回2。 代码示例:</think>以下是用 Python 实现命令转换为 Bash 模式执行并获取结果的完整解决方案: ```python import subprocess def run_diff_command(): # 构建完整的Bash命令字符串 bash_command = ( "bash -c '" "diff <(tail -n +5 new_top.log_tmp) <(tail -n +5 new_top.log_tmp_1); " "exit'" ) try: # 执行命令并捕获输出 result = subprocess.run( bash_command, shell=True, check=True, # 检查命令返回码 text=True, # 以文本模式返回输出 stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # 返回标准输出内容 return result.stdout except subprocess.CalledProcessError as e: # 当diff发现不同时(返回码1),返回差异结果 if e.returncode == 1: return e.stdout # 处理其他错误 error_msg = f"Command failed with exit code {e.returncode}\n" error_msg += f"Error output:\n{e.stderr}" raise RuntimeError(error_msg) # 使用示例 if __name__ == "__main__": try: diff_output = run_diff_command() print("Diff命令输出结果:") print(diff_output if diff_output else "文件内容相同") except Exception as e: print(f"执行出错: {e}") ``` ### 代码解释: 1. **命令构建**: ```python bash_command = "bash -c 'diff <(tail -n +5 new_top.log_tmp) <(tail -n +5 new_top.log_tmp_1); exit'" ``` - 使用 `bash -c` 启动 Bash 解释器 - `<(tail -n +5 ...)` 是 Bash 的进程替换语法 - `exit` 确保 Bash 进程在执行后退出 2. **subprocess.run 参数**: - `shell=True`:允许使用 shell 特性 - `check=True`:非零返回码时抛出异常 - `text=True`:以字符串形式返回输出 - `stdout/stderr=subprocess.PIPE`:捕获输出 3. **错误处理**: - 当 `diff` 发现文件不同时返回码为 1(正常情况),我们捕获其输出 - 其他非零返回码视为错误,抛出异常 4. **执行流程**: - 启动 Bash 进程执行命令 - 比较两个文件的第 5 行之后内容 - 捕获并返回 `diff` 的输出结果 - 无论是否发现差异,Bash 进程都会退出 ### 注意事项: 1. 文件路径 `new_top.log_tmp` 和 `new_top.log_tmp_1` 需要存在 2. 需要执行权限和文件读取权限 3. 如果文件很大,考虑添加内存限制 4. 特殊字符(如 `$`、`!`)在文件名中可能需要转义 ### 输出示例: ``` 3c3 < process_id=1234 cpu_usage=25% --- > process_id=1234 cpu_usage=30% 5d4 < process_id=5678 memory=1.2GB ``` ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值