Here is a simple script running subprocess that retrieves IP from the ifconfig
command output from the terminal.
I have noticed that subprocess.check_output()
always returns a value with \n
.
I desire to get a return value without \n
.
How can this be done?
$ 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'
To hide output of subprocess with Python, we can set stdout to subprocess. DEVNULL`. to output the echo command's output to dev null by setting the stdout to subprocess.
To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.
The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.
For a generic way :
subprocess.check_output("echo hello world", shell=True).strip()
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-matchingPrint 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With