Search code examples
pythoncommandsubprocess

How to split up the command here for using subprocess.Popen()


ip = subprocess.Popen(["/sbin/ifconfig $(/sbin/route | awk '/default/ {print $8}') | grep \"inet addr\" | awk -F: '{print $2}' | awk \'{print $1}\'"], stdout=subprocess.PIPE)

I am not sure where to put the commas to separate them to use this command using subprocess.Popen. Does anyone know?


Solution

  • Here's what I would recommend.

    Create a file with this contents - call it 'route-info' and make it executable:

    #!/bin/sh
    
    /sbin/ifconfig $(/sbin/route | awk '/default/ {print $8}') |
        grep "inet addr" |
        awk -F: '{print $2}' |
        awk '{print $1}'
    

    In your python program, use:

    ip = subprocess.Popen(["/path/to/route-info"], stdout=subprocess.PIPE)
    

    Then you don't have to worry about quoting characters and you can independently test the route-info script to make sure it is working correctly.

    The script route-info doesn't take any command line arguments, but if it did this is how you would pass them:

    ip = subprocess.Popen(["/path/to/route-info", arg1, arg2, ...], stdout=subprocess.PIPE)