stdin 인자를 써서 subprocess.Popen에 문자열을 전달하는 과정에서 에러가 발생합니다.
조회수 6328회
소스코드
import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]
에러내용
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
(p2cread, p2cwrite,
File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'
subprocess.Popen
에서 stdin=StringIO...
이 부분 때문에 에러가 나는 것 같은데 어떻게 해야 될까요?
1 답변
-
Popen.communicate()를 간략하게 요약하면
프로세스의 stdin으로 데이터를 전송하려면 stdin=PIPE를 써서 Popen 객체를 생성해야 합니다. 이때 데드록을 방지하려면 stdin.write() 보다는 communicate()를 쓰는 게 좋습니다.
pipe = os.popen(cmd, 'w', bufsize) #를 밑처럼 바꾸세요 pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
그러니까 질문하신 분의 코드는 이렇게 바뀌면 되겠네요
from subprocess import Popen, PIPE, STDOUT p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0] print(grep_stdout.decode()) # -> four # -> five # ->
댓글 입력