Share your repls and programming experiences

← Back to all posts
Finally Releasing My Simple Command Module!
slickassassin03 (69)

Intro

This module is called PyCommands. It is made with the intent of streamlining command line applications made by you! Its memorable syntax and limitless possibilities make it a great choice for any Python program you want to make.

I do plan on making a different post on how to do more complex things, but this is what you get for now.


Setup

  • Create a file named pycommands.py
  • Paste the below code into said file
from shlex import split


class Command:
  def __init__(self, fn, name=None, aliases=None,):
    self.name = name or fn.__name__
    self.aliases = aliases or []
    self.fn = fn

  def __call__(self, *args, **kwargs,):
    return self.fn(*args, **kwargs,)

  @property
  def all_names(self,):
    return self.name, *self.aliases


class Commands(dict):
  def __init__(self, not_found: str='{} was not recognized.', argmismatch: str='{} takes {} arguments but {} were given.',):
    self.flag = [not_found, argmismatch,]
    super().__init__()

  def _add_command(self, command,):
    for cmd_name in command.all_names:
      if cmd_name in self:
        raise ValueError(f'Name or alias assigned to function {command.fn.__name__} is duplicate: {cmd_name}',)
      self[cmd_name] = command
    
  def add_command(self, name=None, aliases=None,):
    def inner_fn(fn,):
      self._add_command(Command(fn, name, aliases,),)
      return fn
    return inner_fn

  def execute(self, user_input,):
    self.command, *args = self.parse(user_input or 'no_input',)
    if self.command.lower() in self:
      try:
        self[self.command](*args,)
      except TypeError:
        return (False, self.flag[1].format(self.command, self[self.command].fn.__code__.co_argcount, len(args,),),)
      else:
        return (True, 'Command found!',)
    else:
      return (False, self.flag[0].format(self.command,),)
  
  @staticmethod
  def parse(string,):
    if (string=='no_input'):
      return ['']*2
    try:
      return split(string,)
    except ValueError:
      return ['']*2
  • Import pycommands
  • Done!

How to use it

  • Initialize the module:
import pycommands

commands = pycommands.Commands(
 '{} was not recognized as a command',
)
  • Add Commands
@commands.add_command(name='clear','aliases=['cls',],)
def clear():
    print('\033[H\033[2J',)

@commands.add_command(name='echo',)
def echo(*args,):
    print('\n'.join(args,),)
  • Create Input Loop
while True:
    cmd = commands.execute(input('>>> ',),)

    if not cmd[0]:  # Checks if command gave error
        print(cmd[1])  # Prints error message
    else:
        continue

And you are done!!! Here's what it would look like if you ran it:

>>> notacommand
notacommand was not recognized as a command
>>> echo quotes 'work in the' arguments
quotes
work in the
arguments
>>>

Wrapping Up

That's all you need to know to be able to use the module effectively, but there are many more possibilities. The more experienced of you will find them by reading the code, but for the people who need a tutorial, a post will come out soon. Please upvote this if you like it, and tell me in the comments what you plan to use it for! The program below is the program we wrote in this tutorial, I hope you enjoy, have a good time using PyCommands!

Commentshotnewtop
MarcusWeinberger (177)

But it doesn't seem to work for me :/

slickassassin03 (69)

@MarcusWeinberger Did you use the '@' symbol? These are decorators. You cannot simply call the function.

MarcusWeinberger (177)

@slickassassin03 This screenshot is from running the repl you shared

slickassassin03 (69)

@MarcusWeinberger

Well it seemed to be a pesky little comma, it has been fixed now. Sorry for that lol.