<p><code>subprocess.check_output()</code>不添加新行。<code>echo</code>是的。可以使用<code>-n</code>开关来抑制换行符,但必须避免使用shell内置实现(因此使用<code>/bin/echo</code>):</p>
<pre><code>>>> import subprocess
>>> subprocess.check_output('/bin/echo -n hello world', shell=True)
'hello world'
</code></pre>
<p>如果改用<code>echo -n</code>,则可以得到字符串<code>'-n hello world\n'</code>,因为并非所有的<code>sh</code>实现都支持<code>-n</code>开关支持<code>echo</code>(例如OS X)。</p>
<p>当然,您可以始终使用<a href="https://docs.python.org/2/library/stdtypes.html#str.rstrip" rel="nofollow noreferrer">^{<cd10>}</a>或<a href="https://docs.python.org/2/library/stdtypes.html#str.strip" rel="nofollow noreferrer">^{<cd11>}</a>来删除空白,但不要责怪这里的<code>subprocess</code>:</p>
<pre><code>>>> subprocess.check_output('echo hello world', shell=True).rstrip('\n')
'hello world'
</code></pre>
<p>您的问题更新使用<code>awk</code>和<code>grep</code>添加了一个更复杂的示例:</p>
<pre><code>subprocess.check_output("ifconfig en0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)
</code></pre>
<p>此处<em>grep</em>添加(最终)换行符。<code>grep -o</code>可能只打印匹配文本,但仍会添加新行来分隔匹配。请参阅<a href="http://www.gnu.org/software/grep/manual/grep.html#General-Output-Control" rel="nofollow noreferrer">^{<cd14>} manual</a>:</p>
<blockquote>
<p>-o<br/>
--only-matching </p>
<p>Print only the matched (non-empty) parts of matching lines, <strong>with each such part on a separate output line.</strong></p>
</blockquote>
<p>强调我的。</p>
<p>您可以在末尾添加<a href="https://unix.stackexchange.com/questions/3297/remove-end-of-line-characters-from-stdout-multiple-lines-into-a-single-line">^{<cd17>}</a>以从管道输出中删除任何新行:</p>
<pre><code>>>> 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'
</code></pre>