开发者

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 "thr开发者_JS百科ee\ntwo\none\n"

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