본문 바로가기
Computer & Program/python

[python] Shell script 실행

by TDRemon 2024. 3. 20.
반응형

안녕하세요. TDR입니다.

오늘은 python에서 shell scipt를 실행시킬 수 있는 3가지 방법을 간략히 알아보겠습니다. 참고로 해당 환경은 linux입니다.

1. os.system

import os

os.system('ls -al')

위와 같이 명령어를 실행하면 해당 명령어가 즉시 실행 됩니다. blocking 명령으로 해당 작업이 모두 끝날 때 까지 다음 명령어는 실행 되지 않습니다.

2. os.popen()

import os

stream = os.popen('ls -al')
for line in stream:
  print(line)

os.system과 달리 명령 결과를 stream 형태로 받을 수 있어 원하는 후처리가 가능하다는 장점이 있습니다. os.popen도 blocking 명령어 입니다.

3. subprocess()

res = subprocess.run(['ls', '-al'], stdout=subprocess.PIPE, text=True)
for i in res.stdout.splitlines():
  print(i)

마지막으로 가장 추천하는 subprocess입니다. run() 외에도 call(), Popen()과 같은 메소드도 있지만 python 3.5 이후부터 생긴 run()을 사용하기를 추천드립니다. (사실상 run()이 기존 메소드들의 상위 호환)

위에서는 간단히 명령 결과를 변수에 저장해서 한줄씩 출력하는 예제인데, run()에는 다양한 파라미터들이 존재합니다. 자세한 건 하기 공식 문서를 참고하시면 됩니다.

 

subprocess — Subprocess management

Source code: Lib/subprocess.py The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace seve...

docs.python.org

 

반응형

'Computer & Program > python' 카테고리의 다른 글

[python] for & while & print  (0) 2024.03.16
[python] String(문자열) 포함 여부 확인  (0) 2024.03.14
[python] Python 특징  (0) 2024.03.12
[python] Package & Module  (0) 2024.03.10
[python] Format(f-string)  (0) 2024.03.07

댓글