Verified Commit b251e639 authored by Toby Hodges's avatar Toby Hodges Committed by Renato Alves
Browse files

add solution for 4.2

parent 26f8c9bc
......@@ -93,7 +93,7 @@ END
> > but in a standalone script or a module
> > it can be helpful, e.g. for including in logging messages created by
> > functions that could be imported into other programs.
> >
> >
> > Whether the full path to the program is included or not depends on the
> > operating system.
> > If you need to rely on the full path being available,
......@@ -170,6 +170,70 @@ TypeError: can only concatenate str (not "int") to str
> Do you think this is a good way to construct an interface for a program like this?
> What potential problems can you identify with this approach?
> Pair up and discuss with a partner.
>
> > ## Solution
> >
> > ~~~
> > from sys import argv, stdout
> > from numpy import prod # use math.prod here if you're running Python 3.8
> > from statistics import mean
> >
> > input_files = argv[-3:]
> >
> > modes = {'--sum': sum,
> > '--product': prod,
> > '--mean': mean}
> > output_file = stdout
> >
> > for option in argv[1:-3]:
> > if option in modes:
> > output_function=modes[option]
> > elif option.startswith('--output='):
> > output_file = option.split('=')[1]
> > ~~~
> > {: .language-python}
> >
> > Changing the code to take an arbirary number of input files
> > is possible,
> > but you will have to assume that your user(s) will remember the required
> > syntax for running your program:
> > ~~~
> > from sys import argv, stdout, exit
> > from numpy import prod # use math.prod here if you're running Python 3.8
> > from statistics import mean
> >
> > input_files = []
> >
> > modes = {'--sum': sum,
> > '--product': prod,
> > '--mean': mean}
> > output_file = stdout
> >
> > for argument in argv[1:]:
> > if argument in modes:
> > output_function=modes[argument]
> > elif argument.startswith('--output='):
> > output_file = argument.split('=')[1]
> > elif not argument.startswith('--'):
> > input_files.append(argument)
> > else:
> > print('unexpected option,', argument, 'given! exiting.')
> > exit(1)
> > ~~~
> > {: .language-python}
> >
> > The example solution above makes the assumption that anything
> > passed on the command line that doesn't begin with `--` must be
> > the name of an input file.
> > This is certainly not the most robust interface ever designed!
> >
> > Note also that, to encourage good practices,
> > we use the `sys.exit` function,
> > which you may not have been introduced to before.
> > This function call will cause the script to quit with error code 1
> > (after printing a semi-helpful error message)
> > when an invalid option is provided.
> {: .solution }
{: .challenge}
`sys.argv` is a great choice when the interface of our program is
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment