Skip to content

Commit

Permalink
:memos: update EXAMPLES
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Oct 24, 2024
1 parent 78f6342 commit 9bcdfba
Show file tree
Hide file tree
Showing 16 changed files with 153 additions and 87 deletions.
34 changes: 19 additions & 15 deletions README-EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ from arclet.alconna import Alconna, Option, Subcommand, Args

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

Expand Down Expand Up @@ -75,15 +75,19 @@ Example of Callback Executor:

```python
# callback.py
from arclet.alconna import Alconna, Args
from arclet.alconna import Alconna, ArgsBase

class CallbackArgs(ArgsBase):
foo: int
bar: str

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

@alc.bind()
def callback(foo: int, bar: str):
print(f"foo: {foo}")
print(f"bar: {bar}")
print(bar * foo)
def cb(args: CallbackArgs):
print(f"foo: {args.foo}")
print(f"bar: {args.bar}")
print(args.bar * args.foo)

if __name__ == "__main__":
alc()
Expand All @@ -103,7 +107,7 @@ Example of Type Conversion:
from arclet.alconna import Alconna, Args
from pathlib import Path

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

@read.bind()
def cb(data: bytes):
Expand All @@ -127,9 +131,9 @@ from arclet.alconna import Alconna, Args, Option, Subcommand, store_true, count,

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

Expand All @@ -154,7 +158,7 @@ Example of Command Shortcut:
# shortcut.py
from arclet.alconna import Alconna, Args

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

@alc.bind()
Expand All @@ -177,7 +181,7 @@ Example of Command Completion:
# completion.py
from arclet.alconna import Alconna, Args, Option

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

if __name__ == "__main__":
alc()
Expand All @@ -198,7 +202,7 @@ 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 = Alconna("test", Args.foo(Annotated[int, lambda x: x % 2 == 0]))
alc.parse("test 2")
alc.parse("test 3")

Expand All @@ -212,9 +216,9 @@ Example of FuzzyMatch:

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

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

if __name__ == "__main__":
alc()
Expand Down
34 changes: 19 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ from arclet.alconna import Alconna, Option, Subcommand, Args

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

Expand Down Expand Up @@ -73,15 +73,19 @@ QQ 交流群: [链接](https://jq.qq.com/?_wv=1027&k=PUPOnCSH)
执行回调示范:
```python
# callback.py
from arclet.alconna import Alconna, Args
from arclet.alconna import Alconna, ArgsBase

class CallbackArgs(ArgsBase):
foo: int
bar: str

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

@alc.bind()
def cb(foo: int, bar: str):
print(f"foo: {foo}")
print(f"bar: {bar}")
print(bar * foo)
def cb(args: CallbackArgs):
print(f"foo: {args.foo}")
print(f"bar: {args.bar}")
print(args.bar * args.foo)

if __name__ == '__main__':
alc()
Expand All @@ -100,7 +104,7 @@ hellohello
from arclet.alconna import Alconna, Args
from pathlib import Path

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

@read.bind()
def cb(data: bytes):
Expand All @@ -124,9 +128,9 @@ from arclet.alconna import Alconna, Args, Option, Subcommand, store_true, count,

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

Expand All @@ -151,7 +155,7 @@ $ python component.py /home/arclet -vvvv -f1 -f2 -f3 sub bar
# shortcut.py
from arclet.alconna import Alconna, Args

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

@alc.bind()
Expand All @@ -174,7 +178,7 @@ hello world!
# complete.py
from arclet.alconna import Alconna, Args, Option

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

if __name__ == '__main__':
alc()
Expand All @@ -195,7 +199,7 @@ typing 支持示范:
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 = Alconna("test", Args.foo(Annotated[int, lambda x: x % 2 == 0]))
alc.parse("test 2")
alc.parse("test 3")

Expand All @@ -208,9 +212,9 @@ ParamsUnmatched: 参数 3 不正确
模糊匹配示范:
```python
# fuzzy.py
from arclet.alconna import Alconna, CommandMeta, Arg
from arclet.alconna import Alconna, Config, Arg

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

if __name__ == '__main__':
alc()
Expand Down
8 changes: 4 additions & 4 deletions exam1.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
api_list = ["saucenao", "ascii2d", "ehentai", "iqdb", "tracemoe"]
alc = Alconna(
"setu",
Args['content', str],
Option("use", Args['api', api_list], help_text="选择搜图使用的 API"),
Args.content(str),
Option("use", Args.api(api_list), help_text="选择搜图使用的 API"),
Option("count", Arg("num", int), help_text="设置每次搜图展示的最多数量"),
Option("--similarity|-s", Args["val", float], help_text="设置相似度过滤的值", default=OptionResult(args={"val": 0.5})),
Option("--timeout|-t", Args["sec", int], help_text="设置超时时间", default=OptionResult(args={"sec": 60})),
Option("--similarity|-s", Args.val(float), help_text="设置相似度过滤的值", default=OptionResult(args={"val": 0.5})),
Option("--timeout|-t", Args.sec(int), help_text="设置超时时间", default=OptionResult(args={"sec": 60})),
Metadata(
"依据输入的图片寻找可能的原始图片来源",
usage="可以传入图片, 也可以是图片的网络链接",
Expand Down
26 changes: 26 additions & 0 deletions exam8.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from arclet.alconna.args import ArgsBase, Args, arg_field
from arclet.alconna import Alconna


class Foo(ArgsBase):
foo: str
bar: int = arg_field(42, kw_only=True)


alc = Alconna("test", Foo)


@alc.bind()
def cb(args: Foo):
print(args.foo, args.bar)


print(alc.parse("test abc bar=123"))


class Bar(ArgsBase):
foo: tuple[str, ...] = arg_field(multiple=True)


alc2 = Alconna("test2", Bar)
print(alc2.parse("test2 abc def ghi"))
2 changes: 2 additions & 0 deletions example/calculate.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@
Arg("b", NUMBER),
)


@alc.bind()
def calc(a, action, b):
print(action(a, b))


alc.parse("calc 123 + 456")
alc.parse("calc 4.56 mul 8")
19 changes: 9 additions & 10 deletions example/endpoint.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
from dataclasses import asdict, dataclass
from arclet.alconna import Alconna, ArgsBase, Args, Option

from arclet.alconna import Alconna, Args, KeyWordVar, Option, UnpackVar


@dataclass
class User:
class User(ArgsBase, kw_only=True, seps="&"):
name: str
age: int


user_ = Alconna(
"user",
Option("list"),
Option("add", Args["user", UnpackVar(User, kw_only=True)].separate("&"), separators="?"),
Option("del", Args["name", KeyWordVar(str)], separators="?"),
Option("add", User, separators="?"),
Option("del", Args.name(str, kw_only=True), separators="?"),
separators="/"
)

Expand All @@ -33,9 +30,10 @@ def handle(send: str):
if not res.matched:
return {"result": "Err", "msg": res.error_info}
if res.find("list"):
return {"result": "Ok", "msg": "", "data": [asdict(u) for u in users.values()]}
elif user := res.query[User]("add.user"):
users[user.name] = user
return {"result": "Ok", "msg": "", "data": [u.dump() for u in users.values()]}
elif user := res.query[dict]("add.args"):
_user = User(**user)
users[_user.name] = _user
return {"result": "Ok", "msg": ""}
elif name := res.query[str]("del.name"):
if name not in users:
Expand All @@ -45,5 +43,6 @@ def handle(send: str):
else:
return {"result": "Err", "msg": "Unknown API"}


for s in sends:
print(handle(s))
11 changes: 6 additions & 5 deletions example/exec_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@

from nepattern import AnyString

from arclet.alconna import Alconna, Args, Arparma, CommandMeta, Field, MultiVar, Option
from arclet.alconna import Alconna, Args, Arparma, Metadata, Option

alc = Alconna(
"exec",
Args["code", MultiVar(AnyString), Field(completion=lambda: "print(1+1)")] / "\n",
Args.code(AnyString, multiple=True, completion=lambda: "print(1+1)", seps="\n"),
Option("--pure-text"),
Option("--no-output"),
Option("--out", Args["name", str, "res"]),
meta=CommandMeta("exec python code", example="exec\\nprint(1+1)"),
Option("--out", Args.name(str, "res")),
Metadata("exec python code", example="exec\\nprint(1+1)"),
)

alc.shortcut(
"echo",
{"command": "exec --pure-text\nprint(\\'{*}\\')"},
{"command": "exec --pure-text\nprint('{*}')"},
)

alc.shortcut(
Expand Down Expand Up @@ -59,6 +59,7 @@ def exec_code(result: Arparma):
finally:
sys.stdout = _to


print(exec_code(alc.parse("echo 1234")))
print(exec_code(alc.parse("sin30")))
print(
Expand Down
8 changes: 4 additions & 4 deletions example/exec_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from sqlite3 import connect
from typing import Optional

from arclet.alconna import Alconna, Arg, KeyWordVar, MultiVar, Option
from arclet.alconna import Alconna, Args, Option

db = connect('example.db')

Expand All @@ -12,9 +12,9 @@

select = Alconna(
"SELECT",
Arg("columns", MultiVar(str)),
Option("FROM", Arg("table", str, field="UNKNOWN")),
Option("WHERE", Arg("conditions", MultiVar(KeyWordVar(str)))),
Args.columns(str, multiple=True),
Option("FROM", Args.table(str, "UNKNOWN")),
Option("WHERE", Args.conditions(str, multiple=True, kw_only=True)),
)


Expand Down
4 changes: 3 additions & 1 deletion example/img_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,18 @@ def __repr__(self):
np.to_text = lambda x: x.text if x.__class__ is Text else None
alc = Alconna(
"search",
Args["img?", Image]
Args.img(Image, optional=True),
)


@alc.bind()
def search(img: Optional[Image] = None):
if not img:
print("Please input your image")
else:
print(f"Searching {img.src} ...")


alc.parse([Text("search")])
alc.parse([Text("search"), Image("https://www.example.com/img")])
alc.parse([Text("search"), At(12345)])
Loading

0 comments on commit 9bcdfba

Please sign in to comment.