Search code examples
pythonsubprocessecho

How to call python 'subprocess' with pipe operator and with multiple parameters


I am using Python and wants to run the "editUtility" as shown below.

echo "Some data" | /opt/editUtility --append="configuration" --user=userid 1483485

Where 1483485 is some random number and passed as parameter too.

What I am doing is calling the "editUtility" via Python "subprocess" and passing the param as shown below.

proc = subprocess.Popen(['/opt/editUtility', '--append=configuration'],stdout=subprocess.PIPE)
            lsOutput=""
            while True:
              line = proc.stdout.readline()
              lsOutput += line.decode()
              if not line:
                break
            print(lsOutput)

My question is: How to pass all of the params mentioned above and how to fit the 'echo "some data"' along with pipe sign with subprocess invocation?


Solution

  • so if you just want to input a string and then read the output of the process until the end Popen.communicate can be used:

    cmd = [
        '/opt/editUtility',
        '--append=configuration',
        '--user=userid',
        '1483485'
    ]
    
    proc = subprocess.Popen(
        cmd,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    
    (stdoutData, stderrData) = proc.communicate('Some data')