Skip to main content

A High-performance, Generality, Humane Command Line Arguments Parser Library.

Project description

Alconna

Alconna latest release Licence PyPI PyPI - Python Version FOSSA Status

简体中文|English

About

Alconna is a powerful cli tool for parsing message chain or other raw message data. It is an overload version of CommandAnalysis, affiliated to ArcletProject.

Alconna has a large number of built-in components and complex parsing functions. But do not afraid, you can use it as a simple command parser.

Installation

pip

$ pip install --upgrade arclet-alconna
$ pip install --upgrade arclet-alconna[full]

Documentation

Official Document : 👉Link

Relevant Document : 📚Docs

A Simple Example

from arclet.alconna import Alconna, Option, Subcommand, Args

cmd = Alconna(
    "/pip",
    Subcommand("install", Option("-U|--upgrade"), Args["pak", str]),
    Option("list")
)

result = cmd.parse("/pip install numpy --upgrade") # This method returns an 'Arparma' class instance.
print(result.query('install'))  # Or result.install

Output as follows:

value=None args={'pak': 'numpy'} options={'upgrade': value=Ellipsis args={}} subcommands={}

Communication

QQ Group: Link

Features

  • High Performance. On i5-10210U, performance is about 71000~289000 msg/s; test script: benchmark
  • Intuitive way to create command components
  • Powerful Automatic Type Parse and Conversion
  • Customizable Help Text Formatter and Control of Command Analyser
  • i18n Support
  • Cache of input command for quick response of repeated command
  • Easy-to-use Construct and Usage of Command Shortcut
  • Can bind callback function to execute after command parsing
  • Can create command completion session to implement multi-round continuous completion prompt
  • Various Features (FuzzyMatch, Output Capture, etc.)

Example of Callback Executor:

# callback.py
from arclet.alconna import Alconna, Args

alc = Alconna("callback", Args["foo", int]["bar", str])

@alc.bind()
def callback(foo: int, bar: str):
    print(f"foo: {foo}")
    print(f"bar: {bar}")
    print(bar * foo)
    
if __name__ == "__main__":
    alc()
$ python callback.py 3 hello
foo: 3
bar: hello
hellohellohello

Example of Type Conversion:

from arclet.alconna import Alconna, Args
from pathlib import Path

read = Alconna("read", Args["data", bytes])

@read.bind()
def cb(data: bytes):
    print(type(data))

read.parse(["read", b'hello'])
read.parse("read test_fire.py")
read.parse(["read", Path("test_fire.py")])

'''
<class 'bytes'>
<class 'bytes'>
<class 'bytes'>
'''

Example of Component creation:

# component.py
from arclet.alconna import Alconna, Args, Option, Subcommand, store_true, count, append

alc = Alconna(
    "component",
    Args["path", str],
    Option("--verbose|-v", action=count),
    Option("-f", Args["flag", str], compact=True, action=append),
    Subcommand("sub", Option("bar", action=store_true, default=False))
)

if __name__ == '__main__':
    res = alc()
    print(res.query("path"))
    print(res.query("verbose.value"))
    print(res.query("f.flag"))
    print(res.query("sub"))
$ python component.py /home/arclet -vvvv -f1 -f2 -f3 sub bar
/home/arclet
4
['1', '2', '3']
(value=Ellipsis args={} options={'bar': (value=True args={})} subcommands={})

Example of Command Shortcut:

# shortcut.py
from arclet.alconna import Alconna, Args

alc = Alconna("eval", Args["content", str])
alc.shortcut("echo", {"command": "eval print(\\'{*}\\')"})

@alc.bind()
def cb(content: str):
    eval(content, {}, {})

if __name__ == '__main__':
    alc()
$ python shortcut.py eval print(\"hello world\")
hello world
$ python shortcut.py echo hello world!
hello world!

Example of Command Completion:

# completion.py
from arclet.alconna import Alconna, Args, Option

alc = Alconna("complete", Args["bar", int]) + Option("foo") + Option("fool")

if __name__ == "__main__":
    alc()
$ python completion.py ?
suggest input follows:
* bar: int
* --help
* -h
* foo
* fool

Example of typing Support:

from typing import Annotated  # or typing_extensions.Annotated
from arclet.alconna import Alconna, Args

alc = Alconna("test", Args.foo[Annotated[int, lambda x: x % 2 == 0]])
alc.parse("test 2")
alc.parse("test 3")

'''
'foo': 2
ParamsUnmatched: param 3 is incorrect
'''

Example of FuzzyMatch:

# fuzzy.py
from arclet.alconna import Alconna, CommandMeta, Arg

alc = Alconna('!test_fuzzy', Arg("foo", str), meta=CommandMeta(fuzzy_match=True))

if __name__ == "__main__":
    alc()
$ python fuzzy.py /test_fuzzy foo bar
/test_fuzy not matched. Are you mean "!test_fuzzy"?

Examples

Name File
Calculate calculate.py
Execute exec_code.py
Request Route endpoint.py
Image Search img_search.py
PIP pip.py
Database Query exec_sql.py

License

Alconna is licensed under the MIT License.

FOSSA Status

Acknowledgement

JetBrains: Support Authorize for PyCharm

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

arclet_alconna-1.8.43.tar.gz (80.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

arclet_alconna-1.8.43-py3-none-any.whl (77.1 kB view details)

Uploaded Python 3

File details

Details for the file arclet_alconna-1.8.43.tar.gz.

File metadata

  • Download URL: arclet_alconna-1.8.43.tar.gz
  • Upload date:
  • Size: 80.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: pdm/2.25.5 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for arclet_alconna-1.8.43.tar.gz
Algorithm Hash digest
SHA256 23c89d334f4d44e2130f1abc63d8641ac39be9009be023ebd08c2739bbef42c9
MD5 2d4cae08a686c8f9f7cf97d7c967f141
BLAKE2b-256 3e4ebee9056fac9fbd24d45eb8023ee44949d15bae7c680fa6a2e4a3447c87cd

See more details on using hashes here.

File details

Details for the file arclet_alconna-1.8.43-py3-none-any.whl.

File metadata

  • Download URL: arclet_alconna-1.8.43-py3-none-any.whl
  • Upload date:
  • Size: 77.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: pdm/2.25.5 CPython/3.12.3 Linux/6.11.0-1018-azure

File hashes

Hashes for arclet_alconna-1.8.43-py3-none-any.whl
Algorithm Hash digest
SHA256 fd38ee4ca6404f7b698be8d9ec47248f9a95008d4d80c824375811ef5183d2c6
MD5 275cfdf3008b13e2b229e67e71ecef08
BLAKE2b-256 2960ed738f7917d2bbb714c3464a8288fed2b381a1c33180396f6d7ad2e43b45

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page