반응형

fire 라이브러리는 Python 함수나 클래스를 커맨드라인에서 바로 호출할 수 있도록 해줍니다.  또한 커맨드라인의 인자를 함수의 인자로 매핑하는 기능도 제공합니다.



2024. 1. 14  최초작성




커맨드라인의 인자를 함수의 인자로 매핑해주는 예제 코드입니다.  커맨드라인 인자가 calculator 함수의 인자로 패핑이 됩니다. 



import fire

def calculator(num1, num2):
    """
   
    간단한 계산기 함수

    :param num1: (float) 첫 번째 숫자
    :param num2: (float) 두 번째 숫자

    Returns:
        float: 계산 결과
    """
    return num1 + num2

if __name__ == '__main__':
    fire.Fire(calculator)




실행결과입니다. 아무 인자 없이 실행하면 인자에 대한 설명이 출력됩니다.

 

(python311) webnautes@webnautes-laptop:~$ python test.py 

ERROR: The function received no value for the required argument: num1

Usage: test.py NUM1 NUM2

 

For detailed information on this command, run:

  test.py --help



인자를 다음처럼 1과 2로 주면 calculator 함수의 인자로 사용되어 계산 결과 3이 출력됩니다. 

 

(python311) webnautes@webnautes-laptop:~$ python test.py 1 2

3





커맨드라인에서 함수를 바로 호출하는 예제 코드입니다. 

 

import fire

class Calculator(object):
    def add(self, num1, num2):
        return num1 + num2

    def subtract(self, num1, num2):
        return num1 - num2

    def multiply(self, num1, num2):
        return num1 * num2

    def divide(self, num1, num2):
        return num1 / num2

if __name__ == '__main__':
    fire.Fire(Calculator)



아무 인자 없이 실행하면 

 

(python311) webnautes@webnautes-laptop:~$ python test.py   



설명이 다음처럼 보이며  q를 누르면 빠져나옵니다. 

 



다음처럼 함수 이름을 인자로 주고 뒤에 연산할 숫자 2개를 주면 해당 함수로 전달되어 계산 결과가 출력됩니다. 

 

(python311) webnautes@webnautes-laptop:~$ python test.py  add 1 2 

3

(python311) webnautes@webnautes-laptop:~$ python test.py  subtract  1 2 

-1

(python311) webnautes@webnautes-laptop:~$ python test.py  multiply  1 2 

2

(python311) webnautes@webnautes-laptop:~$ python test.py  divide  1 2 

0.5




반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts