Passing command line arguments to functions and methods with python-fire
pythonpython-fire is a library to create CLI tools from Python objects.
$ pip install fire
Just wrap with fire.Fire() to pass command line arguments to functions and methods.
$ cat main.py
import fire
class FizzBuzz:
def fizzbuzz(self, num):
ret = ""
if num % 3 == 0:
ret += "fizz"
if num % 5 == 0:
ret += "buzz"
if len(ret) != 0:
return ret
return str(num)
def fizzbuzzs(self, nums):
return [self.fizzbuzz(num) for num in nums]
if __name__ == '__main__':
fire.Fire(FizzBuzz)
$ python main.py fizzbuzzs --nums="[2,21,30]"
2
fizz
fizzbuzz
Command line arguments are evaluated to strings, numbers, lists, etc. by ast.literal_eval().
import ast
root = ast.parse('[{"a":100}]', mode='eval')
print(type(ast.literal_eval(root))) # <class 'list'>
Besides, you can run REPL or display trace.
$ python main.py -- --interactive
>>> FizzBuzz().fizzbuzz(10)
'buzz'
$ python main.py fizzbuzzs --nums="[2,21,30]" -- --trace
Fire trace:
1. Initial component
2. Instantiated class "FizzBuzz" (xxx/main.py:3)
3. Accessed property "fizzbuzzs" (xxx/main.py:14)
4. Called routine "fizzbuzzs" (xxx/main.py:14)