개요
2023.02.08 - [Python] 시스템 명령어 실행에서 정리하지 않았던 subprocess.Popen 객체에 대해 추가적으로 정리한다.
Popen 객체
이전 글에서 살펴봤던 subprocess.run은 내부적으로 Popen 객체를 통해 동작한다. subprocess.run은 명령어 실행 후 종료할 때까지 대기하지만 Popen은 백그라운드 프로세스로 실행하며 세밀하게 시스템 명령을 사용할 수 있다.
class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True,
shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None,
umask=-1, encoding=None, errors=None, text=None, pipesize=-1, process_group=None)
# args : 실행할 명령어를 공백으로 나눈 문자열 리스트
# executable : 실행 프로그램 지정. shell=True 시 기본적으로 /bin/sh로 실행한다.
# stdin, stdout, stderr : 표준 입력, 출력, 에러 설정
# shell : shell 실행 여부
# text : True 지정 시 결과값을 string으로 출력
사용 예시
1. 명령어를 공백으로 나눠 실행
stdin, stdout, stderr를 PIPE로 지정하면 subporcess를 실행시키는 프로그램의 표준 입출력으로 연결한다. shell이 True인 경우 실행하는 명령인 cmd는 하나의 문자열로 전달할 수 있다.
ps = subprocess.Popen(
shlex.split(cmd),
stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE,
text=True)
2. /bin/bash 쉘을 이용해 process 실행
shell이 True인 경우 실행하는 명령인 cmd는 하나의 문자열로 전달할 수 있다. 또한 자식 프로세스를 추가로 생성하여 실행한다.
실행 결과는 communicate 함수를 통해 전달받을 수 있다.
ps = subprocess.Popen(
cmd,
stdin=subprocess.PIPE, stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
shell=True, executable="/bin/bash",
text=True
)
out, err = ps.communicate()
ps.terminate()
만약 text=True 지정이 없다면 결과가 byte형 데이터로 반환된다.
참고 문서