1

Hi I am trying to run this command in python's subprocess with shlex split, however, I haven't found anything helpful for this particular case :

ifconfig | grep "inet " | grep -v 127.0.0.1 | grep -v 192.* | awk '{print $2}'

I get an with ifconfig error because the split with the single and double quotes and even the white space before the $ sign are not correct. Please Help.

Aboogie
  • 450
  • 2
  • 9
  • 27
  • The `grep` commands are a bit off, `.` is a wildcard, and `*` isn't, and `*` is a shell wildcard, so you want to escape it in the shell. – Dietrich Epp Feb 25 '16 at 06:59

1 Answers1

1

You can use shell=True (shell will interpret |) and triple quote string literal (otherwise you need to escape ", ' inside the string literal):

import subprocess
cmd = r"""ifconfig | grep "inet " | grep -v 127\.0\.0\.1 | grep -v 192\. | awk '{print $2}'"""
subprocess.call(cmd, shell=True)

or you can do it in harder way (Replacing shell pipeline from subprocess module documentation):

from subprocess import Popen, PIPE, call                                       

p1 = Popen(['ifconfig'], stdout=PIPE)
p2 = Popen(['grep', 'inet '], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(['grep', '-v', r'127\.0\.0\.1'], stdin=p2.stdout, stdout=PIPE)
p4 = Popen(['grep', '-v', r'192\.'], stdin=p3.stdout, stdout=PIPE)
call(['awk', '{print $2}'], stdin=p4.stdout)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    1- `.close()` calls are missing in the second code example. 2- It is better to [invert the order if you want to emulate the pipeline by hand (you don't need `.close()` calls in this case)](http://stackoverflow.com/a/9164238/4279). – jfs Feb 25 '16 at 11:02