通过外部程序过滤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", "tac")
# => returns "three\ntwo\none\n"
Run Code Online (Sandbox Code Playgroud)
注意:这个例子只是 - 我意识到在python中有更好的方法来反转行.
使用子进程模块.
在你的情况下,你可以使用类似的东西
import subprocess
proc=subprocess.Popen(['tac','-'], shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, )
output,_=proc.communicate('one\ntwo\nthree\n')
print output
Run Code Online (Sandbox Code Playgroud)
需要注意的是发送的指令是tac -让tac从标准输入期望.我们通过调用communicate方法发送到stdin .communicate返回一个2元组:stdout和stderr的输出.
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |