Linux中subprocess.check_output执行命令遇127错误及换行符问题求助
解决subprocess返回127错误(命令含换行符问题)
问题根源:readlines()读取文件时,每一行末尾会保留换行符\n。当你把x直接拼接到命令字符串中时,换行符会被带入命令,导致命令被拆分成多行,系统无法正确识别完整的命令,甚至把带换行的整段字符串当成命令名,最终触发FileNotFoundError(错误码127对应命令未找到)。
修复步骤
1. 去除每行的换行符和多余空白
在使用x拼接命令前,用strip()或rstrip('\n')清理换行符和前后空白字符:
import subprocess with open("file.txt", 'r') as fl: xs = fl.readlines() for x in xs: # 去除换行符和前后空白 cleaned_x = x.strip() # 跳过空行(如果文件里存在) if not cleaned_x: continue output = subprocess.check_output(f"command -L {cleaned_x} -N", shell=True, stderr=subprocess.STDOUT) print(output)
2. 更安全的调用方式:避免使用shell=True
shell=True存在命令注入风险,且容易因字符串格式问题出错。推荐将命令拆分为列表形式传递,此时subprocess会自动处理参数,无需担心换行符或特殊字符:
import subprocess with open("file.txt", 'r') as fl: xs = fl.readlines() for x in xs: cleaned_x = x.strip() if not cleaned_x: continue # 命令拆分为列表,每个元素对应一个参数 output = subprocess.check_output(["command", "-L", cleaned_x, "-N"], stderr=subprocess.STDOUT) print(output.decode('utf-8')) # 把字节流转成字符串,打印更友好
3. 验证处理后的参数
如果不确定是否清理干净,可以先打印cleaned_x的原始表示,确认没有换行符:
print(repr(cleaned_x)) # repr会显示转义字符,若仍有\n会直接显示出来
内容的提问来源于stack exchange,提问作者Jugert Mucoimaj
相关产品推荐
相关产品推荐

