如何从TXT文件读取Shell命令并将执行结果存入TXT文件
问题描述
我需要实现两个操作:
- 从TXT文件中读取Shell命令
- 将这些命令的执行结果存入另一个TXT文件
我已经写好了读取文件的Python函数read_file,可以把文件里的命令转成字符串列表,也写了写入文件的函数框架write_file,但不知道怎么执行存在data里的命令并存储执行结果,要求只能用Python内置库。
输入文件内容示例:
func1 val1 val2 val3 func3 valx valy valz func2 val ...
现有代码如下:
读取文件的代码:
import os def read_file(file_name): #file_name must be a string current_dir_path = os.getcwd() #getting current directory path reading_file_name = file_name reading_file_path = os.path.join(current_dir_path, reading_file_name) #file path to read # Open file with open(reading_file_path, "r") as f: #"r" for reading data = f.readlines() for i in range(len(data)): data[i] = data[i].replace("\n", "") return data
写入文件的代码框架:
outputs = "?" def write_file(file_name): #file_name must be a string current_dir_path = os.getcwd() writing_file_name = file_name writing_file_path = os.path.join(current_dir_path, writing_file_name) # Open file and add with open(writing_file_path, "w") as f: f.write(outputs)
解决方案
要执行Shell命令并捕获结果,推荐使用Python内置的subprocess库,它比os.system更灵活,能直接获取命令的输出、错误信息和返回码。以下是修改后的完整可运行代码:
import os import subprocess def read_file(file_name): current_dir_path = os.getcwd() reading_file_path = os.path.join(current_dir_path, file_name) with open(reading_file_path, "r") as f: # 读取每行并去除换行符,同时过滤空行 data = [line.strip() for line in f if line.strip()] return data def execute_commands(commands): results = [] for cmd in commands: try: # 执行命令,捕获标准输出、标准错误,返回字符串格式结果 result = subprocess.run( cmd, shell=True, capture_output=True, text=True, check=False # 命令执行失败时不抛出异常,保留错误信息 ) # 整理成易读的结果格式 output_block = f"=== 执行命令: {cmd} ===\n" output_block += f"返回码: {result.returncode}\n" output_block += f"标准输出:\n{result.stdout}\n" output_block += f"标准错误:\n{result.stderr}\n\n" results.append(output_block) except Exception as e: results.append(f"=== 执行命令: {cmd} 出错 ===\n错误信息: {str(e)}\n\n") return "".join(results) def write_file(file_name, content): current_dir_path = os.getcwd() writing_file_path = os.path.join(current_dir_path, file_name) with open(writing_file_path, "w", encoding="utf-8") as f: f.write(content) # 主执行流程 if __name__ == "__main__": # 替换为你的命令文件名 commands = read_file("commands.txt") outputs = execute_commands(commands) # 替换为你要保存结果的文件名 write_file("command_results.txt", outputs)
关键修改说明
- 新增
subprocess依赖:这是Python官方推荐的执行外部命令的内置库,功能覆盖os.system且更强大。 - 优化
read_file:用列表推导式简化换行符处理,同时过滤空行,避免执行无效的空命令。 - 新增
execute_commands函数:专门处理命令执行逻辑,为每个命令保留完整的执行信息(命令内容、返回码、输出、错误),方便后续排查问题。 - 改进
write_file:添加content参数接收执行结果,同时指定utf-8编码,避免中文输出乱码。 - 主流程串联:通过
if __name__ == "__main__"实现脚本直接运行,只需替换对应的文件名即可使用。
内容的提问来源于stack exchange,提问作者Diotima
相关产品推荐
相关产品推荐

