Search code examples
pythonuser-interfacencursescurses

Python: ncurses not printing a value passed to function


I'm writing a ncurses GUI for an app. I have following code in a file admin.py:

#-*- coding: utf-8 -*-

import curses.textpad

from gui_helpers import *
import global_vars as g

def parse_command(win, command):
    # print_str(win, 0, 0, command)
    if command == "help":
        print_str(win, 1, 1, "Available commands: add - adds a board, list - lists boards, mkdir - makes board directory")

def display_admin_screen(win, keypress):
    rows = win.getmaxyx()[0]
    cols = win.getmaxyx()[1]

    print_str_center(win, 0, 1, "Admin interface", g.RED|g.BOLD)
    print_str(win, 1, 0, "Command line")

    textpad_win = win.subwin(1, cols - 1, 3, 1)
    output_win = win.subwin(5, cols - 1, 5, 1)

    output_win.refresh()
    textpad_win.refresh()
    win.refresh()

    curses.curs_set(1)
    textpad = curses.textpad.Textbox(textpad_win)
    textpad.stripspaces = 0
    textpad_win.move(0,0)
    textpad.edit()

    command = textpad.gather()
    parse_command(output_win, command)
    # print_str(output_win, 0, 0, command)
    textpad_win.clear()
    curses.curs_set(0)

The code itself (the function display_admin_screen()) runs in a loop in file gui.py which has all the necessary library imports:

while True:    
        keypress = stdscr.getch()
        display_title_bar(stdscr)

        if g.STATE == 'motd':
            display_motd(working_win, keypress)
        elif g.STATE == 'boards':
            boards_view.display_threads(working_win, g.SELECTED_BOARD, keypress)
        elif g.STATE == 'admin':
            admin.display_admin_screen(working_win, keypress)

        working_win.refresh()
        stdscr.refresh()

The problem I'm having is that when I type 'help' in the textbox in admin.py, nothing happens. It should display help text in output_win. I've checked that the value gets passed to function parse_command() properly, and that it is a proper value. I thought it may be the problem with creating subwindows inside a loop, so I tried creating them in gui.py outside of the loop and passing them to the function, but to no avail. If I just tell the parse_command() function to write something to the output window it does that no problem. For some reason the if block seems to be a problem.


Solution

  • I finally found out what was wrong. After pressing Enter, there was a bunch of whitespace (not newline \n) appended to the command. All I had to do was change:

    command = textpad.gather()
    

    to

    command = textpad.gather().strip()
    

    And it works now.