Skip to content

Instantly share code, notes, and snippets.

@kinow
Created July 3, 2016 02:22
Show Gist options
  • Save kinow/81e4ff7e399349a6f056ee2dd15c88e2 to your computer and use it in GitHub Desktop.
Save kinow/81e4ff7e399349a6f056ee2dd15c88e2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# @see http://www.andrewnoske.com/wiki/Unix_-_ncurses_ui
# my_first_ncurses_menu_ui.py - simple interactive command line
# program generated using 'ncurses ui'.
# This example has four options:
# > option 1: prompts for more input
# > option 2&3: execute basic bash commands.
# > option 4: exits back to bash prompt.
# This can be a good base to build a more sophisticated interative program.
import os
import curses
def get_param(prompt_string):
"""Brings up new screen asking user to enter a single parameter.
Args:
prompt_string: Prompt which asks/tells user what to enter (string).
"""
screen.clear()
screen.border(0)
screen.addstr(2, 2, prompt_string)
screen.refresh()
input = screen.getstr(10, 10, 60)
return input
def execute_cmd(cmd_string):
"""Clears the screen, executes the given system command and shows the result.
Args:
cmd_string: Unix/system command to execute.
"""
os.system('clear')
a = os.system(cmd_string)
print ''
if a == 0:
print 'Command executed correctly: ' + cmd_string
else:
print 'Command terminated with error'
raw_input('Press enter')
print ''
# Init screen with global var:
screen = curses.initscr()
def main():
opt = 0
while opt != ord('4'):
screen.clear()
screen.border(0)
screen.addstr(2, 2, 'Please enter a number...')
screen.addstr(4, 4, '1 - Print happy birthday (custom input)')
screen.addstr(5, 4, '2 - Output date (date)')
screen.addstr(6, 4, '3 - Show disk space (df -h)')
screen.addstr(7, 4, '4 - Exit')
screen.refresh()
opt = screen.getch() # Wait for user to enter a character.
if opt == ord('1'):
names = get_param('Enter your name, or comma-seperated names')
age = get_param('Enter your age')
curses.endwin()
print '\n\nHappy birthday ' + names + '. You are ' + age + '!\n\n'
raw_input('Press enter (to return to main)')
if opt == ord('2'):
curses.endwin()
execute_cmd('date')
if opt == ord('3'):
curses.endwin()
execute_cmd('df -h')
curses.endwin()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment