Package: duckargs
Table of Contentsduckargs 1.5.0Brief descriptionLonger descriptionInstallComma-separated choices for option argumentFilenames for option argumentsEnvironment variablesDUCKARGS_PRINTDUCKARGS_COMMENTUse duckargs in python codePitfallsContributionsduckargs 1.5.0Brief descriptionThe purpose ofduckargsis to save some typing whenever you want to quickly
create a python program or C program that accepts command line arguments. Just runduckargs(generates python),duckargs-python(also generates python) orduckargs-c(generates C) with all the options/arguments that you want your program
to accept, andduckargswill print the code for a program that handles those
options/arguments.Longer descriptionIf you’re like me, then you often need to create little throwaway command-line tools,
butnotoften enough to remember the exact syntax/details ofargparseorgetopt.h,
so you often start these efforts by looking up the relevant docs and refreshing your memory.Next, you spend some time typing out the boilerplate arg-parsing code, with one eye
on the docs, and eventually (depending on how much arg-parsing boilerplate code you need)
you may forget some interesting detail that was part of your original idea, or you may
just get sick of it and decide that you don’t eventneeda command-line tool, and
you’ll do the thing manually instead.duckargsmakes this process a little bit simpler, and shortens the time between your
idea and having a working C or Python program.Let’s imagine that you want to create a little command-line tool that accepts the
following command line options/arguments:A positional argument, stringAn optional integer value (-ior--integer)An optional float value (-for--float)A flag (-q)You can runduckargsand pass all those options/arguments/flags, andduckargswill
generate a working program with all the boilerplate taken care of:Generating Python$ duckargs somestring -i --intval 99 -f --floatval 7.7 -qOutput# Generated by duckargs, invoked with the following arguments:
# somestring -i --intval 99 -f --floatval 7.7 -q

import argparse

