简体   繁体   English

使用子进程库时如何摆脱变量中的\n

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

I'm running a bash command through Python to get the stdout.我正在通过 Python 运行 bash 命令以获取标准输出。

This is the start of the command这是命令的开始

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

I then try to remove the \n from the output然后我尝试从 output 中删除\n

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

When doing a print, no issue.打印时,没有问题。

wwwvhugo                        wwwvhugo-mlfwordpress                                          134d

Yet when I'm only running output , I still see the \n然而,当我只运行output时,我仍然看到\n

wwvhugo                        wwwvhugo-mlfwordpress                                          134d\n'

I tried to use the strip() but I do not think it is related.我尝试使用strip()但我不认为它是相关的。

Thank you.谢谢你。

Note : There are no whitespaces at the start or at the end of the string.注意:字符串的开头或结尾没有空格。

This should do the trick这应该可以解决问题

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

However, after many tryout, using a regex can help too (like below)然而,经过多次尝试,使用正则表达式也有帮助(如下所示)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM