代码之家  ›  专栏  ›  技术社区  ›  Peter

通过外部程序过滤python字符串

  •  1
  • Peter  · 技术社区  · 14 年前

    通过外部程序过滤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"
    

    注意:这个例子只是-我意识到在python中有更好的反转行的方法。

    1 回复  |  直到 14 年前
        1
  •  5
  •   unutbu    14 年前

    使用 subprocess

    对你来说,你可以用

    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 我们通过呼叫 communicate 方法。 返回一个2元组:stdout和stderr的输出。