如何在Python中通过os.system()获取grep命令的输出结果?
如何将Linux命令的输出赋值给Python变量
你用os.system()得到的0是命令的退出状态码,0代表命令执行成功,并不是grep命令的实际输出内容。要把命令的输出赋值给变量,推荐使用Python的subprocess模块,这是官方推荐替代os.system的方案,功能更完善。
方法1:使用subprocess.run(推荐,可控性强)
这种方式可以同时捕获输出和错误信息,还能处理命令执行失败的情况:
import subprocess # 用列表形式传参,避免命令注入风险 cmd_args = ["grep", "-n", "str", "file.txt"] # capture_output=True 捕获输出,text=True 让输出为字符串而非字节流 result = subprocess.run(cmd_args, capture_output=True, text=True) # 提取命令输出(去除首尾空白字符) command_output = result.stdout.strip() print(command_output) # 输出:1:str # 若需要检查命令执行状态 if result.returncode == 0: print("命令执行成功") else: print(f"命令执行失败,错误信息:{result.stderr.strip()}")
如果希望命令执行失败时直接抛出异常,可以添加check=True参数:
import subprocess cmd_args = ["grep", "-n", "str", "file.txt"] try: result = subprocess.run(cmd_args, capture_output=True, text=True, check=True) command_output = result.stdout.strip() print(command_output) except subprocess.CalledProcessError as e: print(f"命令执行出错:{e.stderr.strip()}")
方法2:使用subprocess.check_output(简化版)
如果只需要获取命令成功时的输出,可以用这个更简洁的方法:
import subprocess cmd_args = ["grep", "-n", "str", "file.txt"] try: command_output = subprocess.check_output(cmd_args, text=True).strip() print(command_output) except subprocess.CalledProcessError: print("未找到匹配内容或命令执行失败")
注意:尽量使用列表形式传递命令参数,不要直接拼接字符串,这能避免潜在的命令注入安全问题。
内容的提问来源于stack exchange,提问作者spookyss
相关产品推荐
相关产品推荐

