optfunc2 0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2016 The Python Packaging Authority (PyPA)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7
+ of the Software, and to permit persons to whom the Software is furnished to do
8
+ so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
optfunc2-0.1/PKG-INFO ADDED
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.1
2
+ Name: optfunc2
3
+ Version: 0.1
4
+ Summary: Generate options from function.
5
+ Author-email: bajeer <z_bajer@yeah.net>
6
+ Maintainer-email: bajeer <z_bajer@yeah.net>
7
+ License: Copyright (c) 2016 The Python Packaging Authority (PyPA)
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
10
+ this software and associated documentation files (the "Software"), to deal in
11
+ the Software without restriction, including without limitation the rights to
12
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
13
+ of the Software, and to permit persons to whom the Software is furnished to do
14
+ so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Project-URL: Homepage, https://gitee.com/z-bajer/autocall
28
+ Project-URL: Bug Reports, https://gitee.com/z-bajer/autocall/issues
29
+ Project-URL: Source, https://gitee.com/z-bajer/autocall
30
+ Keywords: call,function,option
31
+ Classifier: Development Status :: 3 - Alpha
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Topic :: Software Development
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.7
37
+ Classifier: Programming Language :: Python :: 3.8
38
+ Classifier: Programming Language :: Python :: 3.9
39
+ Classifier: Programming Language :: Python :: 3.10
40
+ Classifier: Programming Language :: Python :: 3.11
41
+ Classifier: Programming Language :: Python :: 3.12
42
+ Classifier: Programming Language :: Python :: 3.13
43
+ Classifier: Programming Language :: Python :: 3.14
44
+ Classifier: Programming Language :: Python :: 3 :: Only
45
+ Requires-Python: >=3.7
46
+ Description-Content-Type: text/markdown
47
+ License-File: LICENSE.txt
48
+ Provides-Extra: dev
49
+ Requires-Dist: check-manifest; extra == "dev"
50
+ Provides-Extra: test
51
+ Requires-Dist: coverage; extra == "test"
52
+
53
+ # Call function directly in cmd line
54
+
55
+ #### Features
56
+ 1. Allow user call functions directly in command line.
57
+ 2. Generate help tips automatically.
58
+ 3. Add default called functions if not function was specific.
59
+
60
+ #### Notice
61
+ 1. It's better to add argument type for each autocall functions.
62
+ 2. Function with @optfunc_default has @optfunc implicitly.
63
+ 3. Arguments of function with @optfunc_default should be optional or no argument.
64
+ 4. Not support two type of variadic arguments.
65
+
66
+ #### TODO
67
+ 1. Beautiful print.
68
+
69
+ #### Code example
70
+ ``` python
71
+ from optfunc import *
72
+
73
+ @optfunc
74
+ def arg_test_positional_only(pos_only0, pos_only1: int, pos_only2 = 5, pos_only3: int = 6):
75
+ """summary for the function
76
+
77
+ Args:
78
+ pos_only0 (_type_): This is the first positional-only argument.
79
+ pos_only1 (int): This is the second positional-only argument.
80
+ pos_only2 (int, optional): This is the third positional-only argument. Defaults to 5.
81
+ pos_only3 (int, optional): This is the fourth positional-only argument. Defaults to 6.
82
+ """
83
+ " Argument test for positional-only arguments. "
84
+ print(f'pos_only0: {pos_only0}, pos_only1: {pos_only1}, pos_only2: {pos_only2}, pos_only3: {pos_only3}')
85
+ pass
86
+
87
+ @optfunc
88
+ def arg_test_positional_or_keyword(pos_or_kw, pos_or_kw1: int, pos_or_kw2 = 3, pos_or_kw3: int = 4):
89
+ " Argument test for positional-or-keyword arguments. "
90
+ print(f'pos_or_kw: {pos_or_kw}, pos_or_kw1: {pos_or_kw1}, pos_or_kw2: {pos_or_kw2}, pos_or_kw3: {pos_or_kw3}')
91
+ pass
92
+
93
+ @optfunc
94
+ def arg_test_kw_only(*, kw_only0, kw_only1: int, kw_only2 = 9, kw_only3: int = 10):
95
+ " Argument test for keyword-only arguments. "
96
+ print(f'kw_only0: {kw_only0}, kw_only1: {kw_only1}, kw_only2: {kw_only2}, kw_only3: {kw_only3}')
97
+ pass
98
+
99
+ if __name__ == '__main__':
100
+ optfunc_start(globals=globals(), has_abbrev=False, header_doc='This is a test file for the module "autocall".')
101
+ ```
102
+ #### Run the code
103
+ ``` bash
104
+ ~/:$ python3 test.py -h
105
+ Usage: test.py [command] [<args>|--help]
106
+
107
+ This is a test file for the module "autocall".
108
+
109
+ commands:
110
+ arg_test_positional_only summary for the function
111
+ arg_test_positional_or_keyword Argument test for positional-or-keyword arguments.
112
+ arg_test_kw_only Argument test for keyword-only arguments.
113
+
114
+ ~/:$ python3 test.py arg_test_positional_only -h
115
+ Usage: test.py arg_test_positional_only [OPTIONS]
116
+
117
+ summary for the function
118
+
119
+
120
+ Arguments:
121
+ +-------------+------+---------+-------------------------------------------------------------+
122
+ | Opt | Type | Default | Desc |
123
+ +-------------+------+---------+-------------------------------------------------------------+
124
+ | --pos_only0 | any | | This is the first positional-only argument. |
125
+ | --pos_only1 | int | | This is the second positional-only argument. |
126
+ | --pos_only2 | any | 5 | This is the third positional-only argument. Defaults to 5. |
127
+ | --pos_only3 | int | 6 | This is the fourth positional-only argument. Defaults to 6. |
128
+ +-------------+------+---------+-------------------------------------------------------------+
129
+ ~/:$ python3 test.py arg_test_positional_only --pos_only0 "good day" --pos_only1 2
130
+ pos_only0: good day, pos_only1: 2, pos_only2: 5, pos_only3: 6
131
+ ```
optfunc2-0.1/README.md ADDED
@@ -0,0 +1,79 @@
1
+ # Call function directly in cmd line
2
+
3
+ #### Features
4
+ 1. Allow user call functions directly in command line.
5
+ 2. Generate help tips automatically.
6
+ 3. Add default called functions if not function was specific.
7
+
8
+ #### Notice
9
+ 1. It's better to add argument type for each autocall functions.
10
+ 2. Function with @optfunc_default has @optfunc implicitly.
11
+ 3. Arguments of function with @optfunc_default should be optional or no argument.
12
+ 4. Not support two type of variadic arguments.
13
+
14
+ #### TODO
15
+ 1. Beautiful print.
16
+
17
+ #### Code example
18
+ ``` python
19
+ from optfunc import *
20
+
21
+ @optfunc
22
+ def arg_test_positional_only(pos_only0, pos_only1: int, pos_only2 = 5, pos_only3: int = 6):
23
+ """summary for the function
24
+
25
+ Args:
26
+ pos_only0 (_type_): This is the first positional-only argument.
27
+ pos_only1 (int): This is the second positional-only argument.
28
+ pos_only2 (int, optional): This is the third positional-only argument. Defaults to 5.
29
+ pos_only3 (int, optional): This is the fourth positional-only argument. Defaults to 6.
30
+ """
31
+ " Argument test for positional-only arguments. "
32
+ print(f'pos_only0: {pos_only0}, pos_only1: {pos_only1}, pos_only2: {pos_only2}, pos_only3: {pos_only3}')
33
+ pass
34
+
35
+ @optfunc
36
+ def arg_test_positional_or_keyword(pos_or_kw, pos_or_kw1: int, pos_or_kw2 = 3, pos_or_kw3: int = 4):
37
+ " Argument test for positional-or-keyword arguments. "
38
+ print(f'pos_or_kw: {pos_or_kw}, pos_or_kw1: {pos_or_kw1}, pos_or_kw2: {pos_or_kw2}, pos_or_kw3: {pos_or_kw3}')
39
+ pass
40
+
41
+ @optfunc
42
+ def arg_test_kw_only(*, kw_only0, kw_only1: int, kw_only2 = 9, kw_only3: int = 10):
43
+ " Argument test for keyword-only arguments. "
44
+ print(f'kw_only0: {kw_only0}, kw_only1: {kw_only1}, kw_only2: {kw_only2}, kw_only3: {kw_only3}')
45
+ pass
46
+
47
+ if __name__ == '__main__':
48
+ optfunc_start(globals=globals(), has_abbrev=False, header_doc='This is a test file for the module "autocall".')
49
+ ```
50
+ #### Run the code
51
+ ``` bash
52
+ ~/:$ python3 test.py -h
53
+ Usage: test.py [command] [<args>|--help]
54
+
55
+ This is a test file for the module "autocall".
56
+
57
+ commands:
58
+ arg_test_positional_only summary for the function
59
+ arg_test_positional_or_keyword Argument test for positional-or-keyword arguments.
60
+ arg_test_kw_only Argument test for keyword-only arguments.
61
+
62
+ ~/:$ python3 test.py arg_test_positional_only -h
63
+ Usage: test.py arg_test_positional_only [OPTIONS]
64
+
65
+ summary for the function
66
+
67
+
68
+ Arguments:
69
+ +-------------+------+---------+-------------------------------------------------------------+
70
+ | Opt | Type | Default | Desc |
71
+ +-------------+------+---------+-------------------------------------------------------------+
72
+ | --pos_only0 | any | | This is the first positional-only argument. |
73
+ | --pos_only1 | int | | This is the second positional-only argument. |
74
+ | --pos_only2 | any | 5 | This is the third positional-only argument. Defaults to 5. |
75
+ | --pos_only3 | int | 6 | This is the fourth positional-only argument. Defaults to 6. |
76
+ +-------------+------+---------+-------------------------------------------------------------+
77
+ ~/:$ python3 test.py arg_test_positional_only --pos_only0 "good day" --pos_only1 2
78
+ pos_only0: good day, pos_only1: 2, pos_only2: 5, pos_only3: 6
79
+ ```
@@ -0,0 +1,164 @@
1
+ # Guide (user-friendly):
2
+ # https://packaging.python.org/en/latest/guides/writing-pyproject-toml/
3
+
4
+ # Specification (technical, formal):
5
+ # https://packaging.python.org/en/latest/specifications/pyproject-toml/
6
+
7
+
8
+ # Choosing a build backend:
9
+ # https://packaging.python.org/en/latest/tutorials/packaging-projects/#choosing-a-build-backend
10
+ [build-system]
11
+ # A list of packages that are needed to build your package:
12
+ requires = ["setuptools"] # REQUIRED if [build-system] table is used
13
+ # The name of the Python object that frontends will use to perform the build:
14
+ build-backend = "setuptools.build_meta" # If not defined, then legacy behavior can happen.
15
+
16
+
17
+ [project]
18
+ # This is the name of your project. The first time you publish this
19
+ # package, this name will be registered for you. It will determine how
20
+ # users can install this project, e.g.:
21
+ #
22
+ # $ pip install sampleproject
23
+ #
24
+ # And where it will live on PyPI: https://pypi.org/project/sampleproject/
25
+ #
26
+ # There are some restrictions on what makes a valid project name
27
+ # specification here:
28
+ # https://packaging.python.org/specifications/core-metadata/#name
29
+ name = "optfunc2" # REQUIRED, is the only field that cannot be marked as dynamic.
30
+
31
+ # Versions should comply with PEP 440:
32
+ # https://www.python.org/dev/peps/pep-0440/
33
+ #
34
+ # For a discussion on single-sourcing the version, see
35
+ # https://packaging.python.org/guides/single-sourcing-package-version/
36
+ version = "0.1" # REQUIRED, although can be dynamic
37
+
38
+ # This is a one-line description or tagline of what your project does. This
39
+ # corresponds to the "Summary" metadata field:
40
+ # https://packaging.python.org/specifications/core-metadata/#summary
41
+ description = "Generate options from function."
42
+
43
+ # This is an optional longer description of your project that represents
44
+ # the body of text which users will see when they visit PyPI.
45
+ #
46
+ # Often, this is the same as your README, so you can just read it in from
47
+ # that file directly.
48
+ #
49
+ # This field corresponds to the "Description" metadata field:
50
+ # https://packaging.python.org/specifications/core-metadata/#description-optional
51
+ readme = "README.md"
52
+
53
+ # Specify which Python versions you support. In contrast to the
54
+ # 'Programming Language' classifiers in this file, 'pip install' will check this
55
+ # and refuse to install the project if the version does not match. See
56
+ # https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires
57
+ requires-python = ">=3.7"
58
+
59
+ # This is either text indicating the license for the distribution, or a file
60
+ # that contains the license.
61
+ # https://packaging.python.org/en/latest/specifications/core-metadata/#license
62
+ license = {file = "LICENSE.txt"}
63
+
64
+ # This field adds keywords for your project which will appear on the
65
+ # project page. What does your project relate to?
66
+ #
67
+ # Note that this is a list of additional keywords, separated
68
+ # by commas, to be used to assist searching for the distribution in a
69
+ # larger catalog.
70
+ keywords = ["call", "function", "option"]
71
+
72
+ # This should be your name or the name of the organization who originally
73
+ # authored the project, and a valid email address corresponding to the name
74
+ # listed.
75
+ authors = [
76
+ {name = "bajeer", email = "z_bajer@yeah.net" }
77
+ ]
78
+
79
+ # This should be your name or the names of the organization who currently
80
+ # maintains the project, and a valid email address corresponding to the name
81
+ # listed.
82
+ maintainers = [
83
+ {name = "bajeer", email = "z_bajer@yeah.net" }
84
+ ]
85
+
86
+ # Classifiers help users find your project by categorizing it.
87
+ #
88
+ # For a list of valid classifiers, see https://pypi.org/classifiers/
89
+ classifiers = [
90
+ # How mature is this project? Common values are
91
+ # 3 - Alpha
92
+ # 4 - Beta
93
+ # 5 - Production/Stable
94
+ "Development Status :: 3 - Alpha",
95
+
96
+ # Indicate who your project is intended for
97
+ "Intended Audience :: Developers",
98
+ "Topic :: Software Development",
99
+
100
+ # Pick your license as you wish
101
+ "License :: OSI Approved :: MIT License",
102
+
103
+ # Specify the Python versions you support here. In particular, ensure
104
+ # that you indicate you support Python 3. These classifiers are *not*
105
+ # checked by "pip install". See instead "requires-python" key in this file.
106
+ "Programming Language :: Python :: 3",
107
+ "Programming Language :: Python :: 3.7",
108
+ "Programming Language :: Python :: 3.8",
109
+ "Programming Language :: Python :: 3.9",
110
+ "Programming Language :: Python :: 3.10",
111
+ "Programming Language :: Python :: 3.11",
112
+ "Programming Language :: Python :: 3.12",
113
+ "Programming Language :: Python :: 3.13",
114
+ "Programming Language :: Python :: 3.14",
115
+ "Programming Language :: Python :: 3 :: Only",
116
+ ]
117
+
118
+ # This field lists other packages that your project depends on to run.
119
+ # Any package you put here will be installed by pip when your project is
120
+ # installed, so they must be valid existing projects.
121
+ #
122
+ # For an analysis of this field vs pip's requirements files see:
123
+ # https://packaging.python.org/discussions/install-requires-vs-requirements/
124
+
125
+ # List additional groups of dependencies here (e.g. development
126
+ # dependencies). Users will be able to install these using the "extras"
127
+ # syntax, for example:
128
+ #
129
+ # $ pip install sampleproject[dev]
130
+ #
131
+ # Optional dependencies the project provides. These are commonly
132
+ # referred to as "extras". For a more extensive definition see:
133
+ # https://packaging.python.org/en/latest/specifications/dependency-specifiers/#extras
134
+ [project.optional-dependencies]
135
+ dev = ["check-manifest"]
136
+ test = ["coverage"]
137
+
138
+ # List URLs that are relevant to your project
139
+ #
140
+ # This field corresponds to the "Project-URL" and "Home-Page" metadata fields:
141
+ # https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use
142
+ # https://packaging.python.org/specifications/core-metadata/#home-page-optional
143
+ #
144
+ # Examples listed include a pattern for specifying where the package tracks
145
+ # issues, where the source is hosted, where to say thanks to the package
146
+ # maintainers, and where to support the project financially. The key is
147
+ # what's used to render the link text on PyPI.
148
+ [project.urls]
149
+ "Homepage" = "https://gitee.com/z-bajer/autocall"
150
+ "Bug Reports" = "https://gitee.com/z-bajer/autocall/issues"
151
+ "Source" = "https://gitee.com/z-bajer/autocall"
152
+
153
+ # The following would provide a command line executable called `sample`
154
+ # which executes the function `main` from this package when invoked.
155
+ #[project.scripts]
156
+ #sample = "sample:main"
157
+
158
+
159
+ # This is configuration specific to the `setuptools` build backend.
160
+ # If you are using a different build backend, you will need to change this.
161
+ #[tool.setuptools]
162
+ # If there are data files included in your packages that need to be
163
+ # installed, specify them here.
164
+ #package-data = {"sample" = ["*.dat"]}
optfunc2-0.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ #!/bin/python3
2
+
3
+ __all__ = ['cmdline', 'cmdline_default', 'cmdline_start',
4
+ 'optfunc', 'optfunc_default', 'optfunc_start']
5
+
6
+ from optfunc2.parser import cmdline as cmdline
7
+ from optfunc2.parser import cmdline_default as cmdline_default
8
+ from optfunc2.parser import cmdline_start as cmdline_start
9
+
10
+ from optfunc2.parser import cmdline as optfunc
11
+ from optfunc2.parser import cmdline_default as optfunc_default
12
+ from optfunc2.parser import cmdline_start as optfunc_start
13
+
@@ -0,0 +1,353 @@
1
+ import inspect
2
+ import prettytable
3
+ import docstring_parser
4
+ import sys
5
+ import ast
6
+
7
+ # functions taged by @cmdline
8
+ registered_funcs = []
9
+ registered_func_default = None
10
+
11
+ colors = {
12
+ "red": 91,
13
+ "blue": 94,
14
+ "green": 92,
15
+ "magenta": 95,
16
+ "yellow": 93,
17
+ "black": 90,
18
+ "cyan": 96,
19
+ }
20
+
21
+ def color_begin(color):
22
+ print('\033[{}m'.format(colors[color]), end='')
23
+
24
+ def color_end():
25
+ print('\033[0m', end='')
26
+
27
+ def decode_func_args(func: callable):
28
+ """
29
+ (type, name, abbreviation, annotation, default, doc)
30
+ """
31
+
32
+ doc = func.__doc__
33
+ docstring = docstring_parser.parse(doc)
34
+
35
+ args_list = []
36
+ abbrev_list = []
37
+
38
+ # -h has been occupied by help command.
39
+ abbrev_list.append('h')
40
+
41
+ for name, param in inspect.signature(func).parameters.items():
42
+ if len(name) == 1:
43
+ abbrev_list.append(name)
44
+
45
+ abbrev = name[0]
46
+
47
+ desc = inspect.Signature.empty
48
+ for param_docstring in docstring.params:
49
+ if name == param_docstring.arg_name:
50
+ desc = param_docstring.description
51
+ break
52
+
53
+ if abbrev not in abbrev_list:
54
+ abbrev_list.append(abbrev)
55
+ else:
56
+ abbrev = inspect.Signature.empty
57
+
58
+ args_list.append((param.kind, name, abbrev, param.annotation, param.default, desc))
59
+
60
+
61
+ return args_list
62
+
63
+ def get_and_check_opt(args_list: list, opt_name):
64
+ opt_name2 = opt_name
65
+ if opt_name.startswith('--'):
66
+ opt_name = opt_name[2:]
67
+ if len(opt_name) == 1:
68
+ raise ValueError(f'{opt_name} is not a valid option name.')
69
+ elif opt_name.startswith('-'):
70
+ opt_name = opt_name[1:]
71
+ if len(opt_name) != 1:
72
+ raise ValueError(f'{opt_name} is not a valid option name.')
73
+ else:
74
+ raise ValueError(f'{opt_name} is not a valid option name.')
75
+
76
+ for idx, (_, name, abbrev, _, _, _) in enumerate(args_list):
77
+ if name == opt_name or abbrev == opt_name:
78
+ return args_list.pop(idx)
79
+
80
+ raise ValueError(f'{opt_name2} not found.')
81
+
82
+ def decode_opts(arg_pairs, func: callable):
83
+ """
84
+ (type, name, annotation, value)
85
+ """
86
+ arg_list = decode_func_args(func)
87
+ opt_list = []
88
+
89
+ for (opt, val) in arg_pairs:
90
+ typ, name, _, anno, _, _ = get_and_check_opt(arg_list, opt)
91
+ try:
92
+ if anno != inspect.Signature.empty:
93
+ value = anno(val)
94
+ else:
95
+ try:
96
+ value = ast.literal_eval(val)
97
+ except Exception:
98
+ value = str(val)
99
+
100
+ anno = type(value)
101
+
102
+ opt_list.append((typ, name, anno, value))
103
+
104
+ except ValueError:
105
+ raise ValueError(f'Value type of {opt} should be {anno.__name__}.')
106
+
107
+ for (typ, name, _, anno, default, _) in arg_list:
108
+ if default == inspect.Signature.empty:
109
+ raise ValueError(f'--{name} is required.')
110
+
111
+ opt_list.append((typ, name, anno, default))
112
+
113
+ return opt_list
114
+
115
+ def hibit_variadic(func: callable):
116
+ arg_list = decode_func_args(func)
117
+ for (typ, _, _, _, _, _) in arg_list:
118
+ if typ == inspect.Parameter.VAR_POSITIONAL or typ == inspect.Parameter.VAR_KEYWORD:
119
+ color_begin('red')
120
+ print(f'[Autocall Error]: Function {func.__name__} annotated by @cmdline has variadic arguments.')
121
+ color_end()
122
+ exit(1)
123
+
124
+ def cmdline_default(func):
125
+ global registered_func_default
126
+ global registered_funcs
127
+
128
+ parameters = inspect.getfullargspec(func)
129
+
130
+ if len(parameters.args) != 0 and len(parameters.args) != len(parameters.defaults):
131
+ color_begin('red')
132
+ print(f'[Autocall Erroring]: Function annotated by @cmdline_default should have zero arguments or all arguments have default value.')
133
+ color_end()
134
+ exit(1)
135
+
136
+ if registered_func_default:
137
+ color_begin('yellow')
138
+ print(f'[Autocall Warning]: @cmdline_default can only be used once or the last one will be used.')
139
+ color_end()
140
+
141
+ registered_func_default = func
142
+
143
+ hibit_variadic(func)
144
+
145
+ if func not in registered_funcs:
146
+ registered_funcs.append(func)
147
+
148
+ # globals()[funcname] = func
149
+ return func
150
+
151
+ def cmdline(func):
152
+ global registered_funcs
153
+ if func not in registered_funcs:
154
+ registered_funcs.append(func)
155
+
156
+ hibit_variadic(func)
157
+ return func
158
+
159
+
160
+ def cmd_help(func: callable, has_abbrev = True):
161
+ args_list = decode_func_args(func)
162
+
163
+ func_desc = docstring_parser.parse(func.__doc__).description
164
+
165
+ empty_tag = ''
166
+
167
+ color_begin('blue')
168
+ print(f'Usage: {sys.argv[0]} {func.__name__} ', end='')
169
+ print('[OPTIONS]')
170
+ color_end()
171
+ print()
172
+
173
+ if func_desc != None:
174
+ print(func_desc)
175
+ else:
176
+ print('Help Tips Provided by Autocall.')
177
+
178
+ print()
179
+
180
+ if len(args_list) == 0:
181
+ return
182
+
183
+ print('Arguments:')
184
+
185
+ table = prettytable.PrettyTable()
186
+ table.field_names = ['Opt', 'Abbrev', 'Type', 'Default', 'Desc']
187
+
188
+ for (type, name, abbrev, anno, default, desc) in args_list:
189
+ # abbrev, anno, default, desc all may be empty
190
+ if len(name) == 1:
191
+ name = '-' + name
192
+ else:
193
+ name = '--' + name
194
+
195
+ if abbrev == inspect.Signature.empty:
196
+ abbrev = empty_tag
197
+ else:
198
+ abbrev = '-' + abbrev
199
+
200
+ if anno == inspect.Signature.empty:
201
+ anno = 'any'
202
+ else:
203
+ anno = anno.__name__
204
+
205
+ if default == inspect.Signature.empty:
206
+ default = empty_tag
207
+ else:
208
+ default = repr(default)
209
+
210
+ if desc == inspect.Signature.empty:
211
+ desc = empty_tag
212
+
213
+ table.add_row([name, abbrev, anno, default, desc])
214
+
215
+ if not has_abbrev:
216
+ table.del_column('Abbrev')
217
+
218
+ print(table)
219
+
220
+ def help(header_doc):
221
+ """
222
+ Give the argument \"verbose\" instead of \"notverbose\" to print detail information.
223
+ """
224
+ global registered_funcs
225
+
226
+ color_begin('blue')
227
+ print(f'Usage: {sys.argv[0]} ', end='')
228
+ # print('[--help] ', end='')
229
+ color_begin('green')
230
+ print('[command] [<args>|--help]')
231
+ color_end()
232
+ print()
233
+
234
+ print(header_doc)
235
+ print()
236
+
237
+ print('commands:')
238
+
239
+ max_name_len = max([len(f.__name__) for f in registered_funcs]) + 5
240
+
241
+ for f in registered_funcs:
242
+ doc = f.__doc__
243
+ color_begin('green')
244
+ print(f' {f.__name__:<{max_name_len}s}', end='')
245
+ color_end()
246
+ if doc:
247
+ doc_list = [d.strip() for d in doc.split('\n') if d.strip()]
248
+ doc = doc_list[0]
249
+ print(doc)
250
+ else:
251
+ print()
252
+
253
+ print()
254
+
255
+ def match_and_check(name):
256
+ """
257
+ Match the name with the function name.
258
+ """
259
+ global registered_funcs
260
+ for f in registered_funcs:
261
+ if f.__name__ == name:
262
+ return f
263
+
264
+ return None
265
+
266
+ def pair_argv(argv, has_abbrev = True):
267
+ """ Support these styles:
268
+ --arg val
269
+ --arg=val
270
+ -a val
271
+ -aval
272
+ """
273
+ if len(argv) == 0:
274
+ return []
275
+
276
+ idx = 0
277
+ arg_pairs = []
278
+ while idx < len(argv):
279
+ arg = argv[idx]
280
+ if arg.startswith('--'):
281
+ if '=' in arg:
282
+ arg, val = arg.split('=')
283
+ arg_pairs.append((arg, val))
284
+ else:
285
+ if len(argv) == idx + 1:
286
+ raise ValueError(f'No value given for argument {arg}.')
287
+ arg_pairs.append((arg, argv[idx+1]))
288
+ idx += 1
289
+ elif arg.startswith('-'):
290
+ if not has_abbrev:
291
+ raise ValueError(f'Unknown argument {arg}. Abbreviations are not supported.')
292
+
293
+ if len(arg) != 2:
294
+ arg_pairs.append((arg[0:2], arg[2:]))
295
+ else:
296
+ arg_pairs.append((arg, argv[idx+1]))
297
+ idx += 1
298
+ idx += 1
299
+
300
+ return arg_pairs
301
+
302
+ # def parse_run(argv = sys.argv[1:]):
303
+ def cmdline_start(globals, locals = None, *, argv = sys.argv, header_doc: str = 'Help Tips Provided by Autocall.', has_abbrev = True):
304
+ """Begin to handle argv and execute the corresponding function.
305
+
306
+ Args:
307
+ globals (dict): Used to be the execution environment.
308
+ locals (dict, optional): Used to be the execution environment.
309
+ argv (list, optional): Advanced usage. Defaults to sys.argv.
310
+ header_doc (str, optional): Will be printed as the header of help information.
311
+ has_abbrev (bool, optional): Whether to support abbreviations. Defaults to True.
312
+ """
313
+
314
+ if len(argv) == 1:
315
+ return
316
+
317
+ if argv[1] == 'help' or argv[1] == '--help' or argv[1] == '-h':
318
+ help(header_doc)
319
+ return
320
+
321
+ func = match_and_check(argv[1])
322
+
323
+ if not func:
324
+ color_begin('red')
325
+ print(f'[Autocall Warning]: Unknown command \"{argv[1]}\". Use \"--help\" or \"help\" to get help.')
326
+ color_end()
327
+ return
328
+
329
+ # Not exception will be raised when no more arguments are given.
330
+ argv = argv[2:]
331
+ if '-h' in argv or '--help' in argv:
332
+ cmd_help(func, has_abbrev)
333
+ return
334
+
335
+ # parse argv
336
+ arg_pairs = pair_argv(argv, has_abbrev)
337
+
338
+ # get opt_list from arg_pairs
339
+ opt_list = decode_opts(arg_pairs, func)
340
+
341
+ final_args = []
342
+
343
+ for (typ, name, anno, value) in opt_list:
344
+ if typ != inspect.Parameter.POSITIONAL_ONLY:
345
+ final_args.append(f'{name}={repr(value)}')
346
+ else:
347
+ final_args.append(repr(value))
348
+
349
+ func_call_str = f'{func.__name__}('
350
+ func_call_str += ', '.join(final_args)
351
+ func_call_str += ')'
352
+
353
+ eval(func_call_str, globals, locals)
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.1
2
+ Name: optfunc2
3
+ Version: 0.1
4
+ Summary: Generate options from function.
5
+ Author-email: bajeer <z_bajer@yeah.net>
6
+ Maintainer-email: bajeer <z_bajer@yeah.net>
7
+ License: Copyright (c) 2016 The Python Packaging Authority (PyPA)
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
10
+ this software and associated documentation files (the "Software"), to deal in
11
+ the Software without restriction, including without limitation the rights to
12
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
13
+ of the Software, and to permit persons to whom the Software is furnished to do
14
+ so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Project-URL: Homepage, https://gitee.com/z-bajer/autocall
28
+ Project-URL: Bug Reports, https://gitee.com/z-bajer/autocall/issues
29
+ Project-URL: Source, https://gitee.com/z-bajer/autocall
30
+ Keywords: call,function,option
31
+ Classifier: Development Status :: 3 - Alpha
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Topic :: Software Development
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.7
37
+ Classifier: Programming Language :: Python :: 3.8
38
+ Classifier: Programming Language :: Python :: 3.9
39
+ Classifier: Programming Language :: Python :: 3.10
40
+ Classifier: Programming Language :: Python :: 3.11
41
+ Classifier: Programming Language :: Python :: 3.12
42
+ Classifier: Programming Language :: Python :: 3.13
43
+ Classifier: Programming Language :: Python :: 3.14
44
+ Classifier: Programming Language :: Python :: 3 :: Only
45
+ Requires-Python: >=3.7
46
+ Description-Content-Type: text/markdown
47
+ License-File: LICENSE.txt
48
+ Provides-Extra: dev
49
+ Requires-Dist: check-manifest; extra == "dev"
50
+ Provides-Extra: test
51
+ Requires-Dist: coverage; extra == "test"
52
+
53
+ # Call function directly in cmd line
54
+
55
+ #### Features
56
+ 1. Allow user call functions directly in command line.
57
+ 2. Generate help tips automatically.
58
+ 3. Add default called functions if not function was specific.
59
+
60
+ #### Notice
61
+ 1. It's better to add argument type for each autocall functions.
62
+ 2. Function with @optfunc_default has @optfunc implicitly.
63
+ 3. Arguments of function with @optfunc_default should be optional or no argument.
64
+ 4. Not support two type of variadic arguments.
65
+
66
+ #### TODO
67
+ 1. Beautiful print.
68
+
69
+ #### Code example
70
+ ``` python
71
+ from optfunc import *
72
+
73
+ @optfunc
74
+ def arg_test_positional_only(pos_only0, pos_only1: int, pos_only2 = 5, pos_only3: int = 6):
75
+ """summary for the function
76
+
77
+ Args:
78
+ pos_only0 (_type_): This is the first positional-only argument.
79
+ pos_only1 (int): This is the second positional-only argument.
80
+ pos_only2 (int, optional): This is the third positional-only argument. Defaults to 5.
81
+ pos_only3 (int, optional): This is the fourth positional-only argument. Defaults to 6.
82
+ """
83
+ " Argument test for positional-only arguments. "
84
+ print(f'pos_only0: {pos_only0}, pos_only1: {pos_only1}, pos_only2: {pos_only2}, pos_only3: {pos_only3}')
85
+ pass
86
+
87
+ @optfunc
88
+ def arg_test_positional_or_keyword(pos_or_kw, pos_or_kw1: int, pos_or_kw2 = 3, pos_or_kw3: int = 4):
89
+ " Argument test for positional-or-keyword arguments. "
90
+ print(f'pos_or_kw: {pos_or_kw}, pos_or_kw1: {pos_or_kw1}, pos_or_kw2: {pos_or_kw2}, pos_or_kw3: {pos_or_kw3}')
91
+ pass
92
+
93
+ @optfunc
94
+ def arg_test_kw_only(*, kw_only0, kw_only1: int, kw_only2 = 9, kw_only3: int = 10):
95
+ " Argument test for keyword-only arguments. "
96
+ print(f'kw_only0: {kw_only0}, kw_only1: {kw_only1}, kw_only2: {kw_only2}, kw_only3: {kw_only3}')
97
+ pass
98
+
99
+ if __name__ == '__main__':
100
+ optfunc_start(globals=globals(), has_abbrev=False, header_doc='This is a test file for the module "autocall".')
101
+ ```
102
+ #### Run the code
103
+ ``` bash
104
+ ~/:$ python3 test.py -h
105
+ Usage: test.py [command] [<args>|--help]
106
+
107
+ This is a test file for the module "autocall".
108
+
109
+ commands:
110
+ arg_test_positional_only summary for the function
111
+ arg_test_positional_or_keyword Argument test for positional-or-keyword arguments.
112
+ arg_test_kw_only Argument test for keyword-only arguments.
113
+
114
+ ~/:$ python3 test.py arg_test_positional_only -h
115
+ Usage: test.py arg_test_positional_only [OPTIONS]
116
+
117
+ summary for the function
118
+
119
+
120
+ Arguments:
121
+ +-------------+------+---------+-------------------------------------------------------------+
122
+ | Opt | Type | Default | Desc |
123
+ +-------------+------+---------+-------------------------------------------------------------+
124
+ | --pos_only0 | any | | This is the first positional-only argument. |
125
+ | --pos_only1 | int | | This is the second positional-only argument. |
126
+ | --pos_only2 | any | 5 | This is the third positional-only argument. Defaults to 5. |
127
+ | --pos_only3 | int | 6 | This is the fourth positional-only argument. Defaults to 6. |
128
+ +-------------+------+---------+-------------------------------------------------------------+
129
+ ~/:$ python3 test.py arg_test_positional_only --pos_only0 "good day" --pos_only1 2
130
+ pos_only0: good day, pos_only1: 2, pos_only2: 5, pos_only3: 6
131
+ ```
@@ -0,0 +1,11 @@
1
+ LICENSE.txt
2
+ README.md
3
+ pyproject.toml
4
+ src/test.py
5
+ src/optfunc2/__init__.py
6
+ src/optfunc2/parser.py
7
+ src/optfunc2.egg-info/PKG-INFO
8
+ src/optfunc2.egg-info/SOURCES.txt
9
+ src/optfunc2.egg-info/dependency_links.txt
10
+ src/optfunc2.egg-info/requires.txt
11
+ src/optfunc2.egg-info/top_level.txt
@@ -0,0 +1,6 @@
1
+
2
+ [dev]
3
+ check-manifest
4
+
5
+ [test]
6
+ coverage
@@ -0,0 +1,2 @@
1
+ optfunc2
2
+ test
@@ -0,0 +1,41 @@
1
+ #!/bin/python3
2
+ import sys
3
+ import os
4
+ # sys.path.append("Z:\\autocall\\src")
5
+ current_dir = os.path.dirname(os.path.realpath(__file__))
6
+ autocall_dir = os.path.join(current_dir, 'src')
7
+ sys.path.insert(0, current_dir)
8
+ # print(sys.path)
9
+ # sys.path.append(autocall_dir)
10
+ # print(current_dir)
11
+ from autocall import *
12
+ import autocall
13
+
14
+ @cmdline
15
+ def arg_test_positional_only(pos_only0, pos_only1: int, pos_only2 = 5, pos_only3: int = 6):
16
+ """summary for the function
17
+
18
+ Args:
19
+ pos_only0 (_type_): This is the first positional-only argument.
20
+ pos_only1 (int): This is the second positional-only argument.
21
+ pos_only2 (int, optional): This is the third positional-only argument. Defaults to 5.
22
+ pos_only3 (int, optional): This is the fourth positional-only argument. Defaults to 6.
23
+ """
24
+ " Argument test for positional-only arguments. "
25
+ print(f'pos_only0: {pos_only0}, pos_only1: {pos_only1}, pos_only2: {pos_only2}, pos_only3: {pos_only3}')
26
+ pass
27
+
28
+ @cmdline
29
+ def arg_test_positional_or_keyword(pos_or_kw, pos_or_kw1: int, pos_or_kw2 = 3, pos_or_kw3: int = 4):
30
+ " Argument test for positional-or-keyword arguments. "
31
+ print(f'pos_or_kw: {pos_or_kw}, pos_or_kw1: {pos_or_kw1}, pos_or_kw2: {pos_or_kw2}, pos_or_kw3: {pos_or_kw3}')
32
+ pass
33
+
34
+ @cmdline
35
+ def arg_test_kw_only(*, kw_only0, kw_only1: int, kw_only2 = 9, kw_only3: int = 10):
36
+ " Argument test for keyword-only arguments. "
37
+ print(f'kw_only0: {kw_only0}, kw_only1: {kw_only1}, kw_only2: {kw_only2}, kw_only3: {kw_only3}')
38
+ pass
39
+
40
+ if __name__ == '__main__':
41
+ cmdline_start(globals=globals(), has_abbrev=False, header_doc='This is a test file for the module "autocall".')