반응형

How to convert to python script to exec file with options

 

PyInstaller는 python script를 python interpreter나 추가적인 module 설치 없이 파일 하나로 동작할 수 있게 실행 파일을 만들어주는 패키지이다.

기본적인 사용 방법은 다음과 같다.

pyinstaller hello.py

이번에는 추가적으로 사용할 수 있는 옵션들 소개와 사용 예시를 소개하려고 한다. 물론 보다 자세한 설명은 공식 사이트에 있다.

이번 포스팅에서 사용할 hello.py 스크립트의 내용은 다음과 같다.

import argparse
import cv2

parser = argparse.ArgumentParser()
parser.add_argument('--name', type=str, default='world')
args = parser.parse_args()

def main():
    img_path = './help.jpeg'
    img = cv2.imread(img_path)
    
    print('hello ' + args.name)
    print(img.shape)

    return
if __name__ == '__main__':
    main()

스크립트와 같은 위치에 있는 help.jpeg라는 이미지와 name이라는 명령어 인자를 읽어와 hello name과 이미지 사이즈를 출력하는 간단한 코드이다. python interpreter로 간단하게 실행을 한다면 다음과 같이 출력이 된다.

(pytorch) hyeonjeong@baghyeonjeongs-MacBook-Pro Study % python hello.py --name=world    
hello world
(225, 225, 3)

이러한 script를 실행파일로 만들 때 다음과 같은 옵션들을 사용할 수 있다.

-F, --onefile

pyinstaller를 사용해서 실행파일을 생성하게 되면 프로그램에 필요한 여러 파일들이 생성된다. 이러한 추가적인 파일 없이 실행파일을 하나의 bundle로 묶어서 만들어 주는 옵션이다. 다음과 같이 두 가지 방법으로 사용할 수 있다.

pyinstaller -F hello.py
pyinstaller --onefile hello.py

이 옵션을 사용하여 실행파일을 생성하면 dist 폴더 안에 hello라는 폴더가 생성되지 않고 바로 hello라는 실행파일이 생성된다.

-y, --noconfirm

이미 pyinstaller로 실행파일을 생성한 후에 script를 수정하고 다시 생성하고 싶을 때 파일의 삭제나 대체하겠다는 입력 없이 바로 대체하여 생성시켜 주는 옵션이다.

pyinstaller -y hello.py
pyinstaller --noconfirm hello.py

--add-data <SRC;DEST or SRC:DEST>

이미지나 텍스트 파일과 같이 script에서 사용되는 추가 파일들을 실행파일에 포함시키는 옵션이다. 다음과 같이 사용할 수 있다.

이때 윈도우의 경우에는 ;를 사용하고 linux나 MacOS와 같은 대부분의 unix 시스템에서는 :를 사용하여 소스파일과 저장될 폴더를 구분하여 사용한다.

pyinstaller -F --add-data="help.jpeg:." hello.py

위의 예제에서는 script와 이미지파일이 같은 폴더 내에 있었기 때문에 이미지 경로를 단순하게./help.jpeg라고 하였지만 실행파일로 만들어지는 순간 run-time으로 임시 폴더에 있는 이미지 파일을 불러와야 하기 때문에 경로를 수정해 주어야 한다.

import argparse
import cv2
import sys
import os

parser = argparse.ArgumentParser()
parser.add_argument('--name', type=str, default='earth')
args = parser.parse_args()

def main():
    img_path = os.path.join(getattr(sys, '_MEIPASS'), 'help.jpeg')
    img = cv2.imread(img_path)
    
    print('hello ' + args.name)
    print(img.shape)

    return
if __name__ == '__main__':
    main()

sys 모듈을 추가로 import 하고 img_path에 sys._MEIPASS 경로에 있는 help.jpeg 이미지 경로로 수정했다.

 

With Argparse

당연하게도 만들어진 실행파일에 인자를 받아서 사용할 수 있다. 실행파일을 생성할 때는 추가로 해야 할 옵션을 없고 생성된 실행파일을 사용할 때 python interpreter를 사용해서 실행하는 것과 같이 뒤에 추가로 붙여서 사용하면 된다.

./dist/hello --name=earth
hello earth
(225, 225, 3)

 

Reference

https://pyinstaller.org/en/stable/index.html

 

PyInstaller Manual — PyInstaller 5.8.0 documentation

PyInstaller bundles a Python application and all its dependencies into a single package. The user can run the packaged app without installing a Python interpreter or any modules. PyInstaller supports Python 3.7 and newer, and correctly bundles many major P

pyinstaller.org

https://docs.python.org/ko/3/library/argparse.html

 

argparse — Parser for command-line options, arguments and sub-commands

Source code: Lib/argparse.py Tutorial: This page contains the API reference information. For a more gentle introduction to Python command-line parsing, have a look at the argparse tutorial. The arg...

docs.python.org

 

반응형

+ Recent posts