G_OPTION_FLAG_OPTIONAL_ARG is ignored when used alongside G_OPTION_ARG_INT

What I want to do

I want my application to have an option -v, --verbosity=LEVEL with LEVEL being an optional integer. That is, I want my users to be able to use this option as used in following commands

myapp -v            # Automatic verbose mode with predefined verbosity level
myapp -v3           # Verbose mode with verbosity level 3
myapp --verbosity=3 # Verbose mode with verbosity level 3

My Current Code

import sys
import gi
gi.require_version('Adw', '1')
from gi.repository import Adw, Gio, GLib

class Application (Adw.Application):
    def __init__(self):
        Adw.Application.__init__(self,
                                 application_id="org.adw.example",
                                 flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
                                )

        self.add_main_option("verbosity", "v".encode(),      # Long, short option
                             GLib.OptionFlags.OPTIONAL_ARG,  # Option Flags
                             GLib.OptionArg.INT,             # Argument Flags
                             "Enable verbose mode",          # Option Description
                             "LEVEL",                        # Argument Name
                             )

        self.connect("activate", self.on_activate)
        self.connect("handle-local-options", self.handle_local_options)
        self.connect("command-line", self.on_command_line)
    
    def on_activate(self, app):
        pass

    def on_command_line(self, klass, command_line):
        return 0

    def handle_local_options(self, klass, options):
        return 0

app = Application()
app.run(sys.argv)

Current Behavior

Currently, when running above script, it spits out the following output

/mnt/Data/gitapps/test/./test5.py:14: Warning: ../glib/glib/goption.c:2447: ignoring no-arg, optional-arg or filename flags (32) on option of arg-type 2 in entry (null):verbosity
  self.add_main_option("verbosity", "v".encode(),      # Long, short option

My Questions

  • What am I doing wrong?
  • Why does G_OPTION_FLAG_OPTIONAL_ARG not work along with G_OPTION_ARG_INT?
  • How do I achieve my goal?

Docs say you have to use G_OPTION_FLAG_OPTIONAL_ARG with G_OPTION_ARG_CALLBACK and provide your own callback to parse the option. I understand you need a space character between short option name and argument, e.g. -v 3.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.