Skip to content

Instantly share code, notes, and snippets.

@fragmuffin
Created October 5, 2018 16:47
Show Gist options
  • Save fragmuffin/c5f99a2e7011bf065651448dc5f25c85 to your computer and use it in GitHub Desktop.
Save fragmuffin/c5f99a2e7011bf065651448dc5f25c85 to your computer and use it in GitHub Desktop.
python function as script

Python Function as Script

This is a quick demonstration of how to create a function that can be used as either:

  • command-line script with parameters, or
  • imported module function

Running in Command-Line

Direct

$ python mod.py abc --list xyz,123
x = 'abc'
y = ['xyz', '123']

Run Module

Alternatively, it can be run as a module. This will search the sys.path for a module with the same name and run it like the script above.

$ python -m mod abc --list xyz,123
x = 'abc'
y = ['xyz', '123']

Help Output

$ python mod.py --help
usage: mod.py [-h] [--list LIST] [x]

Do some stuff

positional arguments:
  x                     A value with some meaning

optional arguments:
  -h, --help            show this help message and exit
  --list LIST, -l LIST  CSV list of things

Importing function

>>> from mod import foo
>>> foo('abc', ['xyz', '123'])
x = 'abc'
y = ['xyz', '123']
#!/usr/bin/env python
def foo(x, y):
print('x = {!r}'.format(x))
print('y = {!r}'.format(y))
if __name__ == '__main__':
import argparse
# Parse command-line parameters
parser = argparse.ArgumentParser(description="Do some stuff")
def csv_list(value):
return value.split(',')
parser.add_argument(
'x', nargs='?', default='blah',
help="A value with some meaning",
)
parser.add_argument(
'--list', '-l', dest='list',
type=csv_list, default=[],
help="CSV list of things",
)
args = parser.parse_args()
# Run method with command-line arguments
foo(x=args.x, y=args.list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment