Skip to content

Instantly share code, notes, and snippets.

@mlongval
Last active August 27, 2020 17:28
Show Gist options
  • Save mlongval/503e107d2ae0d15106c75489b8a4e5e9 to your computer and use it in GitHub Desktop.
Save mlongval/503e107d2ae0d15106c75489b8a4e5e9 to your computer and use it in GitHub Desktop.
Simple Menu system for CLI written in Python
#!/usr/bin/env python3
# vim: filetype=python
# Simple #!/usr/bin/env python3
# vim: filetype=python
# Michael Longval
# mlongval@gmail.com
# Simple menuing system to execute scripts in $HOME/bin/menu1_items
# code portions courtesy https://pypi.org/project/simple-term-menu/
# (actually I did not ask the guy, I just copied some portions of his code 🤪 )
# I suggest putting at least one script call z_Quit in
# $HOME/bin/menu1_items
# The z_Quit file should be executable (eg chmod +x)
# and should simply contain:
# #!/bin/sh
# echo "Exiting"
# Doing it this way is a simple exit and also avoids crashes if
# menu1 is called and menu1_items is an empty directory.
import os
import subprocess
from simple_term_menu import TerminalMenu
# This has been tested on Linux and MacOS but NOT on Windows
HOME_DIR = os.getenv('HOME')
# this is where scripts go, change it to suit your needs
ITEMS_DIR = HOME_DIR + '/bin/menu1_items/'
# Comment this out if you don't want the screen cleared every time
subprocess.call('clear')
menu_title = 'Please select action: \n'
# if you don't want previews remove 'preview_command' from invocation
# of TerminalMenu below
preview = "cat " + ITEMS_DIR + "{}"
def list_files(directory=ITEMS_DIR):
the_list = (list(file for file in os.listdir(directory)
if os.path.isfile(os.path.join(directory, file))))
the_list.sort()
return the_list
def main():
menu_items = list_files()
if len(menu_items) != 0:
terminal_menu = TerminalMenu(menu_items,
title=menu_title, preview_command=preview)
item = ITEMS_DIR + menu_items[terminal_menu.show()]
subprocess.call(item, shell=True)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment