通过外部程序过滤python字符串
通过外部程序过滤Python字符串最干净的方法是什么?特别是,如何编写以下函数通过外部程序过滤python字符串,python,Python,通过外部程序过滤Python字符串最干净的方法是什么?特别是,如何编写以下函数 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"
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"
注意:这个例子只是-我意识到在python中有更好的反转行的方法。使用这个模块
在你的情况下,你可以使用
import subprocess
proc=subprocess.Popen(['tac','-'], shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, )
output,_=proc.communicate('one\ntwo\nthree\n')
print output
请注意,发送的命令是tac-
,因此tac
需要来自stdin的输入。
我们通过调用communicate
方法发送到stdincommunicate
返回一个2元组:stdout和stderr的输出 使用该模块
在你的情况下,你可以使用
import subprocess
proc=subprocess.Popen(['tac','-'], shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, )
output,_=proc.communicate('one\ntwo\nthree\n')
print output
请注意,发送的命令是tac-
,因此tac
需要来自stdin的输入。
我们通过调用communicate
方法发送到stdincommunicate
返回一个2元组:stdout和stderr的输出