:::: MENU ::::

Monthly Archives / January 2015

  • Jan 22 / 2015
  • 0
Linux

Add a function in shell on Linux (make dmesg timestamps human readable)

You want to add a specific function on your shell which is not available in standard functions and you would like to be able to call it anywhere you want without the need to specify the script location? That’s quite easy to do, with some simple tricks 😉 !

We will here work with a simple example of a useful function:

When you are calling the dmesg command, you got a timestamp which is not human readable and it can be hard to align these logs with the logs of another application running on the server for example. We will create a function called dmesghr (for dmesg human readable) that will allow us to call exactly the same than the dmesg command but with a timestamp human readable.

First of all, we will create our function under our profile at the end of file ~/.bashrc after all the already existing declarations:

[...]
# Function translating dmesg timestamp into a timestamp human readable
function dmesghr {
    # Define date format (similar to syslog)
    date_format="%b %d %T %Y"

    # Get the uptime in seconds from /proc/uptime
    uptime=$(cut -d " " -f 1 /proc/uptime)

    # Read dmesg and convert date with date_format defined above
    dmesg | sed "s/^\[[ ]*\?\([0-9.]*\)\] \(.*\)/\\1 \\2/" | while read timestamp message; do
        printf "[%s] %s\n" "$(date --date "now - $uptime seconds + $timestamp seconds" +"${date_format}")" "$message"
    done
}

Once this done, we will reload the profile file and export our new function so we can use it anywhere:

~$source ~/.bashrc
~$export -f dmesghr

Right now, we can call it directly from our shell and use it as a standard function:

~$dmesghr
[...]
[jan. 21 09:34:00 2015] Initializing cgroup subsys cpuset
[jan. 21 09:34:00 2015] Initializing cgroup subsys cpu
[jan. 21 09:34:00 2015] Initializing cgroup subsys cpuacct
[jan. 21 09:34:00 2015] Linux version 3.13.0-39-generic ([email protected]) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #66-Ubuntu SMP Tue Oct 28 13:30:27 UTC 2014 (Ubuntu 3.13.0-39.66-generic 3.13.11.8)
[jan. 21 09:34:00 2015] Command line: BOOT_IMAGE=/boot/vmlinuz-3.13.0-39-generic root=UUID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ro quiet splash vt.handoff=7
[jan. 21 09:34:00 2015] KERNEL supported cpus:
[jan. 21 09:34:00 2015] Intel GenuineIntel
[...]

  • Jan 12 / 2015
  • 0
Linux, Python

Create an interactive command-line menu using Python

It can be necessary to create a simple interactive menu on CLI (Command-Line Interface) using Python to allow users to make some choices while executing a script/program. As there is no standard library for this in Python, you will have to adapt it by yourself.

Here is a very simple example of how to do this. Feel free to modify, update and improve it as depending on your needs and your expectations 😉 !

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#title           :menu.py
#description     :This program displays an interactive menu on CLI
#author          :
#date            :
#version         :0.1
#usage           :python menu.py
#notes           :
#python_version  :2.7.6  
#=======================================================================

# Import the modules needed to run the script.
import sys, os

# Main definition - constants
menu_actions  = {}  

# =======================
#     MENUS FUNCTIONS
# =======================

# Main menu
def main_menu():
    os.system('clear')
    
    print "Welcome,\n"
    print "Please choose the menu you want to start:"
    print "1. Menu 1"
    print "2. Menu 2"
    print "\n0. Quit"
    choice = raw_input(" >>  ")
    exec_menu(choice)

    return

# Execute menu
def exec_menu(choice):
    os.system('clear')
    ch = choice.lower()
    if ch == '':
        menu_actions['main_menu']()
    else:
        try:
            menu_actions[ch]()
        except KeyError:
            print "Invalid selection, please try again.\n"
            menu_actions['main_menu']()
    return

# Menu 1
def menu1():
    print "Hello Menu 1 !\n"
    print "9. Back"
    print "0. Quit"
    choice = raw_input(" >>  ")
    exec_menu(choice)
    return


# Menu 2
def menu2():
    print "Hello Menu 2 !\n"
    print "9. Back"
    print "0. Quit" 
    choice = raw_input(" >>  ")
    exec_menu(choice)
    return

# Back to main menu
def back():
    menu_actions['main_menu']()

# Exit program
def exit():
    sys.exit()

# =======================
#    MENUS DEFINITIONS
# =======================

# Menu definition
menu_actions = {
    'main_menu': main_menu,
    '1': menu1,
    '2': menu2,
    '9': back,
    '0': exit,
}

# =======================
#      MAIN PROGRAM
# =======================

# Main Program
if __name__ == "__main__":
    # Launch main menu
    main_menu()

Question ? Contact