Skip to main content

Automatically generate a simple CLI.

Project description

FunCLI PyPI

Automatically generate a simple CLI.

Installation

pip install funcli

Basic Usage

def main(*args: int):
	print("Sum:", sum(args))

if __name__ == '__main__':
	import funcli
	funcli.main()

# $ python sum.py 1 2 3
# Sum: 6

--help is autogenerated:

$ python sum.py -h
usage: sum.py [-h] [args [args ...]]

positional arguments:
	args

optional arguments:
	-h, --help  show this help message and exit

Reference

funcli.main(spec = None)

Sugar. spec defaults to the main function from the caller's scope. Calls funcli.run on spec, and calls sys.exit with the return value.

funcli.run(spec, args = None, converters = None)
  • spec is either a callable, a sequence of callables, or a dict mapping strings to nested specs
  • args default to sys.argv[1:]
  • converters is a mapping from types (or whatever you want to use as annotations) to a function that parses a command line argument

Given functions foo, bar, baz, here are some sample invocations:

funcli.run(foo, ['arg0']) # Calls foo('arg0')
funcli.run({ foo, bar }, ['bar', 'arg0']) # Calls bar('arg0')
funcli.run({ 'beep': foo, 'bloop': [bar, baz] }, ['beep', 'arg0']) # Calls foo('arg0')
funcli.run({ 'beep': foo, 'bloop': [bar, baz] }, ['bloop', 'bar', 'arg0']) # Calls bar('arg0')

bool arguments

Non-optional bool values should be passed as True and False on the command line. Optional bool values, on the other hand, must be omitted.

def f(warnings: bool = False): ...
funcli.run(f, ['--warnings']) # f(warnings = True)

Note: currently, if the default value is True, there is no way to pass False.

Converters

Built-in converters handle int, float, bool, and pathlib.Path. Everything else is kept as a str.

Notes

Because of argparse limitations:

  • **kwargs aren't supported; if your function has them, they'll always be empty
  • optional arguments cannot be positional; f(a = 'default') has to be invoked as python foo.py --a=nondefault

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

funcli-0.2.0.tar.gz (3.8 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page