linux下用python实现文本menu

作者: 2hei 发表于2009年11月17日 18:13
版权声明: 可以转载, 转载时务必以超链形式标明文章原始出处和作者信息及版权声明
http://www.2hei.net/mt/2009/11/linux-python-txt-menu.html
linux用shell实现menu比较简单,今天用python实现了一个,因为python没有switch语法,所以使用了dict来替代,另外调用了linux的clear来清屏,本例只是说明一下简单的实现方法,菜单的命令或者语句可以自由发挥 呵呵。

截个图先:
2009-11-17-linux-python-menu.png

















具体代码如下:
#!/usr/bin/evn python
# -*- coding: utf-8 -*-
#Author: 2hei#2hei.net
#Date: 2009-11-17 18:24

import os,sys

running = True
menu = """
             menu
------------------------------
    1:   Disk info
    2:   Mem info
    3:   Network info
    4:   Sys load info
    5:   Process info
    h:   Help
    q:   Quit
------------------------------
"""

menu_dict={
      "h": "echo help ^_^",
      "1": "df -h",
      "2": "free -m",
      "3": "netstat -lnt",
      "4": "uptime",
      "5": "ps x"
      }

def commands(args):
    cmd = menu_dict.get(args)
    return cmd

if __name__ == "__main__":
    os.system('clear')
    print menu   
    while running:
        cmd = raw_input("Input your commond :\n")
        if cmd != 'q':
            os.system('clear')
            try:
                print menu
                if commands(cmd) != None:
                    fo = os.popen(commands(cmd))
                    print fo.read()
                else:
                    print "Input is Wrong!\n"
            except Exception,e:
                print menu
                print e            
        else:
            print 'we will exit the menu\n'
            sys.exit()


| | Comments (0) | TrackBacks (0)

发表一个评论

关于这篇文章

这篇文章由2hei2009年11月17日 18:13发布.

上一篇:python 访问带有web认证的页面

下一篇:mptscsih: ioc0: attempting task abort

回到首页 或者查看归档文章