-
Notifications
You must be signed in to change notification settings - Fork 1
Using PyCSH to create an APM extension for CSH
kivkiv12345 edited this page May 12, 2024
·
3 revisions
""" Python APM test """
from __future__ import annotations
# Import pycsh, which will be linked to CSH when imported as an APM
import pycsh
def inform(name: str) -> None:
""" This is the function that our slash command will execute,
notice that it accepts the argument <name> """
print(f"Hej {name}, nu kan du lave APMer i Python :)")
# Calls to pycsh.PythonSlashCommand() create new slash commands.
# Here we create a command called "inform" that runs the function inform().
# Optionally an 'argument' string may be specified, which is what "help" in CSH will show.
# When commands are instantiated on global scope,
# they will not be recreated if their module is imported/executed multiple times.
_inform = pycsh.PythonSlashCommand("inform", inform, "<name>")
def main() -> None:
""" The "py run" command in CSH will currently execute main() by default,
this may be changed by the "-f" argument """
# Our slash command may also be invoked here through Python
_inform("mig selv")
_original_command = pycsh.SlashCommand(<COMMAND NAME>)
def command(*args: tuple[str]) -> None:
""" This is Python command that extends an existing command """
# ... Extend original command here ...
# Extending command may of course opt out of calling the original.
if <GUARD CLAUSE>:
return
# Call the original slash command, with whatever argument we received.
_original_reboot(*args)
# ... Perhaps do something after the original command has executed ...
_command = pycsh.PythonSlashCommand(<COMMAND NAME>, command, _original_command.args)
Here is a concrete example
_original_reboot = pycsh.SlashCommand("reboot")
def reboot(*args: tuple[str]) -> None:
reboot_self = False
if '-n' in args and args[args.index('-n' + 1)] == '0':
reboot_self = True
elif args[0] == '0':
reboot_self = True
if reboot_self:
# Refuse to reboot node 0
print("Refusing to reboot self")
else:
# Execute original (overridden) command, with whatever arguments we were given
_original_reboot(*args)
_reboot = pycsh.PythonSlashCommand("reboot", reboot, _original_reboot.args)