pythonpipestdoutmail-queue

Execute shell command with pipes in Python


I'm new to Python, tried googling, but no help..
I need to call such commands in pipes (Get the oldest pending mail from mailq):

mailq |grep "^[A-F0-9]" |sort -k5n -k6n |head -n 1

The command works in shell.

In Python I wrote the following:

 p = subprocess.Popen( 'mailq |grep \"^[A-F0-9]\" |sort -k5n -k6n |head -n 1', shell=True,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
 response = p.communicate()[0]

But I get such output:

sort: write failed: standard output: Broken pipe\nsort: write error\n

Wondering what is causing such error?


Solution

  • I think this should work:

    p = subprocess.Popen( 'mailq |grep \"^[A-F0-9]\" |sort -k5n -k6n |head -n 1', shell=True,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    response = p.stdout.readlines(-1)[0]
    print response
    

    prints the first line of the response