Giter Club home page Giter Club logo

console-menu's Introduction

Build StatusDocumentation Status

console-menu

A simple Python menu-based UI system for terminal applications. Perfect for those times when you need a menu-driven program, but don’t want the overhead or learning curve of a full-fledged GUI framework.

Derived from the curses-menu project, but with curses dependency removed.

http://console-menu.readthedocs.org/en/latest/

image

image

image

image

Installation

Tested on Python 3.7 - 3.11, as well as pypy and pypy 3.

Installation can be performed by running pip

pip install console-menu

Usage

It's designed to be pretty simple to use. Here's an example

# Import the necessary packages
from consolemenu import *
from consolemenu.items import *

# Create the menu
menu = ConsoleMenu("Title", "Subtitle")

# Create some items

# MenuItem is the base class for all items, it doesn't do anything when selected
menu_item = MenuItem("Menu Item")

# A FunctionItem runs a Python function when selected
function_item = FunctionItem("Call a Python function", input, ["Enter an input"])

# A CommandItem runs a console command
command_item = CommandItem("Run a console command",  "touch hello.txt")

# A SelectionMenu constructs a menu from a list of strings
selection_menu = SelectionMenu(["item1", "item2", "item3"])

# A SubmenuItem lets you add a menu (the selection_menu above, for example)
# as a submenu of another menu
submenu_item = SubmenuItem("Submenu item", selection_menu, menu)

# Once we're done creating them, we just add the items to the menu
menu.append_item(menu_item)
menu.append_item(function_item)
menu.append_item(command_item)
menu.append_item(submenu_item)

# Finally, we call show to show the menu and allow the user to interact
menu.show()

Development

pip install -r requirements-docs.txt
pip install -v -e .
pytest

console-menu's People

Contributors

aegirhall avatar davidthomaswood avatar gimli76 avatar janhoy avatar jp-mca avatar mon avatar moralcode avatar omrisarig13 avatar rickbot-dot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

console-menu's Issues

Removal of enter key

Is it possible to make some menu items not wait for the enter key and just press 1 key? Checked out the documentation but doesn't seem to be an option.

Thanks

MultiSelectMenu return selections

I understand that if you want to use the selection menu but provide the option to selection multiple items, you should use the MultiSelectMenu.

However, from what I understand these are somewhat different use cases. Is there a simple/recommended way to have a selection menu that behaves like the SelectionMenu but returns multiple selections? I don't want to launch any functions for each item; I simply want to return a list of selected items.

I've looked through the code and all of the examples, and any attempt I've made at this seems far more complicated and convoluted than it should be. Wondering if I'm missing something here and there's a simple way to implement a multi selection menu with SelectionItems.

Unclear How to Retrieve Return Value from Selection SubMenu after calling Show() on Main Menu.

lightsheetScans = ["scan1", 'scan2', 'scan3']
currentScanSelectionIndex = None`

mainMenu = ConsoleMenu(mainMenuTitle, mainMenuSubTitle, prologue_text=mainMenuPrologue, epilogue_text=mainMenuEpilogue)
lightsheetMenu = ConsoleMenu(lightsheetMenuTitle, prologue_text=lightsheetPrologue, epilogue_text=lightsheetEpilogue)
lightsheetItem = SubmenuItem("Lightsheet Data", lightsheetMenu, mainMenu)

openScanMenu = SelectionMenu(lightsheetScans, "Select a Scan To Open", prologue_text="Opening a scan opens the metadata and a thumbnail of the stitched scan for the user to view.")
openScanMenuItem = SubmenuItem("Open Scan", openScanMenu, lightsheetMenu)

mainMenu.append_item(lightsheetItem)
lightsheetMenu.append_item(openScanMenuItem)
mainMenu.show()

The menu rendering and navigation all work correctly, however I'm not sure what the best way to retrieve the index returned by openScanMenu. Do I need to manage the start() and join() functions myself, or is there a way to retrieve it while only having to call show() once?

Edit: I'd like to make it clear that I need to get the return value of openScanMenu.get_selection() in the main thread where mainMenu.show() is called.

Update text in epilogue

I would like to have the Epilouge text to be updated reading values from a serial port. Is it possible to update the epilouge text on the menu from another thread? It would also be nice to have a way to display a status. Is this doable in some easy way?

by calling os.path.isdir() in a FunctionItem it jumps to the previous menu without finishing the function.

I have a FunctionItem like:
root_path = FunctionItem("Set a path for the root directory: ", set_root_path, [None, False], menu=new_profile_menu)
new_profile_menu.append_item(root_path)

the set_root_path function contain a line:

if not path.isdir(root) or force:
mkdir(root)
mkdir(root+'profile')

which makes the menu jump to the previous one without finishing the function call. if I remove the line it works.
even if I only have

print(path.isdir(root))

same happens.

How to use FunctionItem correctly?

I'm probably not doing it right but when I'm trying to call a function using FunctionItem It does not work like I want it to. Ive read the documentation but I just don't understand how to use it well. I just want to press the button and have it call the function but instead the function is called automatically every time I run the program.

from consolemenu import *
from consolemenu.items import *


def test_function():
	print("TestCall")


def welcome_screen():
	menu = ConsoleMenu("MenuTitle", "SubTitle")

	function_item = FunctionItem("Function item", test_function())

	menu.append_item(function_item)
	menu.show()


welcome_screen()

Output: https://gyazo.com/0c310cd95d587a66c5412f56d318aaa3

Question about using FunctionItem.get_return()

I'm having trouble figuring out where/how to call FunctionItem.get_return() so that I can display the return data while a ConsoleMenu is running. Here's an example script to help explain what I'm trying to do.

from consolemenu import *
from consolemenu.items import *

def command_1():
    print("Command 1 ran")
    return "Command 1 ran"

def command_2():
    print("Command 2 ran")
    return "Command 2 ran"

def main():
    menu = ConsoleMenu("Root Menu", "This is the Root Menu Subtitle")

    # Create a menu item that calls a function
    function_item_1 = FunctionItem("Command 1", command_1)
    function_item_2 = FunctionItem("Command 2", command_2)

    menu.append_item(function_item_1)
    menu.append_item(function_item_2)

    # Show the menu
    menu.show()

    print(function_item_1.get_return())
    print(function_item_2.get_return())

if __name__ == "__main__":
    main()

With this approach, the text printed to the screen in command_1() and command_2() gets overwritten immediately when the menu redraws. The get_return() prints after menu.show() don't appear until after exiting the menu, which makes sense since menu.show() is blocking. So I have two questions:

  1. Is there a way, using console-menu, to delay redrawing the menu after a FunctionItem's function is called (maybe until another keyboard/enter input) so that anything printed in the function doesn't get overwritten immediately?

  2. Is there a way to do the same as 1 but using function_item_*.get_return() outside of the functions themselves? I'm assuming I need to use another thread but I'm not sure.

Thanks!

"from consolemenu.items import *" fails on latest version of python 3.7 (tested on python 3.7.9)

The code snippet I put in the title fails on python version 3.7.9, but it works in slightly older releases of python (tested on python 3.7.4). For the sake of longevity, I was hoping that this issue could be address so that the package is compatible with the latest python release.

To recreate this issue:

  1. Create a python virtual environment and set the python version to 3.7.9
  2. Install the package following the documentation at this link: https://console-menu.readthedocs.io/en/latest/
  3. Following the same documentation, go through the commands in the "Usage" chapter and you should get a "ModuleNotFound" error when you get to the following line: "from consolemenu.items import FunctionItem, SubmenuItem, CommandItem"
  4. Create a new python virtual environment with python version 3.7.4
  5. Repeat steps 2 and 3 for this virtual environment, and you should be able to use the python package freely.

Any help on this issue would be appreciated! I have already ensured that the import path is current in later versions of python, and that the consolemenu package exists and the items directory exists within it.

Thank you in advance!

Custom Exit Text for Main Menu

Hi there,

Thanks for this menu, I enjoy the simplicity. The following is an enhancement request which I have already implemented on my instance of your code:

I'd like to allow custom exit text on the main menu screen. Currently, it is hard coded to show "Exit" as the option, even if we set the Console Menu parameter show_exit_option=False, and then add an ExitItem to the console menu with text="alternative exit text".

I think this would be useful for situations where the console menu does not start up directly upon running a script, so more accurate exit text might be "return to [...]". Also, this could just be useful for anyone who has a different idea of what the exit prompt should look like.

Here is how I would propose you can do this, within console_menu.py > class ExitItem:

def __init__(self, text="Exit", menu=None):
    super(ExitItem, self).__init__(text=text, menu=menu, should_exit=True)

def show(self, index):
    """
    This class overrides this method
    """
    if self.menu and self.menu.parent:
        self.text = "Return to %s" % self.menu.parent.title
        # Check if menu title ends with menu. (Some menus will include Menu in the name).
        if not self.text.strip().lower().endswith("menu"):
            self.text += " menu"
    else:
        if self.text=='': self.text = "Exit"
    return super(ExitItem, self).show(index)`

