这是一个运行子进程的简单脚本,它ifconfig从终端的命令输出中检索IP .我注意到subprocess.check_output()总是返回一个值\n.
我渴望得到一个返回值无\n.如何才能做到这一点?
$ python
>>> import subprocess
>>> subprocess.check_output("ifconfig en0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)
'129.194.246.245\n'
Run Code Online (Sandbox Code Playgroud)
Ben*_*min 23
对于通用方式:
subprocess.check_output("echo hello world", shell=True).strip()
Run Code Online (Sandbox Code Playgroud)
subprocess.check_output()并没有添加一个换行符。echo做。您可以使用-nswitch 来取消换行,但您必须避免使用 shell 内置实现(因此请使用/bin/echo):
>>> import subprocess
>>> subprocess.check_output('/bin/echo -n hello world', shell=True)
'hello world'
Run Code Online (Sandbox Code Playgroud)
如果您echo -n改为使用,您可以获得 string '-n hello world\n',因为并非所有sh实现都支持-nswitch 支持echo(例如 OS X)。
当然,您始终可以使用str.rstrip()或str.strip()删除空格,但不要subprocess在这里责怪:
>>> subprocess.check_output('echo hello world', shell=True).rstrip('\n')
'hello world'
Run Code Online (Sandbox Code Playgroud)
您的问题更新使用awk和添加了一个更复杂的示例grep:
subprocess.check_output("ifconfig en0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)
Run Code Online (Sandbox Code Playgroud)
这里grep添加了(最终)换行符。grep -o可能只打印匹配的文本,但仍会添加一个换行符来分隔匹配项。请参阅grep手册:
-o
--only-matching只打印匹配行的匹配(非空)部分,每个这样的部分在一个单独的输出行上。
强调我的。
您可以tr -d '\n'在末尾添加一个以从管道的输出中删除任何换行符:
>>> subprocess.check_output(
... "ifconfig en0 | awk '{ print $2}' | "
... "grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}' | "
... "tr -d '\n'", shell=True)
'172.17.174.160'
Run Code Online (Sandbox Code Playgroud)