|
|
|
# Creating Your Own Console Line Interface Functionality
|
|
|
|
|
|
|
|
To add a new command to the NES CLI, follow these steps:
|
|
|
|
|
|
|
|
1. **Create the script with the desired functionality**
|
|
|
|
|
|
|
|
Create a new Python script in the `nes/entrypoints/` directory, for example, `my_function.py`.
|
|
|
|
This script should define the function that implements your command's logic.
|
|
|
|
|
|
|
|
```python
|
|
|
|
# nes/entrypoints/my_function.py
|
|
|
|
|
|
|
|
def my_function(args):
|
|
|
|
"""
|
|
|
|
Implement the functionality of your command here.
|
|
|
|
Args:
|
|
|
|
args: Parsed command-line arguments.
|
|
|
|
"""
|
|
|
|
print("Executing my_function with arguments:", args)
|
|
|
|
```
|
|
|
|
|
|
|
|
2. **Expose the function in `__init__.py`**
|
|
|
|
|
|
|
|
Import and expose your function in the `nes/entrypoints/__init__.py` file to make it available for CLI registration.
|
|
|
|
|
|
|
|
```python
|
|
|
|
# nes/entrypoints/__init__.py
|
|
|
|
|
|
|
|
from .my_function import my_function
|
|
|
|
|
|
|
|
__all__ = [..., 'my_function']
|
|
|
|
```
|
|
|
|
|
|
|
|
3. **Register the command in `cli.py`**
|
|
|
|
|
|
|
|
Add a helper function to register your command's subparser in `nes/entrypoints/cli.py`.
|
|
|
|
This function should add the subparser and specify the handler function.
|
|
|
|
|
|
|
|
```python
|
|
|
|
# nes/entrypoints/cli.py
|
|
|
|
|
|
|
|
from nes.entrypoints import my_function
|
|
|
|
|
|
|
|
def _add_my_function(subparsers):
|
|
|
|
parser = subparsers.add_parser('my_function', help='Description of my_function command')
|
|
|
|
# Add any command-line arguments here
|
|
|
|
parser.add_argument('--option', type=str, help='An example option')
|
|
|
|
parser.set_defaults(func=my_function)
|
|
|
|
```
|
|
|
|
|
|
|
|
4. **Call the subparser registration in `main()`**
|
|
|
|
|
|
|
|
Inside the `main()` function of `cli.py`, call `_add_my_function()` to register your command with the CLI.
|
|
|
|
|
|
|
|
```python
|
|
|
|
# nes/entrypoints/cli.py
|
|
|
|
|
|
|
|
def main():
|
|
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(description='NES CLI')
|
|
|
|
subparsers = parser.add_subparsers(title='commands', dest='command')
|
|
|
|
|
|
|
|
# Register your command here
|
|
|
|
_add_my_function(subparsers)
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
if hasattr(args, 'func'):
|
|
|
|
args.func(args)
|
|
|
|
else:
|
|
|
|
parser.print_help()
|
|
|
|
```
|
|
|
|
|
|
|
|
**Usage Example:**
|
|
|
|
|
|
|
|
After completing these steps, you can run your new command from the terminal:
|
|
|
|
|
|
|
|
```bash
|
|
|
|
python -m nes.entrypoints.cli my_function --option example_value
|
|
|
|
```
|
|
|
|
|
|
|
|
This will execute the `my_function` command with the provided option. |
|
|
|
\ No newline at end of file |