Domanda

Vorrei replicare questo in python:

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

(hg gatto file.txt uscite più recentemente impegnati versione di file.txt)

So come pipe il file gvimdiff, ma non accetterà un altro file:

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

Raggiungere il python parte...

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

Quando sottoprocesso è chiamato semplicemente passa <(hg cat file) su gvimdiff come un nome di file.

Quindi, c'è un modo per reindirizzare un comando bash?Per semplicità solo gatto un file e reindirizzare a diff:

diff <(cat file.txt) file.txt
È stato utile?

Soluzione

Esso può essere fatto.Come di Python 2.5, tuttavia, questo meccanismo è specifico di Linux e non portatile:

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()

Detto questo, nel caso specifico di diff, si può semplicemente prendere uno dei file da stdin, e rimuovere la necessità di usare la bash-alike funzionalità in questione:

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]

Altri suggerimenti

C'è anche il modulo comandi:

import commands

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

C'è anche la popen insieme di funzioni, se si desidera effettivamente grok i dati da un comando è in esecuzione.

Questo è un esempio in docs:

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

che significa per voi:

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]

Questo rimuove l'uso di linux-specifiche /proc/self/fd bit, rendendo probabilmente funziona su altri sistemi unix come Solaris e Bsd (tra cui MacOS) e forse anche il lavoro su Windows.

Appena mi resi conto che probabilmente stai cercando una delle popen funzioni.

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

popen3(cmd[, bufsize[, mode]]) Esegue cmd come un sotto-processo.Restituisce il file di oggetti (child_stdout, child_stdin, child_stderr).

namaste, Mark

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top