pyqtcli 0.1.0__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.
- pyqtcli-0.1.0/LICENSE +21 -0
- pyqtcli-0.1.0/PKG-INFO +311 -0
- pyqtcli-0.1.0/README.md +259 -0
- pyqtcli-0.1.0/pyproject.toml +60 -0
- pyqtcli-0.1.0/pyqtcli/__init__.py +11 -0
- pyqtcli-0.1.0/pyqtcli/__init__.pyi +50 -0
- pyqtcli-0.1.0/pyqtcli/_widgets.py +24 -0
- pyqtcli-0.1.0/pyqtcli/argparser.py +57 -0
- pyqtcli-0.1.0/pyqtcli/argparser.pyi +139 -0
- pyqtcli-0.1.0/pyqtcli/py.typed +0 -0
- pyqtcli-0.1.0/pyqtcli.egg-info/PKG-INFO +311 -0
- pyqtcli-0.1.0/pyqtcli.egg-info/SOURCES.txt +14 -0
- pyqtcli-0.1.0/pyqtcli.egg-info/dependency_links.txt +1 -0
- pyqtcli-0.1.0/pyqtcli.egg-info/requires.txt +25 -0
- pyqtcli-0.1.0/pyqtcli.egg-info/top_level.txt +2 -0
- pyqtcli-0.1.0/setup.cfg +4 -0
pyqtcli-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Маг Ильяс DOMA (MagIlyasDOMA)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
pyqtcli-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyqtcli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Package for supporting command-line arguments in Qt for Python applications
|
|
5
|
+
Author-email: "Маг Ильяс DOMA (MagIlyasDOMA)" <magilyas.doma.09@list.ru>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Source, https://github.com/MagIlyasDOMA/pyqtcli
|
|
8
|
+
Project-URL: Repository, https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: Microsoft :: Windows :: Windows 10
|
|
11
|
+
Classifier: Operating System :: Microsoft :: Windows :: Windows 11
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Framework :: Django
|
|
19
|
+
Classifier: Framework :: Django :: 5.2
|
|
20
|
+
Classifier: Framework :: Django :: 6.0
|
|
21
|
+
Classifier: Natural Language :: English
|
|
22
|
+
Classifier: Natural Language :: Russian
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Topic :: Utilities
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
27
|
+
Classifier: Topic :: Security :: Cryptography
|
|
28
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
29
|
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
|
30
|
+
Requires-Python: >=3.9
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
License-File: LICENSE
|
|
33
|
+
Requires-Dist: argparse-typing>=0.2.0
|
|
34
|
+
Provides-Extra: pyside
|
|
35
|
+
Requires-Dist: Pyside2>=5.12.0; extra == "pyside"
|
|
36
|
+
Provides-Extra: pyside2
|
|
37
|
+
Requires-Dist: Pyside2>=5.12.0; extra == "pyside2"
|
|
38
|
+
Provides-Extra: pyside6
|
|
39
|
+
Requires-Dist: Pyside6>=6.0.0; extra == "pyside6"
|
|
40
|
+
Provides-Extra: pyqt
|
|
41
|
+
Requires-Dist: PyQt5>=5.0.0; extra == "pyqt"
|
|
42
|
+
Provides-Extra: pyqt5
|
|
43
|
+
Requires-Dist: PyQt5>=5.0.0; extra == "pyqt5"
|
|
44
|
+
Provides-Extra: pyqt6
|
|
45
|
+
Requires-Dist: PyQt6>=6.0.0; extra == "pyqt6"
|
|
46
|
+
Provides-Extra: dev
|
|
47
|
+
Requires-Dist: setuptools>=61.0.0; extra == "dev"
|
|
48
|
+
Requires-Dist: wheel>=0.46.3; extra == "dev"
|
|
49
|
+
Requires-Dist: twine>=6.2.0; extra == "dev"
|
|
50
|
+
Requires-Dist: build>=1.4.0; extra == "dev"
|
|
51
|
+
Dynamic: license-file
|
|
52
|
+
|
|
53
|
+
<a id="doc_en"></a>
|
|
54
|
+
# `pyqtcli` Documentation (PyQt/PySide CLI Integration)
|
|
55
|
+
#### [Документация на русском](#doc_ru)
|
|
56
|
+
|
|
57
|
+
**PyQtCLI** is a Python package that simplifies integrating command-line argument parsing into Qt-based GUI applications (PySide/PyQt). It allows you to easily combine the standard `argparse` module with the ability to display help messages in a graphical window (`QMessageBox`).
|
|
58
|
+
|
|
59
|
+
## Features
|
|
60
|
+
- **Backend Flexibility:** Automatically detects the available Qt binding (`PySide6`, `PyQt6`, `PyQt5`, `PySide2`).
|
|
61
|
+
- **Graphical Help:** The `GUIHelpParser` class overrides the help output (`-h`, `--help`), displaying it not only in the console but also in a pop-up `QMessageBox` window.
|
|
62
|
+
- **Convenient Mixin:** The `CLIMixin` class provides all the methods of `argparse.ArgumentParser` (`add_argument`, `parse_args`, etc.) for easy addition to your classes.
|
|
63
|
+
- **Ready-to-Use Integration:** The `QCLIApplication` class is a ready-to-use subclass of `QApplication` with the `CLIMixin` functionality already built-in.
|
|
64
|
+
- **Type Hints:** Includes `.pyi` files for better autocompletion and type checking support in modern IDEs.
|
|
65
|
+
|
|
66
|
+
## Installation
|
|
67
|
+
You can install the package directly from the repository or from PyPI after publication (replace with the actual command):
|
|
68
|
+
|
|
69
|
+
```shell
|
|
70
|
+
# From repository
|
|
71
|
+
pip install git+https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
72
|
+
|
|
73
|
+
# Or after publication (example)
|
|
74
|
+
pip install pyqtcli
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The package does not automatically install a specific Qt library. You need to install one of the supported bindings yourself:
|
|
78
|
+
|
|
79
|
+
```shell
|
|
80
|
+
# For example, for PySide6
|
|
81
|
+
pip install pyqtcli[pyside6]
|
|
82
|
+
|
|
83
|
+
# Or for PyQt5
|
|
84
|
+
pip install pyqtcli[pyqt5]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Usage
|
|
88
|
+
### Quick Start with QCLIApplication
|
|
89
|
+
The easiest way to create an application with command-line argument support is to use the ready-made `QCLIApplication` class.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import sys
|
|
93
|
+
from pyqtcli import QCLIApplication
|
|
94
|
+
from PySide6.QtWidgets import QMainWindow, QLabel # Example for PySide6
|
|
95
|
+
|
|
96
|
+
# Create an application instance, passing the command-line arguments
|
|
97
|
+
# All additional parameters (prog, description, etc.) are passed to the parser.
|
|
98
|
+
app = QCLIApplication(
|
|
99
|
+
sys.argv,
|
|
100
|
+
description="My Super Application",
|
|
101
|
+
epilog="Example of using QCLIApplication"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# Add your own arguments, just like in standard argparse
|
|
105
|
+
app.add_argument("-f", "--file", help="Path to the file to open")
|
|
106
|
+
app.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
|
|
107
|
+
|
|
108
|
+
# Parse the arguments. Help (-h) will automatically be displayed in a graphical window.
|
|
109
|
+
args = app.parse_args()
|
|
110
|
+
|
|
111
|
+
# --- Standard Qt application code follows ---
|
|
112
|
+
window = QMainWindow()
|
|
113
|
+
if args.file:
|
|
114
|
+
window.setCentralWidget(QLabel(f"Opened file: {args.file}"))
|
|
115
|
+
else:
|
|
116
|
+
window.setCentralWidget(QLabel("Hello, world!"))
|
|
117
|
+
window.show()
|
|
118
|
+
|
|
119
|
+
sys.exit(app.exec())
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Using CLIMixin in Your Own QApplication Class
|
|
123
|
+
If you need more control or want to add parsing functionality to your own application class, use `CLIMixin`.
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
import sys
|
|
127
|
+
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel
|
|
128
|
+
from pyqtcli import CLIMixin
|
|
129
|
+
|
|
130
|
+
class MyApp(QApplication, CLIMixin):
|
|
131
|
+
def __init__(self, argv):
|
|
132
|
+
# First, initialize the mixin with parser parameters
|
|
133
|
+
CLIMixin.__init__(self, description="My Custom Application")
|
|
134
|
+
# Then initialize QApplication
|
|
135
|
+
QApplication.__init__(self, argv)
|
|
136
|
+
|
|
137
|
+
# Add your own arguments
|
|
138
|
+
self.add_argument("--debug", action="store_true", help="Enable debug mode")
|
|
139
|
+
|
|
140
|
+
# Parse the arguments
|
|
141
|
+
self.args = self.parse_args()
|
|
142
|
+
|
|
143
|
+
if self.args.debug:
|
|
144
|
+
print("Debug mode enabled")
|
|
145
|
+
|
|
146
|
+
# Run the application
|
|
147
|
+
if __name__ == "__main__":
|
|
148
|
+
app = MyApp(sys.argv)
|
|
149
|
+
|
|
150
|
+
window = QMainWindow()
|
|
151
|
+
window.setCentralWidget(QLabel("Application Window"))
|
|
152
|
+
window.show()
|
|
153
|
+
|
|
154
|
+
sys.exit(app.exec())
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Using GUIHelpParser Directly
|
|
158
|
+
You can use the graphical parser directly, for example, to create a standalone tool.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
import sys
|
|
162
|
+
from PySide6.QtWidgets import QApplication
|
|
163
|
+
from pyqtcli.argparser import GUIHelpParser
|
|
164
|
+
|
|
165
|
+
# Create the parser
|
|
166
|
+
app = QApplication(sys.argv)
|
|
167
|
+
parser = GUIHelpParser(prog="tool.py", description="Tool with GUI help")
|
|
168
|
+
parser.add_argument("-o", "--output", help="File to save the result")
|
|
169
|
+
|
|
170
|
+
# When parse_args() is called, help will be shown in a window
|
|
171
|
+
# if the -h or --help arguments are passed.
|
|
172
|
+
# Otherwise, parsing proceeds as usual.
|
|
173
|
+
args = parser.parse_args()
|
|
174
|
+
print(args)
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Package Structure
|
|
178
|
+
- `__init__.py`: The main module, exporting the `QCLIApplication`, `CLIMixin`, and `GUIHelpParser` classes.
|
|
179
|
+
- `_widgets.py`: An internal module for automatically selecting and importing the required Qt binding.
|
|
180
|
+
- `argparser.py`: Contains the `GUIHelpParser` (parser with graphical help) and `CLIMixin` (mixin for adding a parser to any class) classes.
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
<a id="doc_ru"></a>
|
|
185
|
+
# Документация пакета `pyqtcli` (PyQt/PySide CLI Integration)
|
|
186
|
+
#### [Documentation in English](#doc_en)
|
|
187
|
+
|
|
188
|
+
**PyQtCLI** — это пакет для Python, который упрощает интеграцию парсинга аргументов командной строки в приложениях с графическим интерфейсом на базе Qt (PySide/PyQt). Он позволяет легко комбинировать стандартный `argparse` с возможностью отображения справки в графическом окне (`QMessageBox`).
|
|
189
|
+
|
|
190
|
+
## Возможности
|
|
191
|
+
- **Гибкость бэкенда:** Автоматически определяет доступную библиотеку Qt (`PySide6`, `PyQt6`, `PyQt5`, `PySide2`).
|
|
192
|
+
- **Графическая справка:** Класс `GUIHelpParser` переопределяет вывод справки (`-h`, `--help`), отображая её не только в консоли, а в всплывающем окне `QMessageBox`.
|
|
193
|
+
- **Удобный миксин:** Класс `CLIMixin` предоставляет все методы `argparse.ArgumentParser` (`add_argument`, `parse_args` и т.д.) для простого добавления в ваши классы.
|
|
194
|
+
- **Готовая интеграция:** Класс `QCLIApplication` является готовым к использованию наследником `QApplication` с уже встроенным функционалом `CLIMixin`.
|
|
195
|
+
- **Типизация:** В комплекте идут `.pyi` файлы для лучшей поддержки автодополнения и проверки типов в современных IDE.
|
|
196
|
+
|
|
197
|
+
## Установка
|
|
198
|
+
Установить пакет можно напрямую из репозитория или после публикации из PyPI (замените на актуальную команду):
|
|
199
|
+
|
|
200
|
+
```shell
|
|
201
|
+
# Из репозитория
|
|
202
|
+
pip install git+https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
203
|
+
|
|
204
|
+
# Или после публикации (пример)
|
|
205
|
+
pip install pyqtcli
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Пакет не устанавливает автоматически конкретную Qt-библиотеку. Вам необходимо установить одну из поддерживаемых самостоятельно:
|
|
209
|
+
|
|
210
|
+
```shell
|
|
211
|
+
# Например, для PySide6
|
|
212
|
+
pip install pyqtcli[pyside6]
|
|
213
|
+
|
|
214
|
+
# Или для PyQt5
|
|
215
|
+
pip install pyqtcli[pyqt5]
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## Использование
|
|
219
|
+
### Быстрый старт с QCLIApplication
|
|
220
|
+
Самый простой способ создать приложение с поддержкой аргументов командной строки — использовать готовый класс `QCLIApplication`.
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
import sys
|
|
224
|
+
from pyqtcli import QCLIApplication
|
|
225
|
+
from PySide6.QtWidgets import QMainWindow, QLabel # Пример для PySide6
|
|
226
|
+
|
|
227
|
+
# Создаем экземпляр приложения, передавая аргументы командной строки
|
|
228
|
+
# Все дополнительные параметры (prog, description и т.д.) уходят в парсер.
|
|
229
|
+
app = QCLIApplication(
|
|
230
|
+
sys.argv,
|
|
231
|
+
description="Мое супер приложение",
|
|
232
|
+
epilog="Пример использования QCLIApplication"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Добавляем свои аргументы, как в обычном argparse
|
|
236
|
+
app.add_argument("-f", "--file", help="Путь к файлу для открытия")
|
|
237
|
+
app.add_argument("-v", "--verbose", action="store_true", help="Подробный вывод")
|
|
238
|
+
|
|
239
|
+
# Парсим аргументы. Справка (-h) автоматически отобразится в графическом окне.
|
|
240
|
+
args = app.parse_args()
|
|
241
|
+
|
|
242
|
+
# --- Здесь стандартный код Qt приложения ---
|
|
243
|
+
window = QMainWindow()
|
|
244
|
+
if args.file:
|
|
245
|
+
window.setCentralWidget(QLabel(f"Открыт файл: {args.file}"))
|
|
246
|
+
else:
|
|
247
|
+
window.setCentralWidget(QLabel("Привет, мир!"))
|
|
248
|
+
window.show()
|
|
249
|
+
|
|
250
|
+
sys.exit(app.exec())
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
### Использование CLIMixin в своем классе QApplication
|
|
254
|
+
Если вам нужно больше контроля или вы хотите добавить функционал парсинга в свой собственный класс приложения, используйте `CLIMixin`.
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
import sys
|
|
258
|
+
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel
|
|
259
|
+
from pyqtcli import CLIMixin
|
|
260
|
+
|
|
261
|
+
class MyApp(QApplication, CLIMixin):
|
|
262
|
+
def __init__(self, argv):
|
|
263
|
+
# Сначала инициализируем миксин с параметрами парсера
|
|
264
|
+
CLIMixin.__init__(self, description="Мое кастомное приложение")
|
|
265
|
+
# Затем инициализируем QApplication
|
|
266
|
+
QApplication.__init__(self, argv)
|
|
267
|
+
|
|
268
|
+
# Добавляем свои аргументы
|
|
269
|
+
self.add_argument("--debug", action="store_true", help="Включить режим отладки")
|
|
270
|
+
|
|
271
|
+
# Парсим аргументы
|
|
272
|
+
self.args = self.parse_args()
|
|
273
|
+
|
|
274
|
+
if self.args.debug:
|
|
275
|
+
print("Отладка включена")
|
|
276
|
+
|
|
277
|
+
# Запуск приложения
|
|
278
|
+
if __name__ == "__main__":
|
|
279
|
+
app = MyApp(sys.argv)
|
|
280
|
+
|
|
281
|
+
window = QMainWindow()
|
|
282
|
+
window.setCentralWidget(QLabel("Окно приложения"))
|
|
283
|
+
window.show()
|
|
284
|
+
|
|
285
|
+
sys.exit(app.exec())
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### Использование GUIHelpParser напрямую
|
|
289
|
+
Вы можете использовать графический парсер напрямую, например, для создания отдельного инструмента.
|
|
290
|
+
|
|
291
|
+
```python
|
|
292
|
+
import sys
|
|
293
|
+
from PySide6.QtWidgets import QApplication
|
|
294
|
+
from pyqtcli.argparser import GUIHelpParser
|
|
295
|
+
|
|
296
|
+
# Создаем парсер
|
|
297
|
+
app = QApplication(sys.argv)
|
|
298
|
+
parser = GUIHelpParser(prog="tool.py", description="Инструмент с GUI-справкой")
|
|
299
|
+
parser.add_argument("-o", "--output", help="Файл для вывода результата")
|
|
300
|
+
|
|
301
|
+
# При вызове parse_args() справка будет показана в окне,
|
|
302
|
+
# если переданы аргументы -h или --help.
|
|
303
|
+
# В противном случае парсинг пройдет как обычно.
|
|
304
|
+
args = parser.parse_args()
|
|
305
|
+
print(args)
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
## Структура пакета
|
|
309
|
+
- `__init__.py`: Основной модуль, экспортирующий классы `QCLIApplication`, `CLIMixin` и `GUIHelpParser`.
|
|
310
|
+
- `_widgets.py`: Внутренний модуль для автоматического выбора и импорта нужного Qt биндинга.
|
|
311
|
+
- `argparser.py`: Содержит классы `GUIHelpParser` (парсер с графической справкой) и `CLIMixin` (миксин для добавления парсера в любой класс).
|
pyqtcli-0.1.0/README.md
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
<a id="doc_en"></a>
|
|
2
|
+
# `pyqtcli` Documentation (PyQt/PySide CLI Integration)
|
|
3
|
+
#### [Документация на русском](#doc_ru)
|
|
4
|
+
|
|
5
|
+
**PyQtCLI** is a Python package that simplifies integrating command-line argument parsing into Qt-based GUI applications (PySide/PyQt). It allows you to easily combine the standard `argparse` module with the ability to display help messages in a graphical window (`QMessageBox`).
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
- **Backend Flexibility:** Automatically detects the available Qt binding (`PySide6`, `PyQt6`, `PyQt5`, `PySide2`).
|
|
9
|
+
- **Graphical Help:** The `GUIHelpParser` class overrides the help output (`-h`, `--help`), displaying it not only in the console but also in a pop-up `QMessageBox` window.
|
|
10
|
+
- **Convenient Mixin:** The `CLIMixin` class provides all the methods of `argparse.ArgumentParser` (`add_argument`, `parse_args`, etc.) for easy addition to your classes.
|
|
11
|
+
- **Ready-to-Use Integration:** The `QCLIApplication` class is a ready-to-use subclass of `QApplication` with the `CLIMixin` functionality already built-in.
|
|
12
|
+
- **Type Hints:** Includes `.pyi` files for better autocompletion and type checking support in modern IDEs.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
You can install the package directly from the repository or from PyPI after publication (replace with the actual command):
|
|
16
|
+
|
|
17
|
+
```shell
|
|
18
|
+
# From repository
|
|
19
|
+
pip install git+https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
20
|
+
|
|
21
|
+
# Or after publication (example)
|
|
22
|
+
pip install pyqtcli
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The package does not automatically install a specific Qt library. You need to install one of the supported bindings yourself:
|
|
26
|
+
|
|
27
|
+
```shell
|
|
28
|
+
# For example, for PySide6
|
|
29
|
+
pip install pyqtcli[pyside6]
|
|
30
|
+
|
|
31
|
+
# Or for PyQt5
|
|
32
|
+
pip install pyqtcli[pyqt5]
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
### Quick Start with QCLIApplication
|
|
37
|
+
The easiest way to create an application with command-line argument support is to use the ready-made `QCLIApplication` class.
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import sys
|
|
41
|
+
from pyqtcli import QCLIApplication
|
|
42
|
+
from PySide6.QtWidgets import QMainWindow, QLabel # Example for PySide6
|
|
43
|
+
|
|
44
|
+
# Create an application instance, passing the command-line arguments
|
|
45
|
+
# All additional parameters (prog, description, etc.) are passed to the parser.
|
|
46
|
+
app = QCLIApplication(
|
|
47
|
+
sys.argv,
|
|
48
|
+
description="My Super Application",
|
|
49
|
+
epilog="Example of using QCLIApplication"
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
# Add your own arguments, just like in standard argparse
|
|
53
|
+
app.add_argument("-f", "--file", help="Path to the file to open")
|
|
54
|
+
app.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
|
|
55
|
+
|
|
56
|
+
# Parse the arguments. Help (-h) will automatically be displayed in a graphical window.
|
|
57
|
+
args = app.parse_args()
|
|
58
|
+
|
|
59
|
+
# --- Standard Qt application code follows ---
|
|
60
|
+
window = QMainWindow()
|
|
61
|
+
if args.file:
|
|
62
|
+
window.setCentralWidget(QLabel(f"Opened file: {args.file}"))
|
|
63
|
+
else:
|
|
64
|
+
window.setCentralWidget(QLabel("Hello, world!"))
|
|
65
|
+
window.show()
|
|
66
|
+
|
|
67
|
+
sys.exit(app.exec())
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Using CLIMixin in Your Own QApplication Class
|
|
71
|
+
If you need more control or want to add parsing functionality to your own application class, use `CLIMixin`.
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
import sys
|
|
75
|
+
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel
|
|
76
|
+
from pyqtcli import CLIMixin
|
|
77
|
+
|
|
78
|
+
class MyApp(QApplication, CLIMixin):
|
|
79
|
+
def __init__(self, argv):
|
|
80
|
+
# First, initialize the mixin with parser parameters
|
|
81
|
+
CLIMixin.__init__(self, description="My Custom Application")
|
|
82
|
+
# Then initialize QApplication
|
|
83
|
+
QApplication.__init__(self, argv)
|
|
84
|
+
|
|
85
|
+
# Add your own arguments
|
|
86
|
+
self.add_argument("--debug", action="store_true", help="Enable debug mode")
|
|
87
|
+
|
|
88
|
+
# Parse the arguments
|
|
89
|
+
self.args = self.parse_args()
|
|
90
|
+
|
|
91
|
+
if self.args.debug:
|
|
92
|
+
print("Debug mode enabled")
|
|
93
|
+
|
|
94
|
+
# Run the application
|
|
95
|
+
if __name__ == "__main__":
|
|
96
|
+
app = MyApp(sys.argv)
|
|
97
|
+
|
|
98
|
+
window = QMainWindow()
|
|
99
|
+
window.setCentralWidget(QLabel("Application Window"))
|
|
100
|
+
window.show()
|
|
101
|
+
|
|
102
|
+
sys.exit(app.exec())
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Using GUIHelpParser Directly
|
|
106
|
+
You can use the graphical parser directly, for example, to create a standalone tool.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
import sys
|
|
110
|
+
from PySide6.QtWidgets import QApplication
|
|
111
|
+
from pyqtcli.argparser import GUIHelpParser
|
|
112
|
+
|
|
113
|
+
# Create the parser
|
|
114
|
+
app = QApplication(sys.argv)
|
|
115
|
+
parser = GUIHelpParser(prog="tool.py", description="Tool with GUI help")
|
|
116
|
+
parser.add_argument("-o", "--output", help="File to save the result")
|
|
117
|
+
|
|
118
|
+
# When parse_args() is called, help will be shown in a window
|
|
119
|
+
# if the -h or --help arguments are passed.
|
|
120
|
+
# Otherwise, parsing proceeds as usual.
|
|
121
|
+
args = parser.parse_args()
|
|
122
|
+
print(args)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Package Structure
|
|
126
|
+
- `__init__.py`: The main module, exporting the `QCLIApplication`, `CLIMixin`, and `GUIHelpParser` classes.
|
|
127
|
+
- `_widgets.py`: An internal module for automatically selecting and importing the required Qt binding.
|
|
128
|
+
- `argparser.py`: Contains the `GUIHelpParser` (parser with graphical help) and `CLIMixin` (mixin for adding a parser to any class) classes.
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
<a id="doc_ru"></a>
|
|
133
|
+
# Документация пакета `pyqtcli` (PyQt/PySide CLI Integration)
|
|
134
|
+
#### [Documentation in English](#doc_en)
|
|
135
|
+
|
|
136
|
+
**PyQtCLI** — это пакет для Python, который упрощает интеграцию парсинга аргументов командной строки в приложениях с графическим интерфейсом на базе Qt (PySide/PyQt). Он позволяет легко комбинировать стандартный `argparse` с возможностью отображения справки в графическом окне (`QMessageBox`).
|
|
137
|
+
|
|
138
|
+
## Возможности
|
|
139
|
+
- **Гибкость бэкенда:** Автоматически определяет доступную библиотеку Qt (`PySide6`, `PyQt6`, `PyQt5`, `PySide2`).
|
|
140
|
+
- **Графическая справка:** Класс `GUIHelpParser` переопределяет вывод справки (`-h`, `--help`), отображая её не только в консоли, а в всплывающем окне `QMessageBox`.
|
|
141
|
+
- **Удобный миксин:** Класс `CLIMixin` предоставляет все методы `argparse.ArgumentParser` (`add_argument`, `parse_args` и т.д.) для простого добавления в ваши классы.
|
|
142
|
+
- **Готовая интеграция:** Класс `QCLIApplication` является готовым к использованию наследником `QApplication` с уже встроенным функционалом `CLIMixin`.
|
|
143
|
+
- **Типизация:** В комплекте идут `.pyi` файлы для лучшей поддержки автодополнения и проверки типов в современных IDE.
|
|
144
|
+
|
|
145
|
+
## Установка
|
|
146
|
+
Установить пакет можно напрямую из репозитория или после публикации из PyPI (замените на актуальную команду):
|
|
147
|
+
|
|
148
|
+
```shell
|
|
149
|
+
# Из репозитория
|
|
150
|
+
pip install git+https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
151
|
+
|
|
152
|
+
# Или после публикации (пример)
|
|
153
|
+
pip install pyqtcli
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Пакет не устанавливает автоматически конкретную Qt-библиотеку. Вам необходимо установить одну из поддерживаемых самостоятельно:
|
|
157
|
+
|
|
158
|
+
```shell
|
|
159
|
+
# Например, для PySide6
|
|
160
|
+
pip install pyqtcli[pyside6]
|
|
161
|
+
|
|
162
|
+
# Или для PyQt5
|
|
163
|
+
pip install pyqtcli[pyqt5]
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## Использование
|
|
167
|
+
### Быстрый старт с QCLIApplication
|
|
168
|
+
Самый простой способ создать приложение с поддержкой аргументов командной строки — использовать готовый класс `QCLIApplication`.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
import sys
|
|
172
|
+
from pyqtcli import QCLIApplication
|
|
173
|
+
from PySide6.QtWidgets import QMainWindow, QLabel # Пример для PySide6
|
|
174
|
+
|
|
175
|
+
# Создаем экземпляр приложения, передавая аргументы командной строки
|
|
176
|
+
# Все дополнительные параметры (prog, description и т.д.) уходят в парсер.
|
|
177
|
+
app = QCLIApplication(
|
|
178
|
+
sys.argv,
|
|
179
|
+
description="Мое супер приложение",
|
|
180
|
+
epilog="Пример использования QCLIApplication"
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
# Добавляем свои аргументы, как в обычном argparse
|
|
184
|
+
app.add_argument("-f", "--file", help="Путь к файлу для открытия")
|
|
185
|
+
app.add_argument("-v", "--verbose", action="store_true", help="Подробный вывод")
|
|
186
|
+
|
|
187
|
+
# Парсим аргументы. Справка (-h) автоматически отобразится в графическом окне.
|
|
188
|
+
args = app.parse_args()
|
|
189
|
+
|
|
190
|
+
# --- Здесь стандартный код Qt приложения ---
|
|
191
|
+
window = QMainWindow()
|
|
192
|
+
if args.file:
|
|
193
|
+
window.setCentralWidget(QLabel(f"Открыт файл: {args.file}"))
|
|
194
|
+
else:
|
|
195
|
+
window.setCentralWidget(QLabel("Привет, мир!"))
|
|
196
|
+
window.show()
|
|
197
|
+
|
|
198
|
+
sys.exit(app.exec())
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### Использование CLIMixin в своем классе QApplication
|
|
202
|
+
Если вам нужно больше контроля или вы хотите добавить функционал парсинга в свой собственный класс приложения, используйте `CLIMixin`.
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
import sys
|
|
206
|
+
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel
|
|
207
|
+
from pyqtcli import CLIMixin
|
|
208
|
+
|
|
209
|
+
class MyApp(QApplication, CLIMixin):
|
|
210
|
+
def __init__(self, argv):
|
|
211
|
+
# Сначала инициализируем миксин с параметрами парсера
|
|
212
|
+
CLIMixin.__init__(self, description="Мое кастомное приложение")
|
|
213
|
+
# Затем инициализируем QApplication
|
|
214
|
+
QApplication.__init__(self, argv)
|
|
215
|
+
|
|
216
|
+
# Добавляем свои аргументы
|
|
217
|
+
self.add_argument("--debug", action="store_true", help="Включить режим отладки")
|
|
218
|
+
|
|
219
|
+
# Парсим аргументы
|
|
220
|
+
self.args = self.parse_args()
|
|
221
|
+
|
|
222
|
+
if self.args.debug:
|
|
223
|
+
print("Отладка включена")
|
|
224
|
+
|
|
225
|
+
# Запуск приложения
|
|
226
|
+
if __name__ == "__main__":
|
|
227
|
+
app = MyApp(sys.argv)
|
|
228
|
+
|
|
229
|
+
window = QMainWindow()
|
|
230
|
+
window.setCentralWidget(QLabel("Окно приложения"))
|
|
231
|
+
window.show()
|
|
232
|
+
|
|
233
|
+
sys.exit(app.exec())
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### Использование GUIHelpParser напрямую
|
|
237
|
+
Вы можете использовать графический парсер напрямую, например, для создания отдельного инструмента.
|
|
238
|
+
|
|
239
|
+
```python
|
|
240
|
+
import sys
|
|
241
|
+
from PySide6.QtWidgets import QApplication
|
|
242
|
+
from pyqtcli.argparser import GUIHelpParser
|
|
243
|
+
|
|
244
|
+
# Создаем парсер
|
|
245
|
+
app = QApplication(sys.argv)
|
|
246
|
+
parser = GUIHelpParser(prog="tool.py", description="Инструмент с GUI-справкой")
|
|
247
|
+
parser.add_argument("-o", "--output", help="Файл для вывода результата")
|
|
248
|
+
|
|
249
|
+
# При вызове parse_args() справка будет показана в окне,
|
|
250
|
+
# если переданы аргументы -h или --help.
|
|
251
|
+
# В противном случае парсинг пройдет как обычно.
|
|
252
|
+
args = parser.parse_args()
|
|
253
|
+
print(args)
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## Структура пакета
|
|
257
|
+
- `__init__.py`: Основной модуль, экспортирующий классы `QCLIApplication`, `CLIMixin` и `GUIHelpParser`.
|
|
258
|
+
- `_widgets.py`: Внутренний модуль для автоматического выбора и импорта нужного Qt биндинга.
|
|
259
|
+
- `argparser.py`: Содержит классы `GUIHelpParser` (парсер с графической справкой) и `CLIMixin` (миксин для добавления парсера в любой класс).
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pyqtcli"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Package for supporting command-line arguments in Qt for Python applications"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
authors = [
|
|
11
|
+
{name = "Маг Ильяс DOMA (MagIlyasDOMA)", email = "magilyas.doma.09@list.ru"},
|
|
12
|
+
]
|
|
13
|
+
license = {text = "MIT"}
|
|
14
|
+
classifiers = [
|
|
15
|
+
"License :: OSI Approved :: MIT License",
|
|
16
|
+
"Operating System :: Microsoft :: Windows :: Windows 10",
|
|
17
|
+
"Operating System :: Microsoft :: Windows :: Windows 11",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Programming Language :: Python :: 3.14",
|
|
24
|
+
"Framework :: Django",
|
|
25
|
+
"Framework :: Django :: 5.2",
|
|
26
|
+
"Framework :: Django :: 6.0",
|
|
27
|
+
"Natural Language :: English",
|
|
28
|
+
"Natural Language :: Russian",
|
|
29
|
+
"Topic :: Software Development :: Libraries",
|
|
30
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
31
|
+
"Topic :: Utilities",
|
|
32
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
33
|
+
"Topic :: Security :: Cryptography",
|
|
34
|
+
"Topic :: Text Processing :: Markup",
|
|
35
|
+
"Topic :: Text Processing :: Markup :: HTML",
|
|
36
|
+
]
|
|
37
|
+
requires-python = ">=3.9"
|
|
38
|
+
dependencies = ["argparse-typing>=0.2.0"]
|
|
39
|
+
|
|
40
|
+
[project.optional-dependencies]
|
|
41
|
+
pyside = ["Pyside2>=5.12.0"]
|
|
42
|
+
pyside2 = ["Pyside2>=5.12.0"]
|
|
43
|
+
pyside6 = ["Pyside6>=6.0.0"]
|
|
44
|
+
pyqt = ["PyQt5>=5.0.0"]
|
|
45
|
+
pyqt5 = ["PyQt5>=5.0.0"]
|
|
46
|
+
pyqt6 = ["PyQt6>=6.0.0"]
|
|
47
|
+
dev = [
|
|
48
|
+
"setuptools>=61.0.0",
|
|
49
|
+
"wheel>=0.46.3",
|
|
50
|
+
"twine>=6.2.0",
|
|
51
|
+
"build>=1.4.0"
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
[project.urls]
|
|
55
|
+
Source = "https://github.com/MagIlyasDOMA/pyqtcli"
|
|
56
|
+
Repository = "https://github.com/MagIlyasDOMA/pyqtcli.git"
|
|
57
|
+
|
|
58
|
+
[tool.setuptools]
|
|
59
|
+
packages = {find = {}}
|
|
60
|
+
package-data = {"pyqtcli" = ["*.pyi", "py.typed"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from ._widgets import QApplication
|
|
2
|
+
from .argparser import CLIMixin, GUIHelpParser
|
|
3
|
+
|
|
4
|
+
__version__ = '0.1.0'
|
|
5
|
+
__all__ = ['QCLIApplication', 'CLIMixin', 'GUIHelpParser']
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class QCLIApplication(QApplication, CLIMixin):
|
|
9
|
+
def __init__(self, argv, *args, **kwargs):
|
|
10
|
+
CLIMixin.__init__(self, *args, **kwargs)
|
|
11
|
+
QApplication.__init__(self, argv)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from argparse import ArgumentParser, _FormatterClass
|
|
3
|
+
from typing import Final, Sequence, Any
|
|
4
|
+
from ._widgets import QApplication
|
|
5
|
+
from .argparser import CLIMixin, GUIHelpParser
|
|
6
|
+
|
|
7
|
+
__version__: Final[str] = '1.0.0'
|
|
8
|
+
__all__: Final[str] = ['QCLIApplication', 'CLIMixin', 'GUIHelpParser']
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class QCLIApplication(QApplication, CLIMixin):
|
|
12
|
+
if sys.version_info >= (3, 14):
|
|
13
|
+
def __init__(
|
|
14
|
+
self,
|
|
15
|
+
argv: Sequence[str],
|
|
16
|
+
prog: str | None = None,
|
|
17
|
+
usage: str | None = None,
|
|
18
|
+
description: str | None = None,
|
|
19
|
+
epilog: str | None = None,
|
|
20
|
+
parents: Sequence[ArgumentParser] = [],
|
|
21
|
+
formatter_class: _FormatterClass = ...,
|
|
22
|
+
prefix_chars: str = "-",
|
|
23
|
+
fromfile_prefix_chars: str | None = None,
|
|
24
|
+
argument_default: Any = None,
|
|
25
|
+
conflict_handler: str = "error",
|
|
26
|
+
add_help: bool = True,
|
|
27
|
+
allow_abbrev: bool = True,
|
|
28
|
+
exit_on_error: bool = True,
|
|
29
|
+
*,
|
|
30
|
+
suggest_on_error: bool = False,
|
|
31
|
+
color: bool = False,
|
|
32
|
+
) -> None: ...
|
|
33
|
+
else:
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
argv: Sequence[str],
|
|
37
|
+
prog: str | None = None,
|
|
38
|
+
usage: str | None = None,
|
|
39
|
+
description: str | None = None,
|
|
40
|
+
epilog: str | None = None,
|
|
41
|
+
parents: Sequence[ArgumentParser] = [],
|
|
42
|
+
formatter_class: _FormatterClass = ...,
|
|
43
|
+
prefix_chars: str = "-",
|
|
44
|
+
fromfile_prefix_chars: str | None = None,
|
|
45
|
+
argument_default: Any = None,
|
|
46
|
+
conflict_handler: str = "error",
|
|
47
|
+
add_help: bool = True,
|
|
48
|
+
allow_abbrev: bool = True,
|
|
49
|
+
exit_on_error: bool = True,
|
|
50
|
+
) -> None: ...
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
# Определяем доступный Qt биндинг
|
|
5
|
+
def get_qt_binding():
|
|
6
|
+
for binding in ['PySide6', 'PyQt6', 'PyQt5', 'PySide2']:
|
|
7
|
+
try:
|
|
8
|
+
module = importlib.import_module(f"{binding}.QtWidgets")
|
|
9
|
+
return binding, module
|
|
10
|
+
except ImportError:
|
|
11
|
+
continue
|
|
12
|
+
raise ImportError("No Qt binding found")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
QT_BINDING, QtWidgets = get_qt_binding()
|
|
16
|
+
|
|
17
|
+
QApplication = QtWidgets.QApplication
|
|
18
|
+
QMessageBox = QtWidgets.QMessageBox
|
|
19
|
+
QMainWindow = QtWidgets.QMainWindow
|
|
20
|
+
QWidget = QtWidgets.QWidget
|
|
21
|
+
QDialog = QtWidgets.QDialog
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from ._widgets import QT_BINDING, QMessageBox
|
|
3
|
+
|
|
4
|
+
__all__ = ['GUIHelpParser', 'CLIMixin']
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class GUIHelpParser(argparse.ArgumentParser):
|
|
8
|
+
def __init__(self, *args, **kwargs):
|
|
9
|
+
super().__init__(*args, **kwargs)
|
|
10
|
+
self.messagebox = self._init_messagebox()
|
|
11
|
+
|
|
12
|
+
def _init_messagebox(self):
|
|
13
|
+
messagebox = QMessageBox()
|
|
14
|
+
messagebox.setWindowTitle("Help")
|
|
15
|
+
|
|
16
|
+
# Совместимость с разными версиями Qt
|
|
17
|
+
if QT_BINDING in ['PySide6', 'PyQt6']:
|
|
18
|
+
messagebox.setIcon(QMessageBox.Icon.Information)
|
|
19
|
+
else: # PyQt5, PySide2
|
|
20
|
+
messagebox.setIcon(QMessageBox.Information)
|
|
21
|
+
|
|
22
|
+
messagebox.setText(self.format_help())
|
|
23
|
+
return messagebox
|
|
24
|
+
|
|
25
|
+
def print_help(self, file=None):
|
|
26
|
+
super().print_help(file)
|
|
27
|
+
try:
|
|
28
|
+
self.messagebox.exec()
|
|
29
|
+
except AttributeError:
|
|
30
|
+
self.messagebox.exec_()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CLIMixin:
|
|
34
|
+
def __init__(self, *args, **kwargs):
|
|
35
|
+
self.parser = GUIHelpParser(*args, **kwargs)
|
|
36
|
+
|
|
37
|
+
def add_argument(self, *name_or_flags, **kwargs):
|
|
38
|
+
return self.parser.add_argument(*name_or_flags, **kwargs)
|
|
39
|
+
|
|
40
|
+
def add_argument_group(self, *args, **kwargs):
|
|
41
|
+
return self.parser.add_argument_group(*args, **kwargs)
|
|
42
|
+
|
|
43
|
+
def add_mutually_exclusive_group(self, *args, **kwargs):
|
|
44
|
+
return self.parser.add_mutually_exclusive_group(*args, **kwargs)
|
|
45
|
+
|
|
46
|
+
def add_subparsers(self, *args, **kwargs):
|
|
47
|
+
return self.parser.add_subparsers(*args, **kwargs)
|
|
48
|
+
|
|
49
|
+
def parse_args(self, *args, **kwargs):
|
|
50
|
+
return self.parser.parse_args(*args, **kwargs)
|
|
51
|
+
|
|
52
|
+
def parse_known_args(self, *args, **kwargs):
|
|
53
|
+
return self.parser.parse_known_args(*args, **kwargs)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def messagebox(self):
|
|
57
|
+
return self.parser.messagebox
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from argparse import ArgumentParser, _N, Namespace, _SubParsersAction, Action, _FormatterClass, _ArgumentParserT, \
|
|
3
|
+
_ActionTyping, _NargsType, _ActionType, _T, _ArgumentGroup, _MutuallyExclusiveGroup
|
|
4
|
+
from typing import Sequence, Any, overload, Optional, Iterable, Final
|
|
5
|
+
from ._widgets import QMessageBox
|
|
6
|
+
|
|
7
|
+
__all__: Final[str] = ['GUIHelpParser', 'CLIMixin']
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GUIHelpParser(ArgumentParser):
|
|
11
|
+
def __init__(self, *args, **kwargs) -> None:
|
|
12
|
+
self.messagebox: QMessageBox = ...
|
|
13
|
+
|
|
14
|
+
def _init_messagebox(self) -> QMessageBox: ...
|
|
15
|
+
|
|
16
|
+
def print_help(self, file=None) -> None: ...
|
|
17
|
+
|
|
18
|
+
class CLIMixin:
|
|
19
|
+
if sys.version_info >= (3, 14):
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
prog: str | None = None,
|
|
23
|
+
usage: str | None = None,
|
|
24
|
+
description: str | None = None,
|
|
25
|
+
epilog: str | None = None,
|
|
26
|
+
parents: Sequence[ArgumentParser] = [],
|
|
27
|
+
formatter_class: _FormatterClass = ...,
|
|
28
|
+
prefix_chars: str = "-",
|
|
29
|
+
fromfile_prefix_chars: str | None = None,
|
|
30
|
+
argument_default: Any = None,
|
|
31
|
+
conflict_handler: str = "error",
|
|
32
|
+
add_help: bool = True,
|
|
33
|
+
allow_abbrev: bool = True,
|
|
34
|
+
exit_on_error: bool = True,
|
|
35
|
+
*,
|
|
36
|
+
suggest_on_error: bool = False,
|
|
37
|
+
color: bool = False,
|
|
38
|
+
) -> None:
|
|
39
|
+
self.parser: GUIHelpParser = ...
|
|
40
|
+
else:
|
|
41
|
+
def __init__(
|
|
42
|
+
self,
|
|
43
|
+
prog: str | None = None,
|
|
44
|
+
usage: str | None = None,
|
|
45
|
+
description: str | None = None,
|
|
46
|
+
epilog: str | None = None,
|
|
47
|
+
parents: Sequence[ArgumentParser] = [],
|
|
48
|
+
formatter_class: _FormatterClass = ...,
|
|
49
|
+
prefix_chars: str = "-",
|
|
50
|
+
fromfile_prefix_chars: str | None = None,
|
|
51
|
+
argument_default: Any = None,
|
|
52
|
+
conflict_handler: str = "error",
|
|
53
|
+
add_help: bool = True,
|
|
54
|
+
allow_abbrev: bool = True,
|
|
55
|
+
exit_on_error: bool = True,
|
|
56
|
+
) -> None:
|
|
57
|
+
self.parser: GUIHelpParser = ...
|
|
58
|
+
|
|
59
|
+
def add_argument(
|
|
60
|
+
self,
|
|
61
|
+
*name_or_flags: str,
|
|
62
|
+
# str covers predefined actions ("store_true", "count", etc.)
|
|
63
|
+
# and user registered actions via the `register` method.
|
|
64
|
+
action: _ActionTyping = ...,
|
|
65
|
+
# more precisely, Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="],
|
|
66
|
+
# but using this would make it hard to annotate callers that don't use a
|
|
67
|
+
# literal argument and for subclasses to override this method.
|
|
68
|
+
nargs: Optional[_NargsType] = None,
|
|
69
|
+
const: Any = ...,
|
|
70
|
+
default: Any = ...,
|
|
71
|
+
type: _ActionType = ...,
|
|
72
|
+
choices: Iterable[_T] | None = ...,
|
|
73
|
+
required: bool = ...,
|
|
74
|
+
help: str | None = ...,
|
|
75
|
+
metavar: str | tuple[str, ...] | None = ...,
|
|
76
|
+
dest: str | None = ...,
|
|
77
|
+
version: str = ...,
|
|
78
|
+
**kwargs: Any,
|
|
79
|
+
) -> Action: ...
|
|
80
|
+
|
|
81
|
+
def add_argument_group(
|
|
82
|
+
self,
|
|
83
|
+
title: str | None = None,
|
|
84
|
+
description: str | None = None,
|
|
85
|
+
*,
|
|
86
|
+
prefix_chars: str = ...,
|
|
87
|
+
argument_default: Any = ...,
|
|
88
|
+
conflict_handler: str = ...,
|
|
89
|
+
) -> _ArgumentGroup: ...
|
|
90
|
+
def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup: ...
|
|
91
|
+
|
|
92
|
+
@overload
|
|
93
|
+
def parse_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ...
|
|
94
|
+
@overload
|
|
95
|
+
def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ...
|
|
96
|
+
@overload
|
|
97
|
+
def parse_args(self, *, namespace: _N) -> _N: ...
|
|
98
|
+
|
|
99
|
+
@overload
|
|
100
|
+
def add_subparsers(
|
|
101
|
+
self: _ArgumentParserT,
|
|
102
|
+
*,
|
|
103
|
+
title: str = "subcommands",
|
|
104
|
+
description: str | None = None,
|
|
105
|
+
prog: str | None = None,
|
|
106
|
+
action: type[Action] = ...,
|
|
107
|
+
option_string: str = ...,
|
|
108
|
+
dest: str | None = None,
|
|
109
|
+
required: bool = False,
|
|
110
|
+
help: str | None = None,
|
|
111
|
+
metavar: str | None = None,
|
|
112
|
+
) -> _SubParsersAction[_ArgumentParserT]: ...
|
|
113
|
+
@overload
|
|
114
|
+
def add_subparsers(
|
|
115
|
+
self,
|
|
116
|
+
*,
|
|
117
|
+
title: str = "subcommands",
|
|
118
|
+
description: str | None = None,
|
|
119
|
+
prog: str | None = None,
|
|
120
|
+
parser_class: type[_ArgumentParserT],
|
|
121
|
+
action: type[Action] = ...,
|
|
122
|
+
option_string: str = ...,
|
|
123
|
+
dest: str | None = None,
|
|
124
|
+
required: bool = False,
|
|
125
|
+
help: str | None = None,
|
|
126
|
+
metavar: str | None = None,
|
|
127
|
+
) -> _SubParsersAction[_ArgumentParserT]: ...
|
|
128
|
+
|
|
129
|
+
@overload
|
|
130
|
+
def parse_known_args(self, args: Sequence[str] | None = None, namespace: None = None) -> tuple[
|
|
131
|
+
Namespace, list[str]]: ...
|
|
132
|
+
@overload
|
|
133
|
+
def parse_known_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ...
|
|
134
|
+
@overload
|
|
135
|
+
def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ...
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def messagebox(self) -> QMessageBox:
|
|
139
|
+
return self.parser.messagebox
|
|
File without changes
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pyqtcli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Package for supporting command-line arguments in Qt for Python applications
|
|
5
|
+
Author-email: "Маг Ильяс DOMA (MagIlyasDOMA)" <magilyas.doma.09@list.ru>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Source, https://github.com/MagIlyasDOMA/pyqtcli
|
|
8
|
+
Project-URL: Repository, https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: Microsoft :: Windows :: Windows 10
|
|
11
|
+
Classifier: Operating System :: Microsoft :: Windows :: Windows 11
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
18
|
+
Classifier: Framework :: Django
|
|
19
|
+
Classifier: Framework :: Django :: 5.2
|
|
20
|
+
Classifier: Framework :: Django :: 6.0
|
|
21
|
+
Classifier: Natural Language :: English
|
|
22
|
+
Classifier: Natural Language :: Russian
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Topic :: Utilities
|
|
26
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
27
|
+
Classifier: Topic :: Security :: Cryptography
|
|
28
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
29
|
+
Classifier: Topic :: Text Processing :: Markup :: HTML
|
|
30
|
+
Requires-Python: >=3.9
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
License-File: LICENSE
|
|
33
|
+
Requires-Dist: argparse-typing>=0.2.0
|
|
34
|
+
Provides-Extra: pyside
|
|
35
|
+
Requires-Dist: Pyside2>=5.12.0; extra == "pyside"
|
|
36
|
+
Provides-Extra: pyside2
|
|
37
|
+
Requires-Dist: Pyside2>=5.12.0; extra == "pyside2"
|
|
38
|
+
Provides-Extra: pyside6
|
|
39
|
+
Requires-Dist: Pyside6>=6.0.0; extra == "pyside6"
|
|
40
|
+
Provides-Extra: pyqt
|
|
41
|
+
Requires-Dist: PyQt5>=5.0.0; extra == "pyqt"
|
|
42
|
+
Provides-Extra: pyqt5
|
|
43
|
+
Requires-Dist: PyQt5>=5.0.0; extra == "pyqt5"
|
|
44
|
+
Provides-Extra: pyqt6
|
|
45
|
+
Requires-Dist: PyQt6>=6.0.0; extra == "pyqt6"
|
|
46
|
+
Provides-Extra: dev
|
|
47
|
+
Requires-Dist: setuptools>=61.0.0; extra == "dev"
|
|
48
|
+
Requires-Dist: wheel>=0.46.3; extra == "dev"
|
|
49
|
+
Requires-Dist: twine>=6.2.0; extra == "dev"
|
|
50
|
+
Requires-Dist: build>=1.4.0; extra == "dev"
|
|
51
|
+
Dynamic: license-file
|
|
52
|
+
|
|
53
|
+
<a id="doc_en"></a>
|
|
54
|
+
# `pyqtcli` Documentation (PyQt/PySide CLI Integration)
|
|
55
|
+
#### [Документация на русском](#doc_ru)
|
|
56
|
+
|
|
57
|
+
**PyQtCLI** is a Python package that simplifies integrating command-line argument parsing into Qt-based GUI applications (PySide/PyQt). It allows you to easily combine the standard `argparse` module with the ability to display help messages in a graphical window (`QMessageBox`).
|
|
58
|
+
|
|
59
|
+
## Features
|
|
60
|
+
- **Backend Flexibility:** Automatically detects the available Qt binding (`PySide6`, `PyQt6`, `PyQt5`, `PySide2`).
|
|
61
|
+
- **Graphical Help:** The `GUIHelpParser` class overrides the help output (`-h`, `--help`), displaying it not only in the console but also in a pop-up `QMessageBox` window.
|
|
62
|
+
- **Convenient Mixin:** The `CLIMixin` class provides all the methods of `argparse.ArgumentParser` (`add_argument`, `parse_args`, etc.) for easy addition to your classes.
|
|
63
|
+
- **Ready-to-Use Integration:** The `QCLIApplication` class is a ready-to-use subclass of `QApplication` with the `CLIMixin` functionality already built-in.
|
|
64
|
+
- **Type Hints:** Includes `.pyi` files for better autocompletion and type checking support in modern IDEs.
|
|
65
|
+
|
|
66
|
+
## Installation
|
|
67
|
+
You can install the package directly from the repository or from PyPI after publication (replace with the actual command):
|
|
68
|
+
|
|
69
|
+
```shell
|
|
70
|
+
# From repository
|
|
71
|
+
pip install git+https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
72
|
+
|
|
73
|
+
# Or after publication (example)
|
|
74
|
+
pip install pyqtcli
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The package does not automatically install a specific Qt library. You need to install one of the supported bindings yourself:
|
|
78
|
+
|
|
79
|
+
```shell
|
|
80
|
+
# For example, for PySide6
|
|
81
|
+
pip install pyqtcli[pyside6]
|
|
82
|
+
|
|
83
|
+
# Or for PyQt5
|
|
84
|
+
pip install pyqtcli[pyqt5]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Usage
|
|
88
|
+
### Quick Start with QCLIApplication
|
|
89
|
+
The easiest way to create an application with command-line argument support is to use the ready-made `QCLIApplication` class.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import sys
|
|
93
|
+
from pyqtcli import QCLIApplication
|
|
94
|
+
from PySide6.QtWidgets import QMainWindow, QLabel # Example for PySide6
|
|
95
|
+
|
|
96
|
+
# Create an application instance, passing the command-line arguments
|
|
97
|
+
# All additional parameters (prog, description, etc.) are passed to the parser.
|
|
98
|
+
app = QCLIApplication(
|
|
99
|
+
sys.argv,
|
|
100
|
+
description="My Super Application",
|
|
101
|
+
epilog="Example of using QCLIApplication"
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
# Add your own arguments, just like in standard argparse
|
|
105
|
+
app.add_argument("-f", "--file", help="Path to the file to open")
|
|
106
|
+
app.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
|
|
107
|
+
|
|
108
|
+
# Parse the arguments. Help (-h) will automatically be displayed in a graphical window.
|
|
109
|
+
args = app.parse_args()
|
|
110
|
+
|
|
111
|
+
# --- Standard Qt application code follows ---
|
|
112
|
+
window = QMainWindow()
|
|
113
|
+
if args.file:
|
|
114
|
+
window.setCentralWidget(QLabel(f"Opened file: {args.file}"))
|
|
115
|
+
else:
|
|
116
|
+
window.setCentralWidget(QLabel("Hello, world!"))
|
|
117
|
+
window.show()
|
|
118
|
+
|
|
119
|
+
sys.exit(app.exec())
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Using CLIMixin in Your Own QApplication Class
|
|
123
|
+
If you need more control or want to add parsing functionality to your own application class, use `CLIMixin`.
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
import sys
|
|
127
|
+
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel
|
|
128
|
+
from pyqtcli import CLIMixin
|
|
129
|
+
|
|
130
|
+
class MyApp(QApplication, CLIMixin):
|
|
131
|
+
def __init__(self, argv):
|
|
132
|
+
# First, initialize the mixin with parser parameters
|
|
133
|
+
CLIMixin.__init__(self, description="My Custom Application")
|
|
134
|
+
# Then initialize QApplication
|
|
135
|
+
QApplication.__init__(self, argv)
|
|
136
|
+
|
|
137
|
+
# Add your own arguments
|
|
138
|
+
self.add_argument("--debug", action="store_true", help="Enable debug mode")
|
|
139
|
+
|
|
140
|
+
# Parse the arguments
|
|
141
|
+
self.args = self.parse_args()
|
|
142
|
+
|
|
143
|
+
if self.args.debug:
|
|
144
|
+
print("Debug mode enabled")
|
|
145
|
+
|
|
146
|
+
# Run the application
|
|
147
|
+
if __name__ == "__main__":
|
|
148
|
+
app = MyApp(sys.argv)
|
|
149
|
+
|
|
150
|
+
window = QMainWindow()
|
|
151
|
+
window.setCentralWidget(QLabel("Application Window"))
|
|
152
|
+
window.show()
|
|
153
|
+
|
|
154
|
+
sys.exit(app.exec())
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Using GUIHelpParser Directly
|
|
158
|
+
You can use the graphical parser directly, for example, to create a standalone tool.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
import sys
|
|
162
|
+
from PySide6.QtWidgets import QApplication
|
|
163
|
+
from pyqtcli.argparser import GUIHelpParser
|
|
164
|
+
|
|
165
|
+
# Create the parser
|
|
166
|
+
app = QApplication(sys.argv)
|
|
167
|
+
parser = GUIHelpParser(prog="tool.py", description="Tool with GUI help")
|
|
168
|
+
parser.add_argument("-o", "--output", help="File to save the result")
|
|
169
|
+
|
|
170
|
+
# When parse_args() is called, help will be shown in a window
|
|
171
|
+
# if the -h or --help arguments are passed.
|
|
172
|
+
# Otherwise, parsing proceeds as usual.
|
|
173
|
+
args = parser.parse_args()
|
|
174
|
+
print(args)
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
Package Structure
|
|
178
|
+
- `__init__.py`: The main module, exporting the `QCLIApplication`, `CLIMixin`, and `GUIHelpParser` classes.
|
|
179
|
+
- `_widgets.py`: An internal module for automatically selecting and importing the required Qt binding.
|
|
180
|
+
- `argparser.py`: Contains the `GUIHelpParser` (parser with graphical help) and `CLIMixin` (mixin for adding a parser to any class) classes.
|
|
181
|
+
|
|
182
|
+
---
|
|
183
|
+
|
|
184
|
+
<a id="doc_ru"></a>
|
|
185
|
+
# Документация пакета `pyqtcli` (PyQt/PySide CLI Integration)
|
|
186
|
+
#### [Documentation in English](#doc_en)
|
|
187
|
+
|
|
188
|
+
**PyQtCLI** — это пакет для Python, который упрощает интеграцию парсинга аргументов командной строки в приложениях с графическим интерфейсом на базе Qt (PySide/PyQt). Он позволяет легко комбинировать стандартный `argparse` с возможностью отображения справки в графическом окне (`QMessageBox`).
|
|
189
|
+
|
|
190
|
+
## Возможности
|
|
191
|
+
- **Гибкость бэкенда:** Автоматически определяет доступную библиотеку Qt (`PySide6`, `PyQt6`, `PyQt5`, `PySide2`).
|
|
192
|
+
- **Графическая справка:** Класс `GUIHelpParser` переопределяет вывод справки (`-h`, `--help`), отображая её не только в консоли, а в всплывающем окне `QMessageBox`.
|
|
193
|
+
- **Удобный миксин:** Класс `CLIMixin` предоставляет все методы `argparse.ArgumentParser` (`add_argument`, `parse_args` и т.д.) для простого добавления в ваши классы.
|
|
194
|
+
- **Готовая интеграция:** Класс `QCLIApplication` является готовым к использованию наследником `QApplication` с уже встроенным функционалом `CLIMixin`.
|
|
195
|
+
- **Типизация:** В комплекте идут `.pyi` файлы для лучшей поддержки автодополнения и проверки типов в современных IDE.
|
|
196
|
+
|
|
197
|
+
## Установка
|
|
198
|
+
Установить пакет можно напрямую из репозитория или после публикации из PyPI (замените на актуальную команду):
|
|
199
|
+
|
|
200
|
+
```shell
|
|
201
|
+
# Из репозитория
|
|
202
|
+
pip install git+https://github.com/MagIlyasDOMA/pyqtcli.git
|
|
203
|
+
|
|
204
|
+
# Или после публикации (пример)
|
|
205
|
+
pip install pyqtcli
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Пакет не устанавливает автоматически конкретную Qt-библиотеку. Вам необходимо установить одну из поддерживаемых самостоятельно:
|
|
209
|
+
|
|
210
|
+
```shell
|
|
211
|
+
# Например, для PySide6
|
|
212
|
+
pip install pyqtcli[pyside6]
|
|
213
|
+
|
|
214
|
+
# Или для PyQt5
|
|
215
|
+
pip install pyqtcli[pyqt5]
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## Использование
|
|
219
|
+
### Быстрый старт с QCLIApplication
|
|
220
|
+
Самый простой способ создать приложение с поддержкой аргументов командной строки — использовать готовый класс `QCLIApplication`.
|
|
221
|
+
|
|
222
|
+
```python
|
|
223
|
+
import sys
|
|
224
|
+
from pyqtcli import QCLIApplication
|
|
225
|
+
from PySide6.QtWidgets import QMainWindow, QLabel # Пример для PySide6
|
|
226
|
+
|
|
227
|
+
# Создаем экземпляр приложения, передавая аргументы командной строки
|
|
228
|
+
# Все дополнительные параметры (prog, description и т.д.) уходят в парсер.
|
|
229
|
+
app = QCLIApplication(
|
|
230
|
+
sys.argv,
|
|
231
|
+
description="Мое супер приложение",
|
|
232
|
+
epilog="Пример использования QCLIApplication"
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Добавляем свои аргументы, как в обычном argparse
|
|
236
|
+
app.add_argument("-f", "--file", help="Путь к файлу для открытия")
|
|
237
|
+
app.add_argument("-v", "--verbose", action="store_true", help="Подробный вывод")
|
|
238
|
+
|
|
239
|
+
# Парсим аргументы. Справка (-h) автоматически отобразится в графическом окне.
|
|
240
|
+
args = app.parse_args()
|
|
241
|
+
|
|
242
|
+
# --- Здесь стандартный код Qt приложения ---
|
|
243
|
+
window = QMainWindow()
|
|
244
|
+
if args.file:
|
|
245
|
+
window.setCentralWidget(QLabel(f"Открыт файл: {args.file}"))
|
|
246
|
+
else:
|
|
247
|
+
window.setCentralWidget(QLabel("Привет, мир!"))
|
|
248
|
+
window.show()
|
|
249
|
+
|
|
250
|
+
sys.exit(app.exec())
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
### Использование CLIMixin в своем классе QApplication
|
|
254
|
+
Если вам нужно больше контроля или вы хотите добавить функционал парсинга в свой собственный класс приложения, используйте `CLIMixin`.
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
import sys
|
|
258
|
+
from PySide6.QtWidgets import QApplication, QMainWindow, QLabel
|
|
259
|
+
from pyqtcli import CLIMixin
|
|
260
|
+
|
|
261
|
+
class MyApp(QApplication, CLIMixin):
|
|
262
|
+
def __init__(self, argv):
|
|
263
|
+
# Сначала инициализируем миксин с параметрами парсера
|
|
264
|
+
CLIMixin.__init__(self, description="Мое кастомное приложение")
|
|
265
|
+
# Затем инициализируем QApplication
|
|
266
|
+
QApplication.__init__(self, argv)
|
|
267
|
+
|
|
268
|
+
# Добавляем свои аргументы
|
|
269
|
+
self.add_argument("--debug", action="store_true", help="Включить режим отладки")
|
|
270
|
+
|
|
271
|
+
# Парсим аргументы
|
|
272
|
+
self.args = self.parse_args()
|
|
273
|
+
|
|
274
|
+
if self.args.debug:
|
|
275
|
+
print("Отладка включена")
|
|
276
|
+
|
|
277
|
+
# Запуск приложения
|
|
278
|
+
if __name__ == "__main__":
|
|
279
|
+
app = MyApp(sys.argv)
|
|
280
|
+
|
|
281
|
+
window = QMainWindow()
|
|
282
|
+
window.setCentralWidget(QLabel("Окно приложения"))
|
|
283
|
+
window.show()
|
|
284
|
+
|
|
285
|
+
sys.exit(app.exec())
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### Использование GUIHelpParser напрямую
|
|
289
|
+
Вы можете использовать графический парсер напрямую, например, для создания отдельного инструмента.
|
|
290
|
+
|
|
291
|
+
```python
|
|
292
|
+
import sys
|
|
293
|
+
from PySide6.QtWidgets import QApplication
|
|
294
|
+
from pyqtcli.argparser import GUIHelpParser
|
|
295
|
+
|
|
296
|
+
# Создаем парсер
|
|
297
|
+
app = QApplication(sys.argv)
|
|
298
|
+
parser = GUIHelpParser(prog="tool.py", description="Инструмент с GUI-справкой")
|
|
299
|
+
parser.add_argument("-o", "--output", help="Файл для вывода результата")
|
|
300
|
+
|
|
301
|
+
# При вызове parse_args() справка будет показана в окне,
|
|
302
|
+
# если переданы аргументы -h или --help.
|
|
303
|
+
# В противном случае парсинг пройдет как обычно.
|
|
304
|
+
args = parser.parse_args()
|
|
305
|
+
print(args)
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
## Структура пакета
|
|
309
|
+
- `__init__.py`: Основной модуль, экспортирующий классы `QCLIApplication`, `CLIMixin` и `GUIHelpParser`.
|
|
310
|
+
- `_widgets.py`: Внутренний модуль для автоматического выбора и импорта нужного Qt биндинга.
|
|
311
|
+
- `argparser.py`: Содержит классы `GUIHelpParser` (парсер с графической справкой) и `CLIMixin` (миксин для добавления парсера в любой класс).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
pyqtcli/__init__.py
|
|
5
|
+
pyqtcli/__init__.pyi
|
|
6
|
+
pyqtcli/_widgets.py
|
|
7
|
+
pyqtcli/argparser.py
|
|
8
|
+
pyqtcli/argparser.pyi
|
|
9
|
+
pyqtcli/py.typed
|
|
10
|
+
pyqtcli.egg-info/PKG-INFO
|
|
11
|
+
pyqtcli.egg-info/SOURCES.txt
|
|
12
|
+
pyqtcli.egg-info/dependency_links.txt
|
|
13
|
+
pyqtcli.egg-info/requires.txt
|
|
14
|
+
pyqtcli.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
argparse-typing>=0.2.0
|
|
2
|
+
|
|
3
|
+
[dev]
|
|
4
|
+
setuptools>=61.0.0
|
|
5
|
+
wheel>=0.46.3
|
|
6
|
+
twine>=6.2.0
|
|
7
|
+
build>=1.4.0
|
|
8
|
+
|
|
9
|
+
[pyqt]
|
|
10
|
+
PyQt5>=5.0.0
|
|
11
|
+
|
|
12
|
+
[pyqt5]
|
|
13
|
+
PyQt5>=5.0.0
|
|
14
|
+
|
|
15
|
+
[pyqt6]
|
|
16
|
+
PyQt6>=6.0.0
|
|
17
|
+
|
|
18
|
+
[pyside]
|
|
19
|
+
Pyside2>=5.12.0
|
|
20
|
+
|
|
21
|
+
[pyside2]
|
|
22
|
+
Pyside2>=5.12.0
|
|
23
|
+
|
|
24
|
+
[pyside6]
|
|
25
|
+
Pyside6>=6.0.0
|
pyqtcli-0.1.0/setup.cfg
ADDED