[英]Filtering python string through external program
What's the cleanest way of filtering a Python string through an external program? 通过外部程序过滤Python字符串的最干净方法是什么? 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. 注意:仅是示例-我意识到在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. 请注意,发送的命令是
tac -
因此tac
期望来自stdin的输入。 We send to stdin by calling the communicate
method. 我们通过调用
communicate
方法发送到stdin。 communicate
returns a 2-tuple: the output from stdout, and stderr. communicate
返回一个2元组:stdout和stderr的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.