I’m using the fire library in Python to create a simple command-line interface (CLI). My setup is as follows:
import fire
def main(a):
print('hi')
if __name__ == '__main__':
fire.Fire(main)
When I run the script like this:
$ python my_script.py 123
It prints:
hi
What I’d like to do is print the arguments passed to main (in this case 123) before it prints “hi”. Is there a way to intercept and print the arguments in fire.Fire(main)?
I’ve tried modifying the function signature and adding *args, but that changes how the function behaves with Fire.
How can I print the arguments passed to main using Python Fire without changing the logic inside the function?
Attempt:
import fire
class MyWrapper:
def __init__(self, target):
self.target = target
def __getattr__(self, name):
def method(*args, **kwargs):
# Print the arguments passed to the Fire CLI
print(f"Method: {name}, Args: {args}, Kwargs: {kwargs}")
# Call the original method
return getattr(self.target, name)(*args, **kwargs)
return method
class MyCommands:
def greet(self, name="World"):
return f"Hello, {name}!"
if __name__ == '__main__':
fire.Fire(MyWrapper(MyCommands))
2
try
def main(a):
print(f'{a} hi')
I dont have fire installed
There’s always just dumping args and/or kwargs
def example(**kwargs):
print(f"Supplied kwargs: {kwargs}")
a = kwargs.get("a")
print(f"'a' kwarg: {kwargs.get('a')}")
You can also use inspect
import inspect
def example_function(a, b, c=3, d=4):
# Get information about the current function call [frame]
frame = inspect.currentframe()
# Get the arguments passed to this function
args, _, _, values = inspect.getargvalues(frame)
# Print out the arguments and their values
for arg in args:
print(f"{arg} = {values[arg]}")
# Call the function
example_function(1, 2, d=5)
>>> example_function(1, 2, d=5)
a = 1
b = 2
c = 3
d = 5