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

将命令重定向到另一个python中的输入

  •  7
  • alif  · 技术社区  · 17 年前

    我想在python中复制这个:

    gvimdiff <(hg cat file.txt) file.txt
    

    (hg cat file.txt输出最近提交的file.txt版本)

    我知道如何将文件传输到gvimdiff,但它不会接受另一个文件:

    $ hg cat file.txt | gvimdiff file.txt -
    Too many edit arguments: "-"
    

    进入python部分…

    # hgdiff.py
    import subprocess
    import sys
    file = sys.argv[1]
    subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])
    

    当调用子进程时,它只通过 <(hg cat file) 到上面 gvimdiff 作为文件名。

    那么,有没有办法像bash那样重定向命令呢? 为了简单起见,只需对文件进行分类并将其重定向到diff:

    diff <(cat file.txt) file.txt
    
    4 回复  |  直到 11 年前
        1
  •  9
  •   Charles Duffy    17 年前

    这是可以做到的。但是,从python 2.5开始,此机制是特定于Linux的,不可移植:

    import subprocess
    import sys
    
    file = sys.argv[1]
    p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
    p2 = subprocess.Popen([
        'gvimdiff',
        '/proc/self/fd/%s' % p1.stdout.fileno(),
        file])
    p2.wait()
    

    也就是说,在diff的特定情况下,您可以简单地从stdin中获取一个文件,并消除使用相关bash类似功能的需要:

    file = sys.argv[1]
    p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout)
    diff_text = p2.communicate()[0]
    
        2
  •  2
  •   Mark Hattarki    14 年前

    还有命令模块:

    import commands
    
    status, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt")
    

    还有一组popen函数,如果您想在命令运行时从命令中搜索数据的话。

        3
  •  2
  •   twasbrillig    11 年前

    这实际上是 docs :

    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    output = p2.communicate()[0]
    

    这对你来说意味着:

    import subprocess
    import sys
    
    file = sys.argv[1]
    p1 = Popen(["hg", "cat", file], stdout=PIPE)
    p2 = Popen(["gvimdiff", "file.txt"], stdin=p1.stdout, stdout=PIPE)
    output = p2.communicate()[0]
    

    这就消除了Linux特定的/proc/self/fd位的使用,使得它可能在其他Unice上工作,如Solaris和BSD(包括MacOS),甚至可能在Windows上工作。

        4
  •  -1
  •   Mark Hattarki    17 年前

    我刚意识到你可能正在寻找一个popen函数。

    来自: http://docs.python.org/lib/module-popen2.html

    popen3(命令[,bufsize[,模式]]) 将cmd作为子进程执行。返回文件对象(child_stdout、child_stdin、child_stderr)。

    纳马斯特 作记号

    推荐文章