Python调用Shell命令后为每行添加分隔符的问题
问题:为Shell命令输出的每行添加分隔符失败
我用Python调用Shell的find命令,想给命令返回的每一行后面加上分隔符,但写的两段代码都达不到预期效果。
预期输出
/usr/sbin/mount.nfs ----- /usr/sbin/mount.cifs ----- /usr/sbin/pppd ----
代码A的问题
实际输出
/usr/sbin/mount.nfs /usr/sbin/mount.cifs /usr/sbin/pppd ----
代码A
separador = "----------------" shell = ['find', '/', "-perm", "-u=s", "-type", 'f'] output = subprocess.run((shell),capture_output= True, universal_newlines=True, text=True) command_output=(output.stdout+"\n"+separador) print(command_output)
问题原因:这段代码只是把分隔符直接追加到整个输出的末尾,没有给每一行单独添加分隔符。
代码B的问题
实际输出
---------------- e ---------------- l ---------------- p ---------------- e ---------------- r ----------------
代码B
separador = "----------------" shell = ['find', '/', "-perm", "-u=s", "-type", 'f'] output = subprocess.run((shell),capture_output= True, universal_newlines=True, text=True) command_output=(output.stdout) for i in command_output: print(i) print(separador)
问题原因:这里遍历的是输出字符串的每个字符,而不是每一行,导致每个字符后面都被加上了分隔符,完全不符合需求。
正确实现方式
需要将输出按行分割,对每一行(有效非空行)单独添加分隔符,再重新拼接输出。
方法一:过滤空行后处理
separador = "-----" shell = ['find', '/', "-perm", "-u=s", "-type", 'f'] output = subprocess.run(shell, capture_output=True, text=True) # 分割成每行并过滤空行 lines = [line for line in output.stdout.splitlines() if line.strip()] # 拼接每行和分隔符 result = '\n'.join(f"{line}\n{separador}" for line in lines) print(result)
方法二:保留原格式(含空行)
如果需要保留命令输出中的空行,可使用以下代码:
separador = "-----" shell = ['find', '/', "-perm", "-u=s", "-type", 'f'] output = subprocess.run(shell, capture_output=True, text=True) # 按行分割并保留换行符 lines = output.stdout.splitlines(keepends=True) result = "" for line in lines: result += line # 仅对非空行添加分隔符 if line.strip(): result += separador + "\n" print(result)
说明:通过splitlines()将输出拆分为行列表,遍历过程中为每个有效行添加分隔符,最终输出符合预期的格式。
内容的提问来源于stack exchange,提问作者Jose
相关产品推荐
相关产品推荐

