Peter
Peter

Reputation: 132337

Filtering python string through external program

What's the cleanest way of filtering a Python string through an external program? In particular, how do you write the following function?

def filter_through(s, ext_cmd):
  # Filters string s through ext_cmd, and returns the result.

# Example usage:
#   filter a multiline string through tac to reverse the order.
filter_through("one\ntwo\nthree\n", "tac")
#   => returns "three\ntwo\none\n"

Note: the example is only that - I realize there are much better ways of reversing lines in python.

Upvotes: 1

Views: 240

Answers (1)

unutbu
unutbu

Reputation: 880537

Use the subprocess module.

In your case, you could use something like

import subprocess
proc=subprocess.Popen(['tac','-'], shell=True, stdin=subprocess.PIPE,
                      stdout=subprocess.PIPE, )
output,_=proc.communicate('one\ntwo\nthree\n')
print output

Note that the command sent is tac - so that tac expects input from stdin. We send to stdin by calling the communicate method. communicate returns a 2-tuple: the output from stdout, and stderr.

Upvotes: 5

Related Questions