如何在Linux系统的VS Code中使用Python提取终端输出的指定列并保存到文本文件
如何在Linux系统的VS Code中使用Python提取终端输出的指定列并保存到文本文件
嗨,我来帮你搞定这个问题!你想要提取终端输出里的第二列数字并存到文本文件,其实用Python可以轻松实现,我给你分两种常见场景来讲解:
场景1:直接在Python脚本中捕获命令输出并处理
如果你的那些终端输出是由某个命令/脚本产生的,你可以用Python的subprocess模块直接捕获这个命令的输出,然后逐行提取第二列:
import subprocess # 把下面的命令替换成实际产生终端输出的那个命令 # 比如如果是运行另一个Python脚本,就写成 "python your_source_script.py" target_cmd = "your-actual-command" # 执行命令并捕获输出内容 cmd_output = subprocess.run(target_cmd, shell=True, capture_output=True, text=True) # 打开文件准备写入提取的内容 with open("second_column_result.txt", "w") as result_file: # 逐行处理输出 for line in cmd_output.stdout.splitlines(): cleaned_line = line.strip() if not cleaned_line: # 跳过空行,避免报错 continue # 按空格分割每行的内容 columns = cleaned_line.split() # 确保该行至少有2列内容,再提取第二列(Python是0索引,所以用[1]) if len(columns) >= 2: result_file.write(f"{columns[1]}\n")
运行这个脚本后,second_column_result.txt里就会只有你想要的第二列数字啦。
场景2:从已保存的全量输出文件中提取
如果你已经把终端的全部输出保存到了一个文件(比如之前用your-command > full_output.txt保存的),那可以直接读取这个文件来提取:
# 打开输入文件(全量输出)和输出文件(保存第二列) with open("full_output.txt", "r") as input_file, open("second_column_result.txt", "w") as output_file: for line in input_file: cleaned_line = line.strip() if not cleaned_line: continue columns = cleaned_line.split() if len(columns) >= 2: output_file.write(f"{columns[1]}\n")
额外小技巧(Linux命令行快速实现)
其实在Linux下,不用Python也能快速搞定,用awk命令一行就够:
比如直接捕获命令的第二列并保存:
your-actual-command | awk '{print $2}' > second_column_result.txt
如果是从已有的全量输出文件提取:awk '{print $2}' full_output.txt > second_column_result.txt
这个方法更简洁,不过既然你在学Python,前面的Python方案更贴合你的学习需求~
备注:内容来源于stack exchange,提问作者HUH987
相关产品推荐
相关产品推荐

