본문 바로가기

카테고리 없음

[python] subprocess 사용하기

프로세스내에서 cmd 통해서 명령어를 실행하고 그에 대한 결과를 확인해야 할때 subprocess 활용하면 쉽게 해결을 있다. 

나의 경우에는 ffmpeg 라이브러리가 아닌 시스템의 ffmpeg 활용하여 wav파일로 변환하거나, 영상파일 자르기,  파일 사이즈를 활용하는 방법 다양하게 사용한것같다. 

 

import subprocess

def subprocess_func(cmd):
    status = False
    result = ''
    try : 
        result = subprocess.run(cmd, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
        status = True
    except subprocess.CalledProcessError as e:
        # 명령이 실패하면 표준 에러 로깅
        self.logger.error(f"Command: {cmd}")
        self.logger.error(f"STDOUT:\n{e.stdout}")
        self.logger.error(f"STDERR:\n{e.stderr}")
    except Exception as e:
        self.logger.error(f"[threadRequestProcess] {e}\n{traceback.format_exc()}")
    return status, result
    
    status, result = subprocess_func('pwd')
    
    print(f'result : {result}')

 

CompletedProcess(args='pwd', returncode=0, stdout='/root/test\n', stderr='')

결과는 아래와 같이 나온다.