subprocess.check_output() does not add a newline. echo does. You can use the -n switch to suppress the newline, but you have to avoid using the shell built-in implementation (so use /bin/echo):
>>> import subprocess
>>> subprocess.check_output('/bin/echo -n hello world', shell=True)
'hello world'
If you use echo -n instead, you could get the string '-n hello world\n', as not all sh implementations support the -n switch support echo (OS X for example).
You could always use str.rstrip() or str.strip() to remove whitespace, of course, but don't blame subprocess here:
>>> subprocess.check_output('echo hello world', shell=True).rstrip('\n')
'hello world'
Your question update added a more complex example using awk and grep:
subprocess.check_output("ifconfig en0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)
Here grep adds the (final) newline. grep -o may print just the matching text, but still adds a newline to separate matches. See the grep manual:
-o
--only-matching
Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line.
Emphasis mine.
You can add a tr -d '\n' at the end to remove any newlines from the output of your pipe:
>>> 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'
echoadds that newline.. - Martijn Pieters♦subprocess.check_output("ifconfig en0 | awk '{ print $2}' | grep -E -o '([0-9]{1,3}[\.]){3}[0-9]{1,3}'", shell=True)which retrieves my ip address on bash mac OS X, the return line is also present - Jupiterechowith yourifconfig | awk | grep -ocommand, invalidating a lot of the answers. Not that your assertion is any more true because of it. - Martijn Pieters♦execexplicitly (and incorrectly IMHO) removes trailing newlines from the returned output. - Antti Haapala