1

Having read other answers on here, I know that shell=True is frowned upon, but I am having trouble with a command (more accurately a pair of commands?) with a pipe redirect.

This works:

subprocess.call('echo "Test" | mail -s "Test" test@gmail.com', shell=True) 

but this does not:

subprocess.call(["echo", "Test", "|", "mail", "-s", "'Test'", test@gmail.com"]))

Any suggestions on how to make the second one work?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
jnm21
  • 13
  • 2

1 Answers1

2

You can do something like below to get a piped output like this:

echo "Test" | mail -s "Test" test@gmail.com'

Basically, create multiple subprocess.Popen objects, specify one's stdout as a PIPE, and feed this as an stdin to the other object:

p1 = Popen(["echo", "Test"], stdout=PIPE)
p2 = Popen(["mail", "-s", "Test", "test@gmail.com"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

You can check this for more info.

Community
  • 1
  • 1
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186