[파이썬] subprocess 사용자 정의 `subprocess` 유틸리티 작성하기

개요

Python의 subprocess 모듈은 명령어를 실행하고 외부 프로세스와 통신하기 위한 강력한 도구이다. 그러나 때로는 특정 작업이나 호출 패턴에 맞는 사용자 정의 유틸리티가 필요할 수도 있다. 이 블로그 포스트에서는 subprocess 모듈을 사용하여 사용자 정의 subprocess 유틸리티를 작성하는 방법을 알아보겠다.

모듈 생성

먼저, 새로운 Python 모듈을 생성하고 필요한 import 문을 추가한다.

import subprocess

def run_command(command):
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = process.communicate()
    return process.returncode, output.decode(), error.decode()

사용 예시

이제 작성한 사용자 정의 subprocess 유틸리티를 실제 예제로 사용해보자.

command = ["ls", "-l"]
returncode, output, error = run_command(command)

if returncode == 0:
    print("Command executed successfully:")
    print(output)
else:
    print("Error executing the command:")
    print(error)

run_command 함수는 주어진 명령어를 실행하고 해당 명령어의 리턴 코드, 표준 출력 및 표준 에러를 반환한다. 예를 들어, 위의 예제는 “ls -l”을 실행하고 결과를 출력한다.

결론

이제 사용자 정의 subprocess 유틸리티를 작성하는 방법에 대해 알게 되었다. 이렇게 작성된 유틸리티는 코드를 간결하게 유지하면서 외부 프로세스와의 통신을 효율적으로 처리하는 데 도움이 될 것이다. 맞춤형 유틸리티를 작성하여 프로세스 간 통신을 간단하게 만드세요!