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
해결책
그것은 할 수 있습니다.그러나 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]
다른 팁
명령 모듈도 있습니다:
import commands
status, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt")
명령이 실행되는 동안 실제로 데이터를 수집하려는 경우 popen 함수 세트도 있습니다.
이것은 실제로 문서:
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 비트의 사용이 제거되어 Solaris 및 BSD(MacOS 포함)와 같은 다른 유니스에서도 작동하고 Windows에서도 작동할 수도 있습니다.
당신이 아마도 popen 기능 중 하나를 찾고 있다는 생각이 들었습니다.
에서: http://docs.python.org/lib/module-popen2.html
POPEN3 (cmd [, bufsize [, mode]])는 cmd를 하위 프로세스로 실행합니다.파일 객체(child_stdout, child_stdin, child_stderr)를 반환합니다.
Namaste, Mark