On the second to last line (which is line 435 in console_menu.py), add the if statement before deciding to use the default exit prompt text "Exit". This way if someone creates and enables an ExitItem with custom text, it will show that text.

Example does not work with Ubunut 20.04

Got an error message when running an example app in out of the box Ubuntu 20.04

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/root/.local/lib/python3.8/site-packages/consolemenu/console_menu.py", line 169, in _wrap_start
self._main_loop()
File "/root/.local/lib/python3.8/site-packages/consolemenu/console_menu.py", line 225, in _main_loop
self.draw()
File "/root/.local/lib/python3.8/site-packages/consolemenu/console_menu.py", line 232, in draw
self.screen.printf(self.formatter.format(title=self.title, subtitle=self.subtitle, items=self.items,
File "/root/.local/lib/python3.8/site-packages/consolemenu/screen.py", line 74, in printf
print(*args, end='')
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 3-77: ordinal not in range(256)

Although maybe it is related to python3.8 that is automatically comes with that distro

cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04 LTS"
VERSION_ID="20.04"

"clear" command in WSL

I am running Debian 10 thru WSL on a Windows 10 machine.

There seems to be a WSL bug that affects the "clear" shell command. Specifically, after executing the "clear" command the scroll buffer is erased (as expected) but the top left corner of the viewport is several lines below cursor (which is not in the viewpoint), proportional to the number of lines that were erased from scrollback. See this link --> WSL "clear" bug

So, after console menu "shows" a clears the screen, the menu is displayed outside of viewport -- you need to scroll up to see menu.

However, if you run the command "clear -x", the screen is scrolled up so that cursor is lined up with the top of the viewport; but the scroll buffer is not erased. While this is not ideal (as I would like scroll buffer erased), at least the cursor is in the viewport without scrolling up.

I can achieve this result with console menu if I edit the clear() method in screen.py so that the last line read as follows:

print(subprocess.check_output('clear -x', shell=True).decode())

However, I would like to achieve this result by sub-classing Screen. I have attempted the following:

@staticmethod def clear(): """ Clear the screen. """ if platform.system() == 'Windows': subprocess.check_call('cls', shell=True) else: print(subprocess.check_output('clear -x', shell=True).decode())

but I keep getting either (i) a command not found error (if I include "@staticmethod" in subclass as above); or (ii) an AttributeError : 0 parameters expected but 1 given (if I omit "@staticmethod" in the subclass).

How can I subclass Screen to change screen.clear() so that "clear -x" rather than "clear" isezexted by screen.clear?

Colored menu items

I'd like to create colored menu items. I tried using colorama (e.g. Fore.RED + "Menu Item" + Style.RESET_ALL, but this resulted in the menu border being messed up, probably because the color code characters are counted as normal characters but don't take up any screen space.

I saw some notes about color support in console_menu.py. Is someone working on this? Does anyone have some ideas about it? I'd be happy to implement this part, but it would be good to have some discussion about the API. How should a user define the color of a menu item? Obviously we could add a color argument to MenuItem, but how would we handle items in a SelectionMenu?

And then, colors are quite tricky, with all kinds of OS and stream dependent stuff. So I'd propose to use colorama for it. We could say that colored menu items are only supported if the colorama package is installed as well, without making it a hard requirement.

How to properly exit the menu

Hi, after running a FunctionItem I want to stop the entire program. However the current behavior goes back to the previous menu once FunctionItem has completed.

What's the proper way to exit the entire program once FunctionItem has completed?

I'm currently using os._exit() to exit the program, not sure this is the clean way to do it.

Thanks

Function containing plt.show() from matplotlib crashes on execution by Function Item

I have a function that renders a graph from matplotlib, and if I pass that function into a Function-Item it just crashes and throws an NSException.

Relevant code:

def plotData():
    df = pd.read_csv("data/MSFT.csv")
    print (df['Adj Close'])
    df[['High', 'Open', 'Adj Close']].plot()
    plt.show()

equityFunctions = SelectionMenu([])
SymbolLookup = FunctionItem(text="Symbol Lookup", function=plotData, menu=equityFunctions)

Error: libc++abi.dylib: terminating with uncaught exception of type NSException

The print statement shows briefly, but the graph just crashes the function. I'm guessing this is because Function-Item is trying to return me to the most relevant menu as soon as I select it, which seems to be a functionality limitation. It would be pretty useless if I could only use Function-Item to execute one-off functions where I don't need to see any output.

How to display returned values on the menu screen?

If I am presenting a console-menu that is listed with a FunctionItem, how do I return and display data from the function that executed, or is that not a built in feature?

Looking at the documentation, get_return on FunctionItems seems to be appropriate for what I'm looking for, but I'm not sure what I'm missing to get it to show at the menu screen.

Does anyone have any thoughts of where that could be added to the below example?

from consolemenu import *
from consolemenu.items import *

def helloWorld():
    value = "Hello World"
    return value

menu = ConsoleMenu("My Menu Name")
function_item1 = FunctionItem("Hello World", helloWorld)
menu.append_item(function_item1)
menu.show()

How to get a return value when not using SelectionMenu

When creating a menu as below, how does one get the index or value of the menu item that was chosen during the input? Is there a way to get the index or value from the SubmenuItem?

I've used SelectionMenu() successfully to do this, but can't see how to work with a mixture of items, functions and sub menus.

menu = ConsoleMenu('Select from the list')
menu_item_1 = MenuItem("Menu Item 1")
menu_item_2 = MenuItem("Menu Item 2")
menu_item_3 = MenuItem("Menu Item 3")
menu_item_4 = MenuItem("Menu Item 4")
submenu = SelectionMenu(["item1", "item2", "item3"], title="Selection Menu",
                            subtitle="These menu items return to the previous menu")

submenu_item = SubmenuItem("Submenu item", submenu=submenu)
submenu_item.set_menu(menu)

menu.append_item(menu_item_1)
menu.append_item(menu_item_2)
menu.append_item(menu_item_3)
menu.append_item(menu_item_4)
menu.append_item(submenu_item)
choice = menu.show()

menu.show() returns None

Remove readline import

At screen.py, the readline import causes a crash, at least on Windows. It seems that it is not used anywhere so simply removing it works.

Items longer than the default screen width don't wrap

If an item is of a length greater than the screen width (default of 80 characters it doesn't wrap it merely sticks out the side of the box

Steps to reproduce

Install v0.5.1 with pip install console-menu
Create code like

from consolemenu import SelectionMenu

a_list = [
    "This is an option that isn't just a string under 80 characters heck it's actually quite a bit longer",
    "blue", 
    "green"]

selection = SelectionMenu.get_selection(
    a_list)

Expected results

A menu like

  ┌─────────────────────────────────────────────────────────────────────────┐
  │                                                                         │
  │  Select an option                                                       │
  │                                                                         │
  │                                                                         │
  │    1 - This is an option that isn't just a string under 80 characters   │
           heck it's actually quite a bit longer                            │
  │    2 - blue                                                             │
  │    3 - green                                                            │
  │    4 - Exit                                                             │
  │                                                                         │
  │                                                                         │
  └─────────────────────────────────────────────────────────────────────────┘
  >> 

Actual results

  ┌─────────────────────────────────────────────────────────────────────────┐
  │                                                                         │
  │  Select an option                                                       │
  │                                                                         │
  │                                                                         │
  │    1 - This is an option that isn't just a string under 80 characters heck it's actually quite a bit longer  │
  │    2 - blue                                                             │
  │    3 - green                                                            │
  │    4 - Exit                                                             │
  │                                                                         │
  │                                                                         │
  └─────────────────────────────────────────────────────────────────────────┘
  >> 

Multiple thread exit

Hi, and Thanks for this wonderful module, it helps me big time. I'm seeing an issue where if I call menu.start() or menu.show() 3 times, this will create 3 threads/menus. How do I exit the first menu before entering the second? I've looked everywhere and I couldn't figure it out. Your help will be appreciated. Thanks

How to get the index from the selection menu/item?

Hi there! I like this console-menu project.

Can anyone give an example how I can get the index I selected from the submenu. It can be print out after it is back to the top menu.

Here is the code for the menu. Many thanks!

from consolemenu import *
from consolemenu.items import *

def action(name):
pass

def main():

# Create the root menu
menu = ConsoleMenu("Root Menu", "This is the Root Menu Subtitle")

submenu = SelectionMenu(["item1", "item2", "item3"], title="Selection Menu",
                        subtitle="These menu items return to the previous menu")  # Customize the exit text

submenu_item = SubmenuItem("Submenu item", submenu=submenu)

#selection_item = SelectionItem("Selection Item", submenu)

#submenu_item.set_menu(submenu)
# Add all the items to the root menu
menu.append_item(submenu_item)

# Show the menu
menu.start()
menu.join()

if name == "main":
main()

`should_exit=True` with SubmenuItem exiting main menu

If I want to exit out of both the main and sub menus from the sub menu I find this not possible. Take for instance the below code:

from consolemenu import *
from consolemenu.items import *

menu = ConsoleMenu("Title")
submenu1 = SelectionMenu(["a", "b", "c", "d"])
submenu2 = SelectionMenu(["a", "b", "c", "d"])
menu.append_item(SubmenuItem("1", submenu1, menu))
menu.append_item(SubmenuItem("2", submenu2, menu))
menu.show()

When I exit from the SelectionMenu after running a, b, c, or d, it brings me back to the main menu. If I use the "back to title" option it brings me back there as well. This is fine.

However, if I change

- menu.append_item(SubmenuItem("1", submenu1, menu))
- menu.append_item(SubmenuItem("2", submenu2, menu))
+ menu.append_item(SubmenuItem("1", submenu1, menu, should_exit=True))
+ menu.append_item(SubmenuItem("2", submenu2, menu, should_exit=True))

This makes selecting a submenu item exit the menu fully (which is wanted).

However, the "back to title" menu will ALSO exit the menu (which is unwanted).

Tcl_AsyncDelete Error - Multithreading and Matplotlib

Hello,

I am using the console menu package to create a menu of data analytics options, some of which call plotting functions (such as plotting histograms) with Matplotlib. I am able to call my functions and have the plots display correctly, but when I finally finish the entire program (after plotting, exiting the console menu, and exiting my program itself), I receive this error:

Exception ignored in: <function Image.del at 0x0000018B92C749D8>
Traceback (most recent call last):
File "C:\Users\JacobMann\AppData\Local\Programs\Python\Python37\lib\tkinter_init_.py", line 3507, in del
self.tk.call('image', 'delete', self.name)
RuntimeError: main thread is not in main loop
Tcl_AsyncDelete: async handler deleted by the wrong thread

Upon looking into this and finding various questions asked in the past about this problem (such as this one), it appears that TKinter is used for Matplotlib when graphing things, and it is intended to be run on a single thread. So whenever I call Matplotlib from one of the FunctionItems in the console menu, it ends up causing this error at the end of the program. I can confirm that this does not happen when I call the function outside of the console menu framework.

Previous solutions to this problem seem to be centered around importing Matplotlib and then doing matplotlib.use('Agg'), but this makes the back-end non-GUI based, so the solution does not work for people who wish to graph in Matplotlib.

Could this have to do with the "import threading" statement in the console menu code? Here are some posts I found on potentially getting rid of this problem:
Deleting the TCL interpreter
Running GUI on Main Thread

Dynamic, updateable menus

I use console-menu in a script to power a dynamic checklist. So as each menu option is chosen, the user is asked in a SelectionMenu whether the task is completed. If answering Yes, the state in the app is updated. But the update is not reflected when the menu refreshes.

Looks like the menu is initialized once and then has stale item objects with title. I need to update the title dynamically to add (Done) to those that are completed.

I think it could be possible by adding some refresh() method that will cause a re-read of the menu.

Or even better, allow users to pass method references as an alternative to strings, so you could do

def get_title():
    return my_title

def get_submenu():
    return ConsoleMenu(.....)

menu = ConsoleMenu(title="My menu")
menu.append_item(SubmenuItem(get_title, get_submenu()))
menu.show()

Whenever the variable my_title changes, the menu would render it on next refresh since it pulls the value from the method instead of from a copied string?

Menu border

By using the colored text, the menu border is corrupted... (see the attachment)

There is a possibility to "switch off" the menu border?

image

Option to not clear screen

I want the whole dialogue to be scrolling down the screen so you can see what you did above and be able to copy/paste the whole interaction afterwards.

Currently I am able to do this by subclassing Screen() and overriding clear() with do do nothing. But e.g. SelectionMenu does not take screen as argument. Would be nice with some global option instead.

Not an issue more of a usage question

  1. Is there a way to just have the menu scroll up instead of redisplay I am using it to list some info but the info gets blown away with the new display of the menu.

  2. When creating a submenu. Is it possible to then add FunctionItems to the submenu instead of a list of Selections. Or do you simpy add the items the same way as you do in the main menu.

Thank you

Textwrap3 import issue with pyinstaller

Hi,

I am getting the following import error while trying to create a standalone executable of my project using pyinstaller. I have already tried specifying the textwrap3 (dependency used by console menu) as a hidden import in a hook file for console menu, but it is not working.

Traceback (most recent call last): File "main.py", line 4, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "consolemenu\__init__.py", line 1, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "consolemenu\items\__init__.py", line 1, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "consolemenu\console_menu.py", line 9, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "consolemenu\menu_formatter.py", line 3, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "consolemenu\menu_component.py", line 1, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "ansiwrap\__init__.py", line 1, in <module> File "PyInstaller\loader\pyimod03_importers.py", line 495, in exec_module File "ansiwrap\core.py", line 11, in <module> File "imp.py", line 296, in find_module ImportError: No module named 'textwrap3' [34192] Failed to execute script 'main' due to unhandled exception!

Using this command to create a standalone exe,
pyinstaller -n TextFileConversionUtility main.py --onefile --additional-hooks-dir=./hooks

Exceptions and errors get masked by backend

I have just started using this console menu and have noticed some undesired behavior during exceptions. When using different menus, if there is an exception or error, the screen gets cleared before going back to the menu and I don't think this is right. If there is an exception raised, it is important to not catch this as it should cause the program to fail so the user can actually see where the issue is. Yes, in a situation where the backend software is finalized, this should be irrelevant. However, while testing my software in the menu, it is important to see these errors on the screen without them being cleared so I can trace the bugs.

Usage Example Request: getting returned values and user selections

I can see that this is based on the python-curses module. I think that console-menu launches something of a daemon thread that runs in the background continually grabbing user input.

I've never worked with something like this. Can you provide a simple example that shows how to interact with the running menu? How do I get the return values from executed functions or grab the most recent selection?

I cobbled together this example based on what I could piece together from the examples and docs, but I'm not sure where to go from here:

from consolemenu import *
from consolemenu.items import *

import logging
logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)

def add(number):
    return number+number

m = ConsoleMenu('Title')
item = MenuItem('Item one')
item_two = MenuItem('Item Two')
func = FunctionItem('add numbers', add, [5])

m.append_item(item)
m.append_item(item_two)
m.append_item(func)
logging.debug('starting up')
m.start()

while m.is_alive():
    # this is where the work gets done, but I'm not sure how to go about doing that.
    pass

m.join()

Is there a way to call functions in the submenus?

Hi there,
Is there a way to call functions in the submenus?
I want to go to a submenu, press a option and then that option prompts me the function that i build and then i get the result in the console - menu.
Cause when i want to see the ouput of a function i have to quit console - menu
i can show you my code ...

awesome menu, bottom spacing

hey this is an awesome project. i noticed that there are always 2 spaces below exit, is there a way to make it 1 instead? it just makes everything look fatter :D

automatic refresh of the menu item text

I have following problem:

  1. the text of menu item is calculated
  2. the function attached to this FunctionItem changes the values used in the calculation of item text

Why is the menu item text not automatically recalculated after return from the function?

There is some workaround for it?

Color Support?

Is there any possible way to color the menu + text natively or via use of a external library?

Variable Value Extracton

Is it possible I could get a variable from

function_item = FunctionItem("Call a Python function", input, ["Enter an input"])

so that I can use it as input in my functions?

UnicodeEncodeError in linux for printing menu box

I dont know if this is something worth fixing, but I just wanted it to be known.

I pasted the example4.py in my environment in linux (SLES11) and every time I run it, this UnicodeEncodeError comes up.

Just FYI I'm covering up the path with '*' below.

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/*/python/envs/3.6.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/*/python/envs/3.6.6/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "/*/consolemenu_test/vendor/lib/python3.6/site-packages/consolemenu/console_menu.py", line 169, in _wrap_start
    self._main_loop()
  File "/*/consolemenu_test/vendor/lib/python3.6/site-packages/consolemenu/console_menu.py", line 225, in _main_loop
    self.draw()
  File "/*/consolemenu_test/vendor/lib/python3.6/site-packages/consolemenu/console_menu.py", line 233, in draw
    prologue_text=self.prologue_text, epilogue_text=self.epilogue_text))
  File "/*/consolemenu_test/vendor/lib/python3.6/site-packages/consolemenu/screen.py", line 74, in printf
    print(*args, end='')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-77: ordinal not in range(128)

