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.

1
  • 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. Feb 25, 2016 at 6:59

1 Answer 1

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)
1

Not the answer you're looking for? Browse other questions tagged or ask your own question.