Exceptions that might make sense to be used outside the library.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Cancelled
+
+
+
+
+
+
+
+
+
User has cancelled.
+A SystemExit based exception noting that the program exits without a traceback,
+ex. if user hits the escape or closes the window.
+
+
+
+
+
+
+
+
+
+
+
+ ValidationFail
+
+
+
+
+
+
+
+
+
Signal to the form that submit failed and we want to restore it.
+
+
+
+
+
+
+
+
+
+
+
+ InterfaceNotAvailable
+
+
+
+
+
+
+
+
+
Interface failed to init, ex. display not available in GUI. Or the underlying dependency was uninstalled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Experimental/index.html b/Experimental/index.html
index 5eb45fe..f042d1e 100644
--- a/Experimental/index.html
+++ b/Experimental/index.html
@@ -256,6 +256,43 @@
+
+
+
+
+
Normally, you get an interface through mininterface.run
+but if you do not wish to parse CLI and config file, you can invoke one directly from mininterface.interfaces import *.
+
Apart from the default Mininterface, the base interface the others are fully compatible with, several interfaces exist:
The base interface.
You get one through mininterface.run which fills CLI arguments and config file to mininterface.env
- or you can create one directly (without benefiting from the CLI parsing).
+ or you can create one directly (without benefiting from the CLI parsing).
Raise
-
Cancelled: A SystemExit based exception noting that the program exits without a traceback, ex. if user hits the escape.
+
Cancelled: A SystemExit based exception noting that the program exits without a traceback, ex. if user hits the escape.
Raise
-
InterfaceNotAvailable: Interface failed to init, ex. display not available in GUI.
Use a common dataclass, a Pydantic BaseModel or an attrs model to store the configuration. Wrap it to the run function that returns an interface m. Access the configuration via m.env or use it to prompt the user m.is_yes("Is that alright?").
-
There are a lot of supported types you can use, not only scalars and well-known objects (Path, datetime), but also functions, iterables (like list[Path]) and union types (like int | None). To do even more advanced things, stick the value to a powerful Tag or its subclasses. Ex. for a validation only, use its Validation alias.
+
There are a lot of supported types you can use, not only scalars and well-known objects (Path, datetime), but also functions, iterables (like list[Path]) and union types (like int | None). To do even more advanced things, stick the value to a powerful Tag or its subclasses. Ex. for a validation only, use its Validation alias.
At last, use Facet to tackle the interface from the back-end (m) or the front-end (Tag) side.
IDE suggestions
The immediate benefit is the type suggestions you see in an IDE. Imagine following code:
@@ -334,6 +396,9 @@
IDE suggestions
Should the dataclass cannot be easily investigated by the IDE (i.e. a required field), just annotate the output.
+
Bash completion
+
Run your program with a hidden --integrate-to-system flag and a tutorial will install bash completion.
Dealing with CLI subcommands, from mininterface.subcommands import *
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Command
+
+
+
+
+
+
+
+
+
The Command is automatically run while instantanied.
+
Experimental – how should it receive _facet?
+
Put list of Commands to the mininterface.run and divide your application into different sections.
+Alternative to argparse subcommands.
+
Commands might inherit from the same parent to share the common attributes.
+
SubcommandPlaceholder
+
What if I need to use my program
+Special placeholder class SubcommandPlaceholder.
+This special class let the user to choose the subcommands via UI,
+while still benefiniting from default CLI arguments.
+
The CLI behaviour:
+
+
./program.py -> UI started with subcommand choice
+
./program.py subcommand --flag -> special class SubcommandPlaceholder allows defining a common --flag
+ while still starting UI with subcommand choice
Let's start the program, passing there common flags, all HTML files in a folder and setting --common to 7.
+
$program.pysubcommand*.html--common7
+
+
+
As you see, thanks to SubcommandPlaceholder, subcommand was not chosen yet. Click to the first button.
+
+
and the terminal got:
+
Common: 7
+Number: 1
+Internal: value
+
+
Click to the second button.
+
+
Terminal output:
+
Common files [PosixPath('page1.html'), PosixPath('page2.html')]
+
+
Powerful automation
+
Note we use from tyro.conf import Positional to denote the positional argument. We did not have to write --files to put there HTML files.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ init()
+
+
+
+
+
+
+
Just before the form appears.
+As the __post_init__ method is not guaranteed to run just once (internal CLI behaviour),
+you are welcome to override this method instead. You can use self._facet from within.
+
+
+
+
+
+
+
+
+
+ run()
+
+
+
+
+
+
+
This method is run automatically in CLI or by a button button it generates in a UI.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ SubcommandPlaceholder
+
+
+
+
+
+
+
+
+
Use this placeholder to choose the subcomannd via a UI.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Tag/index.html b/Tag/index.html
index 38dd176..8d6d94f 100644
--- a/Tag/index.html
+++ b/Tag/index.html
@@ -254,6 +254,43 @@
+
+
+
+
+
+
+
+
+
When the user submits the form, the values are validated (and possibly transformed) with a callback function.
If the validation fails, user is prompted to edit the value.
Return True if validation succeeded or False or an error message when it failed.
-
ValidationResult is a bool or the error message (that implicitly means it has failed).
+
ValidationResult is a bool or the error message (that implicitly means it has failed).
defcheck(tag:Tag):iftag.val<10:return"The value must be at least 10"
@@ -1158,7 +1248,7 @@
Mininterface – ac
""" This number is very important """if__name__=="__main__":
-env=run(Env,prog="My application").env
-# Attributes are suggested by the IDE
-# along with the hint text 'This number is very important'.
-print(env.my_number)
+m=run(Env,prog="My application")
+m.form()
+# Attributes are suggested by the IDE
+# along with the hint text 'This number is very important'.
+print(m.env.my_number)
Contents
@@ -513,16 +694,18 @@
Contents
You got CLI
It was all the code you need. No lengthy blocks of code imposed by an external dependency. Besides the GUI/TUI, you receive powerful YAML-configurable CLI parsing.
Loading config file is a piece of cake. Alongside program.py, put program.yaml and put there some of the arguments. They are seamlessly taken as defaults.
A powerful m.form dialog method accepts either a dataclass or a dict. Take a look on both.
A complex dataclass.
-
fromtypingimportAnnotated
-fromdataclassesimportdataclass
-frommininterface.validatorsimportnot_empty
-frommininterfaceimportrun,Tag,Validation
-
-@dataclass
-classNestedEnv:
-another_number:int=7
-""" This field is nested """
-
-@dataclass
-classEnv:
-nested_config:NestedEnv
-
-mandatory_str:str
-""" As there is no default value, you will be prompted automatically to fill up the field """
-
-my_number:int|None=None
-""" This is not just a dummy number, if left empty, it is None. """
-
-my_string:str="Hello"
-""" A dummy string """
-
-my_flag:bool=False
-""" Checkbox test """
-
-my_validated:Annotated[str,Validation(not_empty)]="hello"
-""" A validated field """
-
-m=run(Env,title="My program")
-# See some values
-print(m.env.nested_config.another_number)# 7
-print(m.env)
-# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')
-
-# Edit values in a dialog
-m.form()
+
fromtypingimportAnnotated
+fromdataclassesimportdataclass
+frommininterface.validatorsimportnot_empty
+frommininterfaceimportrun,Tag,Validation
+
+@dataclass
+classNestedEnv:
+another_number:int=7
+""" This field is nested """
+
+@dataclass
+classEnv:
+nested_config:NestedEnv
+
+mandatory_str:str
+""" As there is no default value, you will be prompted automatically to fill up the field """
+
+my_number:int|None=None
+""" This is not just a dummy number, if left empty, it is None. """
+
+my_string:str="Hello"
+""" A dummy string """
+
+my_flag:bool=False
+""" Checkbox test """
+
+my_validated:Annotated[str,Validation(not_empty)]="hello"
+""" A validated field """
+
+m=run(Env,title="My program")
+# See some values
+print(m.env.nested_config.another_number)# 7
+print(m.env)
+# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')
+
+# Edit values in a dialog
+m.form()
-
As there is no default value at mandatory_str, you will be prompted automatically to fill up the field:
+
As the attribute mandatory_str requires a value, a prompt appears automatically:
Then, full form appears:
Form with paths
We have a dict with some paths. Here is how it looks.
-
frompathlibimportPath
-frommininterfaceimportrun,Tag
-
-m=run(title="My program")
-my_dictionary={
-"paths":Tag("",annotation=list[Path]),
-"default_paths":Tag([Path("/tmp"),Path("/usr")],annotation=list[Path])
-}
-
-# Edit values in a dialog
-m.form(my_dictionary)
+
frompathlibimportPath
+frommininterfaceimportrun,Tag
+
+m=run(title="My program")
+my_dictionary={
+"paths":Tag("",annotation=list[Path]),
+"default_paths":Tag([Path("/tmp"),Path("/usr")],annotation=list[Path])
+}
+
+# Edit values in a dialog
+m.form(my_dictionary)
Which interface to prefer. By default, we use the GUI, the fallback is the TUI.
+You may write "gui" or "tui" literal or pass a specific Mininterface type,
+see the full list of possible interfaces.
+
+
+
+ None
+
+
+
+
args
+
+ Optional[Sequence[str]]
-
Which interface to prefer. By default, we use the GUI, the fallback is the TUI. See the full list of possible interfaces.
+
Parse arguments from a sequence instead of the command line.
You cay context manager the function by a with statement.
The stdout will be redirected to the interface (ex. a GUI window).
-
withrun(Env)asm:
-print(f"Your important number is {m.env.important_number}")
-boolean=m.is_yes("Is that alright?")
+
fromdataclassesimportdataclass
+frommininterfaceimportrun
+
+@dataclass
+classEnv:
+my_number:int=4
+
+withrun(Env)asm:
+print(f"Your important number is {m.env.my_number}")
+boolean=m.is_yes("Is that alright?")
@@ -778,7 +982,7 @@
Run
-
+
diff --git a/search/search_index.json b/search/search_index.json
index 83157d7..a02a9ab 100644
--- a/search/search_index.json
+++ b/search/search_index.json
@@ -1 +1 @@
-{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Mininterface \u2013 access to GUI, TUI, CLI and config files","text":"
Write the program core, do not bother with the input/output.
Check out the code, which is surprisingly short, that displays such a window or its textual fallback.
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n \"\"\" This calculates something. \"\"\"\n\n my_flag: bool = False\n \"\"\" This switches the functionality \"\"\"\n\n my_number: int = 4\n \"\"\" This number is very important \"\"\"\n\nif __name__ == \"__main__\":\n env = run(Env, prog=\"My application\").env\n # Attributes are suggested by the IDE\n # along with the hint text 'This number is very important'.\n print(env.my_number)\n
It was all the code you need. No lengthy blocks of code imposed by an external dependency. Besides the GUI/TUI, you receive powerful YAML-configurable CLI parsing.
$ ./hello.py\nusage: My application [-h] [--test | --no-test] [--important-number INT]\n\nThis calculates something.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 --test, --no-test My testing flag (default: False) \u2502\n\u2502 --important-number INT This number is very important (default: 4) \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
Loading config file is a piece of cake. Alongside program.py, put program.yaml and put there some of the arguments. They are seamlessly taken as defaults.
Check out several useful methods to handle user dialogues. Here we bound the interface to a with statement that redirects stdout directly to the window.
with run(Env) as m:\n print(f\"Your important number is {m.env.my_number}\")\n boolean = m.is_yes(\"Is that alright?\")\n
Wrapper between the tyro argparse replacement and tkinter_form that converts dicts into a GUI.
Writing a small and useful program might be a task that takes fifteen minutes. Adding a CLI to specify the parameters is not so much overhead. But building a simple GUI around it? HOURS! Hours spent on researching GUI libraries, wondering why the Python desktop app ecosystem lags so far behind the web world. All you need is a few input fields validated through a clickable window... You do not deserve to add hundred of lines of the code just to define some editable fields. Mininterface is here to help.
The config variables needed by your program are kept in cozy dataclasses. Write less! The syntax of tyro does not require any overhead (as its argparse alternatives do). You just annotate a class attribute, append a simple docstring and get a fully functional application: * Call it as program.py --help to display full help. * Use any flag in CLI: program.py --my-flag causes env.my_flag be set to True. * The main benefit: Launch it without parameters as program.py to get a full working window with all the flags ready to be edited. * Running on a remote machine? Automatic regression to the text interface.
from typing import Annotated\nfrom dataclasses import dataclass\nfrom mininterface.validators import not_empty\nfrom mininterface import run, Tag, Validation\n\n@dataclass\nclass NestedEnv:\n another_number: int = 7\n \"\"\" This field is nested \"\"\"\n\n@dataclass\nclass Env:\n nested_config: NestedEnv\n\n mandatory_str: str\n \"\"\" As there is no default value, you will be prompted automatically to fill up the field \"\"\"\n\n my_number: int | None = None\n \"\"\" This is not just a dummy number, if left empty, it is None. \"\"\"\n\n my_string: str = \"Hello\"\n \"\"\" A dummy string \"\"\"\n\n my_flag: bool = False\n \"\"\" Checkbox test \"\"\"\n\n my_validated: Annotated[str, Validation(not_empty)] = \"hello\"\n \"\"\" A validated field \"\"\"\n\nm = run(Env, title=\"My program\")\n# See some values\nprint(m.env.nested_config.another_number) # 7\nprint(m.env)\n# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')\n\n# Edit values in a dialog\nm.form()\n
As there is no default value at mandatory_str, you will be prompted automatically to fill up the field:
Then, full form appears:
"},{"location":"#form-with-paths","title":"Form with paths","text":"
We have a dict with some paths. Here is how it looks.
from pathlib import Path\nfrom mininterface import run, Tag\n\nm = run(title=\"My program\")\nmy_dictionary = {\n \"paths\": Tag(\"\", annotation=list[Path]),\n \"default_paths\": Tag([Path(\"/tmp\"), Path(\"/usr\")], annotation=list[Path])\n }\n\n# Edit values in a dialog\nm.form(my_dictionary)\n
m = run() out = m.form({ \"My choice\": Tag(choices=[\"one\", \"two\"], on_change=callback) })
"},{"location":"Facet/#mininterface.facet.Facet.submit--continue-here-immediately-after-clicking-on-a-radio-button","title":"continue here immediately after clicking on a radio button","text":""},{"location":"Mininterface/","title":"Mininterface","text":"
The base interface. You get one through mininterface.run which fills CLI arguments and config file to mininterface.env or you can create one directly (without benefiting from the CLI parsing).
Raise
Cancelled: A SystemExit based exception noting that the program exits without a traceback, ex. if user hits the escape.
Raise
InterfaceNotAvailable: Interface failed to init, ex. display not available in GUI.
Use scalars, enums, enum instances, objects like datetime, Paths or their list.
from enum import Enum\nfrom mininterface import run, Tag\n\nclass Color(Enum):\n RED = \"red\"\n GREEN = \"green\"\n BLUE = \"blue\"\n\nm = run()\nout = m.form({\n \"my_number\": 1,\n \"my_boolean\": True,\n \"my_enum\": Color,\n \"my_tagged\": Tag(\"\", name='Tagged value', description='Long hint'),\n \"my_path\": Path(\"/tmp\"),\n \"my_paths\": [Path(\"/tmp\")],\n \"My enum with default\": Color.BLUE\n})\n
Parameters:
Name Type Description Default formDataClass | Type[DataClass] | FormDict | None
We accept a dataclass type, a dataclass instance, a dict or None.
If dict, we expect a dict of {labels: value}. The form widget infers from the default value type. The dict can be nested, it can contain a subgroup. The value might be a Tag that allows you to add descriptions.
A checkbox example: {\"my label\": Tag(True, \"my description\")}
If None, the self.env is being used as a form, allowing the user to edit whole configuration. (Previously fetched from CLI and config file.)
Nonetitlestr
Optional form title
''submitstr | bool
Set the submit button text (by default 'Ok') or hide it with False.
True
Returns:
Name Type Description dataclassFormDict | DataClass | EnvClass
If the form is null, the output is self.env.
dataclassFormDict | DataClass | EnvClass
If the form is a dataclass type or a dataclass instance, the output is the dataclass instance.
dictFormDict | DataClass | EnvClass
If the form is a dict, the output is another dict.
Whereas the original dict stays intact (with the values updated), we return a new raw dict with all values resolved (all Tag objects are resolved to their value).
original = {\"my label\": Tag(True, \"my description\")}\noutput = m.form(original) # Sets the label to False in the dialog\n\n# Original dict was updated\nprint(original[\"my label\"]) # Tag(False, \"my description\")\n\n# Output dict is resolved, contains only raw values\nprint(output[\"my label\"]) # False\n
Why this behaviour? You need to do some validation, hence you put Tag objects in the input dict. Then, you just need to work with the values.
original = {\"my label\": Tag(True, \"my description\")}\noutput = m.form(original) # Sets the label to False in the dialog\noutput[\"my_label\"]\n
In the case you are willing to re-use the dict, you need not to lose the definitions, hence you end up with accessing via the .val.
original = {\"my label\": Tag(True, \"my description\")}\n\nfor i in range(10):\n m.form(original, f\"Attempt {i}\")\n print(\"The result\", original[\"my label\"].val)\n
Via the run function you get access to the CLI, possibly enriched from the config file. Then, you receive all data as m.env object and dialog methods in a proper UI.
graph LR\n subgraph mininterface\n run --> GUI\n run --> TUI\n run --> env\n CLI --> run\n id1[config file] --> CLI\n end\n program --> run\n
Use a common dataclass, a Pydantic BaseModel or an attrs model to store the configuration. Wrap it to the run function that returns an interface m. Access the configuration via m.env or use it to prompt the user m.is_yes(\"Is that alright?\").
There are a lot of supported types you can use, not only scalars and well-known objects (Path, datetime), but also functions, iterables (like list[Path]) and union types (like int | None). To do even more advanced things, stick the value to a powerful Tag or its subclasses. Ex. for a validation only, use its Validation alias.
At last, use Facet to tackle the interface from the back-end (m) or the front-end (Tag) side.
The immediate benefit is the type suggestions you see in an IDE. Imagine following code:
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n my_paths: list[Path]\n \"\"\" The user is forced to input Paths. \"\"\"\n\n\n@dataclass\nclass Dialog:\n my_number: int = 2\n \"\"\" A number \"\"\"\n
Now, accessing the main env will trigger the hint.
Calling the form with an empty parameter will trigger editing the main env
Putting there a dict will return the dict too.
Putting there a dataclass type causes it to be resolved.
Should you have a resolved dataclass instance, put it there.
As you see, its attributes are hinted alongside their description.
Should the dataclass cannot be easily investigated by the IDE (i.e. a required field), just annotate the output.
When invoked directly, it creates simple GUI dialogs.
$ mininterface --help\nusage: Mininterface [-h] [OPTIONS]\n\nSimple GUI dialog. Outputs the value the user entered.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 --alert STR Display the OK dialog with text. (default: '') \u2502\n\u2502 --ask STR Prompt the user to input a text. (default: '') \u2502\n\u2502 --ask-number STR Prompt the user to input a number. Empty input = 0. (default: '') \u2502\n\u2502 --is-yes STR Display confirm box, focusing yes. (default: '') \u2502\n\u2502 --is-no STR Display confirm box, focusing no. (default: '') \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
You can fetch a value to i.e. a bash script.
$ mininterface --ask-number \"What's your age?\" # GUI or TUI window invoked\n18\n
"},{"location":"Tag/","title":"Tag","text":"
Wrapper around a value that encapsulates a description, validation etc. When you provide a value to an interface, you may instead use this object.
Bridge between the input values and a UI widget. The widget is created with the help of this object, then transforms the value back (str to int conversion etc).
When the user submits the form, the values are validated (and possibly transformed) with a callback function. If the validation fails, user is prompted to edit the value. Return True if validation succeeded or False or an error message when it failed.
ValidationResult is a bool or the error message (that implicitly means it has failed).
def check(tag: Tag):\n if tag.val < 10:\n return \"The value must be at least 10\"\nm.form({\"number\", Tag(12, validation=check)})\n
Either use a custom callback function or mininterface.validators.
from mininterface.validators import not_empty\nm.form({\"number\", Tag(\"\", validation=not_empty)})\n# User cannot leave the field empty.\n
You may use the validation in a type annotation.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
NOTE Undocumented feature, we can return tuple [ValidationResult, FieldValue] to set the self.val.
Accepts a callback that launches whenever the value changes (if the validation succeeds). The callback runs while the dialog is still running. The return value of the callback is currently not used.
In the following example, we alter the heading title according to the chosen value.
from mininterface import run, Tag\n\ndef callback(tag: Tag):\n tag.facet.set_title(f\"Value changed to {tag.val}\")\n\nm = run()\nm.facet.set_title(\"Click the checkbox\")\nm.form({\n \"My choice\": Tag(choices=[\"one\", \"two\"], on_change=callback)\n})\n
You can denote the choices in many ways. Either put options in an iterable or to a dict {labels: value}. Values might be Tags as well.
See mininterface.choice or Tag.choices for examples.
"},{"location":"Types/","title":"Types","text":"
Various types are supported:
scalars
functions
well-known objects (Path, datetime)
iterables (like list[Path])
custom classes (somewhat)
union types (like int | None)
Take a look how it works with the variables organized in a dataclass:
from dataclasses import dataclass\nfrom pathlib import Path\n\nfrom mininterface import run\n\n\n@dataclass\nclass Env:\n my_number: int = 1\n \"\"\" A dummy number \"\"\"\n my_boolean: bool = True\n \"\"\" A dummy boolean \"\"\"\n my_conditional_number: int | None = None\n \"\"\" A number that can be null if left empty \"\"\"\n my_path: Path = Path(\"/tmp\")\n \"\"\" A dummy path \"\"\"\n\n\nm = run(Env) # m.env contains an Env instance\nm.form() # Prompt a dialog; m.form() without parameter edits m.env\nprint(m.env)\n# Env(my_number=1, my_boolean=True, my_path=PosixPath('/tmp'),\n# my_point=<__main__.Point object at 0x7ecb5427fdd0>)\n
Variables organized in a dict:
Along scalar types, there is (basic) support for common iterables or custom classes.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
Parameters:
Name Type Description Default checkCallable[[Tag], ValidationResult | tuple[ValidationResult, TagValue]]
Functions suitable for Tag validation. When the user submits a value whose validation fails, they are prompted to edit the value.
m = run()\nmy_dict = m.form({\"my_text\", Tag(\"\", validation=validators.not_empty)})\nmy_dict[\"my_text\"] # You can be sure the value is not empty here.\n
Note that alternatively to this module, you may validate with Pydantic or an attrs model.
Assures that Tag the user has written a value and did not let the field empty.
from mininterface import Tag, validators, run\n\nm = run()\nm.form({\"my_text\": Tag(\"\", validation=validators.not_empty)})\n# User cannot leave the string field empty.\n
When submitting an empty value, a warning appears:
Note that for Path, an empty string is converted to an empty Path('.'), hence '.' too is considered as an empty input and the user is not able to set '.' as a value. This does not seem to me as a bad behaviour as in CLI you clearly see the CWD, whereas in a UI the CWD is not evident.
Parameters:
Name Type Description Default tagTag required"},{"location":"Validation/#mininterface.validators.limit","title":"limit(maxOrMin=None, max_=None, lt=None, gt=None, transform=False)","text":"
Limit a number range or a string length.
Either use as limit(maximum) or limit(minimum, maximum).
Parameters:
Name Type Description Default maximumint
limit(maximum) \u2013 from zero (including) to maximum (including)
required minimumint
limit(minimum, maximum) \u2013 From minimum (including) to maximum (including)
required ltfloat | None
lesser than
Nonegtfloat | None
greater than
Nonetransformbool
If the value is not withing the limit, transform it to a boundary.
from mininterface import run, Tag\nfrom mininterface.validators import limit\n\nm = run()\nm.form({\"my_number\": Tag(2, validation=limit(1, 10, transform=True))})\n# Put there '50' \u2192 transformed to 10 and dialog reappears\n# with 'Value must be between 1 and 10.'\n
False"},{"location":"run/","title":"Run","text":"
The main access, start here. Wrap your configuration dataclass into run to access the interface. An interface is chosen automatically, with the preference of the graphical one, regressed to a text interface for machines without display. Besides, if given a configuration dataclass, the function enriches it with the CLI commands and possibly with the default from a config file if such exists. It searches the config file in the current working directory, with the program name ending on .yaml, ex: program.py will fetch ./program.yaml.
Parameters:
Name Type Description Default env_classType[EnvClass] | None
Dataclass with the configuration. Their values will be modified with the CLI arguments.
Noneask_on_empty_clibool
If program was launched with no arguments (empty CLI), invokes self.form() to edit the fields. (Withdrawn when ask_for_missing happens.)
$ program.py # omitting all parameters\n# Dialog for `number` and `text` appears\n$ program.py --number 3\n# No dialog appears\n
Falsetitlestr
The main title. If not set, taken from prog or program name.
''config_filePath | str | bool
File to load YAML to be merged with the configuration. You do not have to re-define all the settings in the config file, you can choose a few. If set to True (default), we try to find one in the current working dir, whose name stem is the same as the program's. Ex: program.py will search for program.yaml. If False, no config file is used.
Trueadd_verbositybool
Adds the verbose flag that automatically sets the level to logging.INFO (-v) or logging.DEBUG (-vv).
import logging\nlogger = logging.getLogger(__name__)\n\nm = run(Env, add_verbosity=True)\nlogger.info(\"Info shown\") # needs `-v` or `--verbose`\nlogger.debug(\"Debug not shown\") # needs `-vv`\n# $ program.py --verbose\n# Info shown\n
$ program.py --verbose\nInfo shown\n
Trueask_for_missingbool
If some required fields are missing at startup, we ask for them in a UI instead of program exit.
$ program.py # omitting --required-number\n# Dialog for `required_number` appears\n
TrueinterfaceType[Mininterface]
Which interface to prefer. By default, we use the GUI, the fallback is the TUI. See the full list of possible interfaces.
GuiInterface or TuiInterface Kwargs
The same as for argparse.ArgumentParser.
Returns:
Type Description Mininterface[EnvClass]
An interface, ready to be used.
You cay context manager the function by a with statement. The stdout will be redirected to the interface (ex. a GUI window).
with run(Env) as m:\n print(f\"Your important number is {m.env.important_number}\")\n boolean = m.is_yes(\"Is that alright?\")\n
"}]}
\ No newline at end of file
+{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Mininterface \u2013 access to GUI, TUI, CLI and config files","text":"
Write the program core, do not bother with the input/output.
Check out the code, which is surprisingly short, that displays such a window or its textual fallback.
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n \"\"\" This calculates something. \"\"\"\n\n my_flag: bool = False\n \"\"\" This switches the functionality \"\"\"\n\n my_number: int = 4\n \"\"\" This number is very important \"\"\"\n\nif __name__ == \"__main__\":\n m = run(Env, prog=\"My application\")\n m.form()\n # Attributes are suggested by the IDE\n # along with the hint text 'This number is very important'.\n print(m.env.my_number)\n
It was all the code you need. No lengthy blocks of code imposed by an external dependency. Besides the GUI/TUI, you receive powerful YAML-configurable CLI parsing.
$ ./hello.py --help\nusage: My application [-h] [-v] [--my-flag | --no-my-flag] [--my-number INT]\n\nThis calculates something.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 -v, --verbose Verbosity level. Can be used twice to increase. \u2502\n\u2502 --my-flag, --no-my-flag \u2502\n\u2502 This switches the functionality (default: False) \u2502\n\u2502 --my-number INT This number is very important (default: 4) \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
Loading config file is a piece of cake. Alongside program.py, put program.yaml and put there some of the arguments. They are seamlessly taken as defaults.
Check out several useful methods to handle user dialogues. Here we bound the interface to a with statement that redirects stdout directly to the window.
with run(Env) as m:\n print(f\"Your important number is {m.env.my_number}\")\n boolean = m.is_yes(\"Is that alright?\")\n
Wrapper between the tyro argparse replacement and tkinter_form that converts dicts into a GUI.
Writing a small and useful program might be a task that takes fifteen minutes. Adding a CLI to specify the parameters is not so much overhead. But building a simple GUI around it? HOURS! Hours spent on researching GUI libraries, wondering why the Python desktop app ecosystem lags so far behind the web world. All you need is a few input fields validated through a clickable window... You do not deserve to add hundred of lines of the code just to define some editable fields. Mininterface is here to help.
The config variables needed by your program are kept in cozy dataclasses. Write less! The syntax of tyro does not require any overhead (as its argparse alternatives do). You just annotate a class attribute, append a simple docstring and get a fully functional application: * Call it as program.py --help to display full help. * Use any flag in CLI: program.py --my-flag causes env.my_flag be set to True. * The main benefit: Launch it without parameters as program.py to get a full working window with all the flags ready to be edited. * Running on a remote machine? Automatic regression to the text interface.
from typing import Annotated\nfrom dataclasses import dataclass\nfrom mininterface.validators import not_empty\nfrom mininterface import run, Tag, Validation\n\n@dataclass\nclass NestedEnv:\n another_number: int = 7\n \"\"\" This field is nested \"\"\"\n\n@dataclass\nclass Env:\n nested_config: NestedEnv\n\n mandatory_str: str\n \"\"\" As there is no default value, you will be prompted automatically to fill up the field \"\"\"\n\n my_number: int | None = None\n \"\"\" This is not just a dummy number, if left empty, it is None. \"\"\"\n\n my_string: str = \"Hello\"\n \"\"\" A dummy string \"\"\"\n\n my_flag: bool = False\n \"\"\" Checkbox test \"\"\"\n\n my_validated: Annotated[str, Validation(not_empty)] = \"hello\"\n \"\"\" A validated field \"\"\"\n\nm = run(Env, title=\"My program\")\n# See some values\nprint(m.env.nested_config.another_number) # 7\nprint(m.env)\n# Env(nested_config=NestedEnv(another_number=7), my_number=5, my_string='Hello', my_flag=False, my_validated='hello')\n\n# Edit values in a dialog\nm.form()\n
As the attribute mandatory_str requires a value, a prompt appears automatically:
Then, full form appears:
"},{"location":"#form-with-paths","title":"Form with paths","text":"
We have a dict with some paths. Here is how it looks.
from pathlib import Path\nfrom mininterface import run, Tag\n\nm = run(title=\"My program\")\nmy_dictionary = {\n \"paths\": Tag(\"\", annotation=list[Path]),\n \"default_paths\": Tag([Path(\"/tmp\"), Path(\"/usr\")], annotation=list[Path])\n }\n\n# Edit values in a dialog\nm.form(my_dictionary)\n
m = run() out = m.form({ \"My choice\": Tag(choices=[\"one\", \"two\"], on_change=callback) })
"},{"location":"Facet/#mininterface.facet.Facet.submit--continue-here-immediately-after-clicking-on-a-radio-button","title":"continue here immediately after clicking on a radio button","text":""},{"location":"Helper-types/","title":"Helper types","text":""},{"location":"Helper-types/#mininterface.tag.ValidationResult","title":"ValidationResult = bool | ErrorMessage","text":"
Callback validation result is either boolean or an error message.
Any dataclass. Its instance will be available through [miniterface.env] after CLI parsing.
"},{"location":"Interfaces/","title":"Interfaces","text":""},{"location":"Interfaces/#all-possible-interfaces","title":"All possible interfaces","text":"
Normally, you get an interface through mininterface.run but if you do not wish to parse CLI and config file, you can invoke one directly from mininterface.interfaces import *.
Apart from the default Mininterface, the base interface the others are fully compatible with, several interfaces exist:
How to invoke a specific interface.
from mininterface.interfaces import TuiInterface\n\nwith TuiInterface(\"My program\") as m:\n number = m.ask_number(\"Returns number\")\n
The base interface. You get one through mininterface.run which fills CLI arguments and config file to mininterface.env or you can create one directly (without benefiting from the CLI parsing).
Raise
Cancelled: A SystemExit based exception noting that the program exits without a traceback, ex. if user hits the escape.
Raise
InterfaceNotAvailable: Interface failed to init, ex. display not available in GUI.
Use scalars, enums, enum instances, objects like datetime, Paths or their list.
from enum import Enum\nfrom mininterface import run, Tag\n\nclass Color(Enum):\n RED = \"red\"\n GREEN = \"green\"\n BLUE = \"blue\"\n\nm = run()\nout = m.form({\n \"my_number\": 1,\n \"my_boolean\": True,\n \"my_enum\": Color,\n \"my_tagged\": Tag(\"\", name='Tagged value', description='Long hint'),\n \"my_path\": Path(\"/tmp\"),\n \"my_paths\": [Path(\"/tmp\")],\n \"My enum with default\": Color.BLUE\n})\n
Parameters:
Name Type Description Default formDataClass | Type[DataClass] | FormDict | None
We accept a dataclass type, a dataclass instance, a dict or None.
If dict, we expect a dict of {labels: value}. The form widget infers from the default value type. The dict can be nested, it can contain a subgroup. The value might be a Tag that allows you to add descriptions.
A checkbox example: {\"my label\": Tag(True, \"my description\")}
If None, the self.env is being used as a form, allowing the user to edit whole configuration. (Previously fetched from CLI and config file.)
Nonetitlestr
Optional form title
''submitstr | bool
Set the submit button text (by default 'Ok') or hide it with False.
True
Returns:
Name Type Description dataclassFormDict | DataClass | EnvClass
If the form is null, the output is self.env.
dataclassFormDict | DataClass | EnvClass
If the form is a dataclass type or a dataclass instance, the output is the dataclass instance.
dictFormDict | DataClass | EnvClass
If the form is a dict, the output is another dict.
Whereas the original dict stays intact (with the values updated), we return a new raw dict with all values resolved (all Tag objects are resolved to their value).
original = {\"my label\": Tag(True, \"my description\")}\noutput = m.form(original) # Sets the label to False in the dialog\n\n# Original dict was updated\nprint(original[\"my label\"]) # Tag(False, \"my description\")\n\n# Output dict is resolved, contains only raw values\nprint(output[\"my label\"]) # False\n
Why this behaviour? You need to do some validation, hence you put Tag objects in the input dict. Then, you just need to work with the values.
original = {\"my label\": Tag(True, \"my description\")}\noutput = m.form(original) # Sets the label to False in the dialog\noutput[\"my_label\"]\n
In the case you are willing to re-use the dict, you need not to lose the definitions, hence you end up with accessing via the .val.
original = {\"my label\": Tag(True, \"my description\")}\n\nfor i in range(10):\n m.form(original, f\"Attempt {i}\")\n print(\"The result\", original[\"my label\"].val)\n
Via the run function you get access to the CLI, possibly enriched from the config file. Then, you receive all data as m.env object and dialog methods in a proper UI.
graph LR\n subgraph mininterface\n run --> GUI\n run --> TUI\n run --> env\n CLI --> run\n id1[config file] --> CLI\n end\n program --> run\n
Use a common dataclass, a Pydantic BaseModel or an attrs model to store the configuration. Wrap it to the run function that returns an interface m. Access the configuration via m.env or use it to prompt the user m.is_yes(\"Is that alright?\").
There are a lot of supported types you can use, not only scalars and well-known objects (Path, datetime), but also functions, iterables (like list[Path]) and union types (like int | None). To do even more advanced things, stick the value to a powerful Tag or its subclasses. Ex. for a validation only, use its Validation alias.
At last, use Facet to tackle the interface from the back-end (m) or the front-end (Tag) side.
The immediate benefit is the type suggestions you see in an IDE. Imagine following code:
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n my_paths: list[Path]\n \"\"\" The user is forced to input Paths. \"\"\"\n\n\n@dataclass\nclass Dialog:\n my_number: int = 2\n \"\"\" A number \"\"\"\n
Now, accessing the main env will trigger the hint.
Calling the form with an empty parameter will trigger editing the main env
Putting there a dict will return the dict too.
Putting there a dataclass type causes it to be resolved.
Should you have a resolved dataclass instance, put it there.
As you see, its attributes are hinted alongside their description.
Should the dataclass cannot be easily investigated by the IDE (i.e. a required field), just annotate the output.
When invoked directly, it creates simple GUI dialogs.
$ mininterface --help\nusage: Mininterface [-h] [OPTIONS]\n\nSimple GUI dialog. Outputs the value the user entered.\n\n\u256d\u2500 options \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n\u2502 -h, --help show this help message and exit \u2502\n\u2502 --alert STR Display the OK dialog with text. (default: '') \u2502\n\u2502 --ask STR Prompt the user to input a text. (default: '') \u2502\n\u2502 --ask-number STR Prompt the user to input a number. Empty input = 0. (default: '') \u2502\n\u2502 --is-yes STR Display confirm box, focusing yes. (default: '') \u2502\n\u2502 --is-no STR Display confirm box, focusing no. (default: '') \u2502\n\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n
You can fetch a value to i.e. a bash script.
$ mininterface --ask-number \"What's your age?\" # GUI or TUI window invoked\n18\n
What if I need to use my program Special placeholder class SubcommandPlaceholder. This special class let the user to choose the subcommands via UI, while still benefiniting from default CLI arguments.
Just before the form appears. As the __post_init__ method is not guaranteed to run just once (internal CLI behaviour), you are welcome to override this method instead. You can use self._facet from within.
Use this placeholder to choose the subcomannd via a UI.
"},{"location":"Tag/","title":"Tag","text":"
Wrapper around a value that encapsulates a description, validation etc. When you provide a value to an interface, you may instead use this object.
Bridge between the input values and a UI widget. The widget is created with the help of this object, then transforms the value back (str to int conversion etc).
When the user submits the form, the values are validated (and possibly transformed) with a callback function. If the validation fails, user is prompted to edit the value. Return True if validation succeeded or False or an error message when it failed.
ValidationResult is a bool or the error message (that implicitly means it has failed).
def check(tag: Tag):\n if tag.val < 10:\n return \"The value must be at least 10\"\nm.form({\"number\", Tag(12, validation=check)})\n
Either use a custom callback function or mininterface.validators.
from mininterface.validators import not_empty\nm.form({\"number\", Tag(\"\", validation=not_empty)})\n# User cannot leave the field empty.\n
You may use the validation in a type annotation.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
NOTE Undocumented feature, we can return tuple [ValidationResult, FieldValue] to set the self.val.
Accepts a callback that launches whenever the value changes (if the validation succeeds). The callback runs while the dialog is still running. The return value of the callback is currently not used.
In the following example, we alter the heading title according to the chosen value.
from mininterface import run, Tag\n\ndef callback(tag: Tag):\n tag.facet.set_title(f\"Value changed to {tag.val}\")\n\nm = run()\nm.facet.set_title(\"Click the checkbox\")\nm.form({\n \"My choice\": Tag(choices=[\"one\", \"two\"], on_change=callback)\n})\n
Take a look how it works with the variables organized in a dataclass:
from dataclasses import dataclass\nfrom pathlib import Path\n\nfrom mininterface import run\n\n\n@dataclass\nclass Env:\n my_number: int = 1\n \"\"\" A dummy number \"\"\"\n my_boolean: bool = True\n \"\"\" A dummy boolean \"\"\"\n my_conditional_number: int | None = None\n \"\"\" A number that can be null if left empty \"\"\"\n my_path: Path = Path(\"/tmp\")\n \"\"\" A dummy path \"\"\"\n\n\nm = run(Env) # m.env contains an Env instance\nm.form() # Prompt a dialog; m.form() without parameter edits m.env\nprint(m.env)\n# Env(my_number=1, my_boolean=True, my_path=PosixPath('/tmp'),\n# my_point=<__main__.Point object at 0x7ecb5427fdd0>)\n
Variables organized in a dict:
Along scalar types, there is (basic) support for common iterables or custom classes.
from mininterface import Tag, Validation\n@dataclass\nclass Env:\n my_text: Annotated[str, Validation(not_empty) = \"will not be emtpy\"\n\n # which is an alias for:\n # my_text: Annotated[str, Tag(validation=not_empty)] = \"will not be emtpy\"\n
Parameters:
Name Type Description Default checkCallable[[Tag], ValidationResult | tuple[ValidationResult, TagValue]]
Functions suitable for Tag validation. When the user submits a value whose validation fails, they are prompted to edit the value.
m = run()\nmy_dict = m.form({\"my_text\", Tag(\"\", validation=validators.not_empty)})\nmy_dict[\"my_text\"] # You can be sure the value is not empty here.\n
Note that alternatively to this module, you may validate with Pydantic or an attrs model.
Assures that Tag the user has written a value and did not let the field empty.
from mininterface import Tag, validators, run\n\nm = run()\nm.form({\"my_text\": Tag(\"\", validation=validators.not_empty)})\n# User cannot leave the string field empty.\n
When submitting an empty value, a warning appears:
Note that for Path, an empty string is converted to an empty Path('.'), hence '.' too is considered as an empty input and the user is not able to set '.' as a value. This does not seem to me as a bad behaviour as in CLI you clearly see the CWD, whereas in a UI the CWD is not evident.
Parameters:
Name Type Description Default tagTag required"},{"location":"Validation/#mininterface.validators.limit","title":"limit(maxOrMin=None, max_=None, lt=None, gt=None, transform=False)","text":"
Limit a number range or a string length.
Either use as limit(maximum) or limit(minimum, maximum).
Parameters:
Name Type Description Default maximumint
limit(maximum) \u2013 from zero (including) to maximum (including)
required minimumint
limit(minimum, maximum) \u2013 From minimum (including) to maximum (including)
required ltfloat | None
lesser than
Nonegtfloat | None
greater than
Nonetransformbool
If the value is not within the limit, transform it to a boundary.
from mininterface import run, Tag\nfrom mininterface.validators import limit\n\nm = run()\nm.form({\"my_number\": Tag(2, validation=limit(1, 10, transform=True))})\n# Put there '50' \u2192 transformed to 10 and dialog reappears\n# with 'Value must be between 1 and 10.'\n
False"},{"location":"run/","title":"Run","text":"
The main access, start here. Wrap your configuration dataclass into run to access the interface. An interface is chosen automatically, with the preference of the graphical one, regressed to a text interface for machines without display. Besides, if given a configuration dataclass, the function enriches it with the CLI commands and possibly with the default from a config file if such exists. It searches the config file in the current working directory, with the program name ending on .yaml, ex: program.py will fetch ./program.yaml.
Parameters:
Name Type Description Default env_or_listType[EnvClass] | list[Type[Command]] | None
dataclass Dataclass with the configuration. Their values will be modified with the CLI arguments.
list of Commands let you create multiple commands within a single program, each with unique options.
None You need just the dialogs, no CLI/config file parsing.
Noneask_on_empty_clibool
If program was launched with no arguments (empty CLI), invokes self.form() to edit the fields. (Withdrawn when ask_for_missing happens.)
$ program.py # omitting all parameters\n# Dialog for `number` and `text` appears\n$ program.py --number 3\n# No dialog appears\n
Falsetitlestr
The main title. If not set, taken from prog or program name.
''config_filePath | str | bool
File to load YAML to be merged with the configuration. You do not have to re-define all the settings in the config file, you can choose a few. If set to True (default), we try to find one in the current working dir, whose name stem is the same as the program's. Ex: program.py will search for program.yaml. If False, no config file is used.
Trueadd_verbositybool
Adds the verbose flag that automatically sets the level to logging.INFO (-v) or logging.DEBUG (-vv).
import logging\nlogger = logging.getLogger(__name__)\n\nm = run(Env, add_verbosity=True)\nlogger.info(\"Info shown\") # needs `-v` or `--verbose`\nlogger.debug(\"Debug not shown\") # needs `-vv`\n# $ program.py --verbose\n# Info shown\n
$ program.py --verbose\nInfo shown\n
Trueask_for_missingbool
If some required fields are missing at startup, we ask for them in a UI instead of program exit.
Which interface to prefer. By default, we use the GUI, the fallback is the TUI. You may write \"gui\" or \"tui\" literal or pass a specific Mininterface type, see the full list of possible interfaces.
NoneargsOptional[Sequence[str]]
Parse arguments from a sequence instead of the command line.
None
Kwargs: The same as for argparse.ArgumentParser.
Returns:
Type Description Mininterface[EnvClass]
An interface, ready to be used.
You cay context manager the function by a with statement. The stdout will be redirected to the interface (ex. a GUI window).
from dataclasses import dataclass\nfrom mininterface import run\n\n@dataclass\nclass Env:\n my_number: int = 4\n\nwith run(Env) as m:\n print(f\"Your important number is {m.env.my_number}\")\n boolean = m.is_yes(\"Is that alright?\")\n
"}]}
\ No newline at end of file
diff --git a/sitemap.xml.gz b/sitemap.xml.gz
index 9ed08e1..a72535d 100644
Binary files a/sitemap.xml.gz and b/sitemap.xml.gz differ