TIL

[Python] os.system VS subprocess

oraange 2022. 6. 3. 08:33

os.system

os.system 메소드는 UNIX Command와 다를 게 없다. 그리고 프로세스를 따로 생성하지 않고 현재 프로세스가 해당 명령을 실행한 뒤 결과를 받아온다.

>>> def ossys():
>>>     os.system("sleep 5")
>>>     print("hello")

>>> ossys()
hello # 5초가 지난 뒤 hello 출력

subprocess

subprocess.Popen 메소드는 커맨드를 실행할 수 있게 도와준다는 느낌이 더 크다. concurrent.futures 모듈이 Threading 모듈을 감싼 고수준 API인 것처럼 subprocess도 마찬가지이다. 또한, 자식 프로세스를 생성하여 실행하는 것이기 때문에 흐름에 영향을 받지 않는다.

>>> def subprc():
>>>     subprocess.Popen("sleep 5")
>>>     print("hello")

>>> subprc()
hello # 함수 호출과 동시에 출력된다. subprocess.Popen은 다른 프로세스가 처리하기 때문에 5초 동안 잠드는 것을 기다릴 필요가 없다.

참고로 subprocess.call 함수는 명령이 끝날 때까지 기다려 준다. 그치만 os.system과 다른 점은 os.system은 shell을 사용하여 명령어를 실행하고, subprocess.call은 그렇지 않다. 그러나 subprocess.call([...], shell=True) 와 같이 shell=True 옵션을 적어주면 os.system과 비슷한 역할을 하게 된다.

반응형