使用子过程库时如何去掉变量中的\n

How to get rid of \n in the variable when using subproces lib

我是运行一个bash命令通过Python获取stdout。

这是命令的开始

bashCommand = "kubectl --context mlf-eks-dev get --all-namespaces ingressroutes"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)

然后我尝试从输出中删除 \n

output = process.communicate()[0].decode('ascii')

进行打印时,没问题。

wwwvhugo                        wwwvhugo-mlfwordpress                                          134d

然而当我只有 运行 output 时,我仍然看到 \n

wwvhugo                        wwwvhugo-mlfwordpress                                          134d\n'

我尝试使用 strip() 但我不认为它是相关的。

谢谢。

注意:字符串的开头和结尾没有空格。

这应该可以解决问题

bashCommand = "kubectl --context mlf-eks-dev get --all-namespaces ingressroutes"
output = subprocess.check_output(bashCommand.split(), text=True)
output = " ".join(output.splitlines())

然而,经过多次尝试,使用正则表达式也有帮助(如下所示)

import re
output = subprocess.check_output(bashCmdNamespace.split(), text=True)
output = re.sub('\s+',' ',output)