subprocess 모듈은 파이썬에서 새로운 프로세스를 만들고 인풋, 아웃풋, 에러 파이프를 연결 시켜준다.
pexpect 모듈을 사용해서도 쉘과 상호작용할 수 있습니다.
# subprocess 모듈 사용
import subprocess
subprocess.call(['ls', '-l']) # 명령어 실행
subprocess.check_call(['ls', '-l']) # 명령어 실행 확인
subprocess.check_output(['ls', '-l']) # 아웃풋 string 으로 출력
# pexpect 모듈 사용
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
# ftp 실행 시 Name (ftp.openbsd.org:carpedm20): 로 입력 받음 -> 정규표현식 Name.* 사용
# 단순하게 child.expect(".*") 로도 사용 가능
child.expect ('Name .*: ')
# 인풋값 입력
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')
print child.before # 이전 명령어 실행으로 나온 아웃풋 출력
try:child.interact() # 유저에게 컨트롤을 넘겨줌
except:pass
댓글 없음:
댓글 쓰기