quan
(Nguyễn Hồng Quân)
June 2, 2020, 5:00am
1
Imagine that I have an app, my_app
, I want to design its CLI option as:
my_app -v
with -v
being “verbose”, and to increase verbosity, user just repeat that option, like:
my_app -vv
How to archive that with Gio.Application.add_main_option
and friends?
baedert
(Timm Bäder)
June 2, 2020, 6:26am
2
GOptionContext can’t do that, so you just have to do the parsing yourself.
1 Like
federico
(Federico Mena Quintero)
June 15, 2020, 11:30pm
3
I don’t know pygi well enough off the top of my head, so here’s a C version which hopefully you can translate to Python You can use a combination of G_OPTION_FLAG_NO_ARG
and G_OPTION_ARG_CALLBACK
. For example:
/* gcc -Wall -g -O0 -o foo foo.c `pkg-config --cflags --libs glib-2.0` */
#include <stdio.h>
#include <glib.h>
static guint verbosity = 0;
static gboolean verbosity_callback (const gchar *option_name,
const gchar *value,
gpointer data,
GError **error)
{
verbosity++;
return TRUE;
}
static GOptionEntry entries[] = {
{ "verbose", 'v', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, verbosity_callback, "Increase verbosity", "" },
{ NULL }
};
int
main (int argc, char **argv)
{
GOptionContext *context;
GError *error = NULL;
context = g_option_context_new ("- test verbosity flag");
g_option_context_add_main_entries (context, entries, NULL);
if (!g_option_context_parse (context, &argc, &argv, &error)) {
printf ("invalid options: %s\n", error->message);
exit (1);
}
printf ("verbosity level %u\n", verbosity);
return 0;
}
If you run it like “foo -vvv
” it will print “verbosity level 3
”.
1 Like
quan
(Nguyễn Hồng Quân)
June 16, 2020, 3:09pm
4
Thanks. I hope that GTK developers will add this feature, because this pattern seems to be popular enough.
ebassi
(Emmanuele Bassi)
June 16, 2020, 3:20pm
5
It’s extremely unlikely that will happen. You can easily use the callback notation to do that yourself, and that kind of incremental globbing is only ever useful for a very small subset of command line arguments.
quan
(Nguyễn Hồng Quân)
June 16, 2020, 3:29pm
6
Among Python applications, this pattern is popular enough that it is added to Python standard library :
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count', default=0)
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)
and also welknown 3-rd party library :
@click.command()
@click.option('-v', '--verbose', count=True)
def log(verbose):
click.echo('Verbosity: %s' % verbose)
ebassi
(Emmanuele Bassi)
June 16, 2020, 4:46pm
7
It doesn’t really matter what’s popular with Python, though.
1 Like
system
(system)
Closed
June 30, 2020, 4:46pm
8
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.