google / python-fire

Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.
Other
26.66k stars 1.44k forks source link

Is it possible to pass arg via code and kwargs by cli (sys.argv) ? #470

Closed ThoenigAdrian closed 8 months ago

ThoenigAdrian commented 8 months ago

Is it possible to do something like that ? Couldn't find anything in the documentation.

def run_test(test_files, test_list=None):
    print(test_files) # this will be passed by the code
    print(test_list) # this should come from cli 

def main():
    test_files = find_test_files() # some function which produces a list as output
    fire.Fire(run_test, test_files) # use test_files from above but also use kwargs from command line 

main()

CLI:

    python run_autotests.py --test_list='["smoke_test"]'
dbieber commented 8 months ago

I think you could use functools for this.

import functools

def run_test(test_files, test_list=None):
    print(test_files) # this will be passed by the code
    print(test_list) # this should come from cli 

def main():
    test_files = find_test_files() # some function which produces a list as output
    modified_run_test = functools.partial(run_test, test_files=test_files)  # This gives a new func where test_files has already been applied.
    fire.Fire(run_test, test_files) # use test_files from above but also use kwargs from command line 

main()

I haven't double checked that this works. Give it a try and report back?