[Python] python에서 os 명령어 실행 결과 불러오기-os.popen과 os.system - macOS

ludvico el's avatar
Feb 07, 2024
[Python] python에서 os 명령어 실행 결과 불러오기-os.popen과 os.system - macOS
작성일: 20240207 최근 수정일: 20240207
OS: mac language: python ver: 3.12.1

Table of contents

선행 지식

점프 투 파이썬 05-6 표준 라이브러리(os, time, zipfile)

create large file on a Mac OS


compression 옵션의 비교

python standard library 중 하나인 zipfile에 대해 배우던 중
compression 옵션의 종류 중 ‘ZIP_DEFLATED’과 ‘ZIP_LZMA’의 압축률 및 속도 차이가 궁금해졌다.
이를 확인하기 위해 임의의 파일(들)을 다음 두 가지 경우로 나누어 압축하기로 한다. compression=zipfile.ZIP_DEFLATED, compresslevel=1 compression=zipfile.ZIP_LZMA, compresslevel=9
결과부터 말하자면 아래 표와 같다.
<Zip efficiency comparison of LZMA and DEFLATED>
size before zip
size after zip
processing time
LZMA9
2.15GB
606KB
4m 52s
DEFLATED9
2.15GB
4.2MB
0m 27s
 

비교를 위한 large dummy file 만들기

또한 압축하려는 파일(들)의 크기가 작으면 ZIP_LZMA, level9로 해도 0.0초가 소요되어 어느 정도의 파일 크기가 보장되는 편이 비교가 편하다.
이를 위해 2GB짜리 dummy file을 2개 만들었다. (dd 명령어를 이용해 만들 수도 있지만 아직 이해가 어려워 mkfile 명령어를 사용하여 만들었다.)
mkfile 2G ziptestfile-1.mov
mkfile 2G ziptestfile-2.mov
figure 1. before zip
figure 1. before zip
mkfile [-n] size[b | k | m | g] filename ’-n’: 실제로 파일을 만들지 않고 생성될 파일의 크기만 출력한다. 테스트 용도로 크기를 확인할 때 유용하다. default값은 파일을 실제 생성한다. ’size’: 생성할 파일의 크기, byte | kilobyte | megabyte | gigabyte이다. default=byte ’filename’: 파일 이름
 

case1. LZMA, level9

compression=LZMA, compresslevel=9로 진행했다.
또한 아래 코드에서 현재 디렉토리를 나타내기 위해 os.system(”pwd”)를 사용했는데 예상과는 다르게 0이 출력되었다. 이 문제에 대해서는 case1 이후에서 다루겠다.
import os import time import zipfile def check_time(): return time.ctime() def compress_zipfile(): with zipfile.ZipFile('zipfile_compress_test1.zip', 'w', compression=zipfile.ZIP_LZMA, compresslevel=9) as myzip: myzip.write('ziptestfile-1.mov') myzip.write('ziptestfile-2.mov') print("dir is :", os.system("pwd")) # 0이 출력된다 time_before = check_time() print("before compress time(LZMA, 9) :", time_before) compress_zipfile() time_after = check_time() print("after compress time(LZMA, 9) :", time_after) print("before compress kb : %dgb" % (2.15*2)) print("==========W A I T==========")
figure 2. excuted in idle shell
figure 2. excuted in idle shell
figure 3. zip file & after unzip(LZMA9)
figure 3. zip file & after unzip(LZMA9)
 

case2. DEFLATED, level9

case1에서 사용한 code 중 일부를 변형하였다.
  • compress_zipfile() 함수에서 compression=DEFLATED로 변경
  • Current Directory 출력을 위해 os.system를 os.popen로 변경 또한 출력을 위해 read() 사용, 빈 줄 제거를 위해 strip() 사용
import os import time import zipfile def check_time(): return time.ctime() def compress_zipfile(): with zipfile.ZipFile('zipfile_compress_test2.zip', 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as myzip: myzip.write('ziptestfile-1.mov') myzip.write('ziptestfile-2.mov') cwd = os.popen("pwd").read() # os.system이 아닌 os.popen을 사용해야 결과가 출력된다. print("dir is :", cwd.strip()) # 빈 줄 제거 time_before = check_time() print("before compress time(DEFLATED, 9) :", time_before) print("==========W A I T==========") compress_zipfile() time_after = check_time() print("after compress time(DEFLATED, 9) :", time_after) print("before compress kb : %dgb" % (2.15*2)) print("==========D O N E==========")
figure 4. excuted in idle shell
figure 4. excuted in idle shell
figure 5. zip file & after unzip(DEFLATED9)
figure 5. zip file & after unzip(DEFLATED9)
 

os.system과 os.popen

os.system

  • os.system(”Instruction”)은 Instruction을 수행하고 수행이 완료되면 0, 오류가 발생하면 오류 메시지를 리턴한다.
    • figure 6. os.system() 실행 시 리턴값
      figure 6. os.system() 실행 시 리턴값
  • 따라서 pwd의 수행 여부가 아닌, pwd의 수행 결과를 출력하고 싶다면 후술하는 os.popen을 사용해야 한다.

os.popen

  • os.popen(”Instruction”)은 os. wrap_close object를 리턴하기 때문에 결과를 출력하기 위해서는 os.popen(”Instruction”).read()로 사용해야 한다.
    • figure 7. os.popen()의 리턴값
      figure 7. os.popen()의 리턴값
  • 위 사진을 보면 빈 줄이 한 줄 출력된 것을 알 수 있다. 출력된 이유는 다음과 같다. - 명령어를 실행하면 출력에는 (명령어 결과를 콘솔에서 보기 쉽게 하기 위하여) 개행 문자(newline character)가 포함된다. - 즉, 콘솔에서 명령어의 출력 더 읽기 쉽게 하기 위함이다.
  • 빈 줄은 strip을 사용해 제거할 수 있다.
    • figure 8. os.popen()의 리턴값에서 빈 줄 제거
      figure 8. os.popen()의 리턴값에서 빈 줄 제거

reference.

 
Share article

rudevico