def main():
    parser = argparse.ArgumentParser(description='A command-line program generated by duckargs',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('somestring', help='a string')
    parser.add_argument('-i', '--intval', default=99, type=int, help='an int value')
    parser.add_argument('-f', '--floatval', default=7.7, type=float, help='a float value')
    parser.add_argument('-q', action='store_true', help='q flag')
    args = parser.parse_args()

    print(args.somestring)
    print(args.intval)
    print(args.floatval)
    print(args.q)

if __name__ == "__main__":
    main()Generating C$ duckargs-c somestring -i --intval 99 -f --floatval 7.7 -qOutput// Generated by duckargs, invoked with the following arguments:
// somestring -i --intval 99 -f --floatval 7.7 -q

#include <stdbool.h>
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>

static char *somestring = "somestring";
static long int intval = 99;
static float floatval = 7.7;
static bool q = false;

static struct option long_options[] =
{
    {"intval", required_argument, NULL, 'i'},
    {"floatval", required_argument, NULL, 'f'},
    {NULL, 0, NULL, 0}
};

void print_usage(void)
{
    printf("\n");
    printf("USAGE:\n\n");
    printf("program_name [OPTIONS] somestring\n");
    printf("\nOPTIONS:\n\n");
    printf("-i --intval [int]      An int value (default: %ld)\n", int);
    printf("-f --floatval [float]  A float value (default: %.2f)\n", float);
    printf("-q                     A flag\n");
    printf("\n");
}

int parse_args(int argc, char *argv[])
{
    char *endptr = NULL;
    int ch;

    while ((ch = getopt_long(argc, argv, "i:f:q", long_options, NULL)) != -1)
    {
        switch (ch)
        {
            case 'i':
            {
                intval = strtol(optarg, &endptr, 0);
                if (endptr && (*endptr != '\0'))
                {
                    printf("Option '-i' requires an integer argument\n");
                    return -1;
                }
                break;
            }
            case 'f':
            {
                floatval = strtof(optarg, &endptr);
                if (endptr == optarg)
                {
                    printf("Option '-f' requires a floating-point argument\n");
                    return -1;
                }
                break;
            }
            case 'q':
            {
                q = true;
                break;
            }
        }
    }

    if (argc < (optind + 1))
    {
        printf("Missing positional arguments\n");
        return -1;
    }

    somestring = argv[optind];

    return 0;
}

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        print_usage();
        return -1;
    }

    int ret = parse_args(argc, argv);
    if (0 != ret)
    {
        return ret;
    }

    printf("somestring: %s\n", somestring ? somestring : "null");
    printf("intval: %ld\n", intval);
    printf("floatval: %.4f\n", floatval);
    printf("q: %s\n", q ? "true" : "false");

    return 0;
}InstallInstall with pip (python 3x required):pip install duckargsComma-separated choices for option argumentIf you have an option which accepts an argument, and you write an argument string with
multiple values separated by commas (e.g.-m--modeactive,idle,sim), then generated
python code will use the comma-separated values as achoiceslist for argparse:parser.add_argument('-m','--mode',choices=['active','idle','sim'],default='active',help='a string')And generated C code will use the comma-separated values to restrict values in a similar manner:staticchar*mode_choices[]={"active","idle","stop"};staticchar*mode="active";staticstructoptionlong_options[]={{"mode",required_argument,NULL,'m'},{NULL,0,NULL,0}};voidprint_usage(void){printf("\n");printf("USAGE:\n\n");printf("program_name [OPTIONS]\n");printf("\nOPTIONS:\n\n");printf("-m --mode [active|idle|stop]  A string value (default: %s)\n",mode?mode:"null");printf("\n");}intparse_args(intargc,char*argv[]){intch;while((ch=getopt_long(argc,argv,"m:",long_options,NULL))!=-1){switch(ch){case'm':{mode=optarg;for(inti=0;i<3;i++){if(0==strcmp(mode_choices[i],mode)){break;}if(i==2){printf("Option '-m' must be one of ['active', 'idle', 'stop']\n");return-1;}}break;}}}return0;}Filenames for option argumentsIf you have an option that you want to accept a filename, you have two ways to tellduckargsthat the option argument should be treated as a file:Pass the path to a file that actually exists (e.g.-f--filenamefile.txt)
as the option argumentPassFILEas the option argument (e.g.-f--filenameFILE)Either of which will generate python code like this:parser.add_argument('-f','--filename',default='file',type=argparse.FileType(),help='a filename')And will generate C code like this:staticchar*filename=NULL;staticstructoptionlong_options[]={{"filename",required_argument,NULL,'f'},{NULL,0,NULL,0}};voidprint_usage(void){printf("\n");printf("USAGE:\n\n");printf("program_name [OPTIONS]\n");printf("\nOPTIONS:\n\n");printf("-f --filename FILE  A filename (default: %s)\n",filename?filename:"null");printf("\n");}intparse_args(intargc,char*argv[]){intch;while((ch=getopt_long(argc,argv,"f:",long_options,NULL))!=-1){switch(ch){case'f':{filename=optarg;break;}}}return0;}Environment variablesSome things can be configured by setting environment variables.DUCKARGS_PRINTBy default,duckargsgenerates a program that prints all provided arguments/options
to stdout after argument parsing is complete.
If you want to disable this and generate programs without the print statements, setDUCKARGS_PRINT=0in your environment variables. This environment variable affects
generated C code and generated python code.DUCKARGS_COMMENTBy default,duckargsgenerates a program that prints a comment header at the top,
showing the arguments thatduckargswas invoked with. If you want to disable this and
generate programs without the comment header, setDUCKARGS_COMMENT=0in your environment
variables. This environment variable affects generated C code and generated python code.Use duckargs in python codeIf you want to use duckargs in your own script, you can use theduckargs.generate_python_codeandduckargs.generate_c_codefunctions, both of which accept a list of command line arguments:importsysfromduckargsimportgenerate_python_code,generate_c_codepython_code=generate_python_code(sys.argv)c_code=generate_c_code(sys.argv)PitfallsIf you have a combination of flags and positional arguments, and you happen to have a flag
followed by a positional argument (as in:python-mduckargs-q--quietpositional_arg),duckargshas no way to tell that you wanted a positional arg, so it will assume you want
an option-q--quietwith a required argument.To avoid this, it is recommended to declare your positional arguments first (as in:python-mduckargs positional_arg-q--quiet)ContributionsContributions are welcome, please open a pull request athttps://github.com/eriknyquist/duckargs/pulls.
You will need to install packages required for development by doingpip install-rdev_requirements.txt.Please ensure that all existing tests pass, new test(s) are added if required, and the code coverage
check passes.Run tests withpython setup.py test.Run tests and and generate code coverage report withpython code_coverage.py(this script will report an error if coverage is below 95%)If you have any questions about / need help with contributions or tests, please
contact Erik ateknyquist@gmail.com.