I found out that the sys.stdout for my linux python is ANSI_X3.4-1968 and windows is utf-8.
I tried many different ways, but after changing my encoding to utf-8 it at least works.

import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

External window opened by menu item hangs.

I created an function item, which calls some other python function, which in turn creates an mpv session to play an video. The video can properly play, but the player window won't close when I try to close the player. It just hangs until I quit the menu.

Any idea?

How to avoid reprinting last console output

When a function executed from a FunctionItem prints something in the console, the text is cut and mixed with the menu header. Can this be avoided?

An screenshot is attached.

Thank you in advance. Your work on this module is really useful.

untitled

Keeping called functions wrapped in menu format

Does anyone have an example of keeping called functions wrapped in the menu formatting? I've got some inputs that question and collect info from the user than process and generate output files or initiate actions on the back end with text updates to the user that I'd like to keep wrapped in the menu borders but not seeing how.

Function Usage Question

Maybe I am misunderstanding this package. It looks great, but for example I have setup a FunctionItem to call hello:

Side note: None of the examples call another function like this. Just input.

def hello():
    print('Hello World')

    # also tried Screen with same results
    Screen.println('hello')

I select the correct number, and enter. It just goes on a loop and shows the menu again. The message printed is shown for a split second. What is the correct way to print lines onto the console so the user can see them?

The example not works in python 2

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/local/lib/python2.7/dist-packages/consolemenu/console_menu.py", line 169, in _wrap_start
self._main_loop()
File "/usr/local/lib/python2.7/dist-packages/consolemenu/console_menu.py", line 225, in _main_loop
self.draw()
File "/usr/local/lib/python2.7/dist-packages/consolemenu/console_menu.py", line 233, in draw
prologue_text=self.prologue_text, epilogue_text=self.epilogue_text))
File "/usr/local/lib/python2.7/dist-packages/consolemenu/screen.py", line 75, in printf
print(*args, end='')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 3-77: ordinal not in range(128)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.