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

2024-10-01 13:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中复制:

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

(hg类别文件.txt输出最近提交的版本文件.txt)

我知道如何通过管道将文件发送到gvimdiff,但它不会接受另一个文件:

^{pr2}$

进入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

Tags: 文件import版本txt管道sysdiffhg
3条回答

还有命令模块:

import commands

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

还有一组popen函数,如果您想在命令运行时从命令中获取数据。在

这实际上是docs中的一个示例:

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

对你来说意味着:

^{pr2}$

这就消除了linux特有的/proc/self/fd位的使用,使得它可以在其他unice上工作,比如Solaris和bsd(包括MacOS),甚至可以在Windows上运行。在

这是可以做到的。但是,对于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的功能了:

^{pr2}$

相关问题 更多 >