【问题标题】:python interactive shell using cmd repeating statements with no arguments typedpython交互式shell使用没有输入参数的cmd重复语句
【发布时间】:2014-07-15 01:01:06
【问题描述】:

python 新手,我正在使用 cmd 开发一个交互式 shell,它接受定义的函数和参数,并以 if/then 格式返回值。下面的例子。但我的问题是,每次用户键入一个函数并且我向用户返回一些内容时,如果他们只是按 Enter 键,那么他们会收到最后提供的输出。

例如下面的代码......但基本上,如果用户没有为此输入参数或函数,我只想不显示任何内容,只显示“”或空格。我认为 else pass 参数会为我做到这一点,但显然不是。我试过if和elif,结果一样。

带有“test arp”的示例输出,只需按回车键即可返回上一个按下的参数:

user@hostname>test arp
? (192.168.50.1) at 0:26:88:38:c6:48 on en0 ifscope [ethernet]
? (192.168.50.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]
> **<enter key>**
? (192.168.50.1) at 0:26:88:38:c6:48 on en0 ifscope [ethernet]
? (192.168.50.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]
> **<enter key>**

示例代码: #!/usr/bin/env python

from cmd import Cmd
from time import ctime
import csv, os, subprocess, getpass, socket, pwd, re, select, shutil, subprocess, sys

syntaxError = "Sorry that syntax isn't quite right..."

class cliPrompt(Cmd):

    def do_test(self, args):
        if len(args) == 0:
            print syntaxError  
        if args == '?':
            print 'want to read the help?'
        if args == 'arp':
            subprocess.call('arp -an', shell=True)
        if args == 'cpu':
            subprocess.call('grep "model name" /proc/cpuinfo', shell=True)
        if args == 'firewall':
            subprocess.call('iptables -L -v -n --line-numbers', shell=True)
        if args == 'interfaces':
            subprocess.call('ifconfig', shell=True)
        else: 
            pass                                            

if __name__ == '__main__':
    prompt = cliPrompt()
    prompt.prompt = '>'
    prompt.cmdloop()

【问题讨论】:

  • Geez 通常有助于阅读 cmd 模块文档。为了胜利! def emptyline(self): 通过

标签: shell python-2.7 python-cmd


【解决方案1】:

在 cmd 文档的首页右侧讨论了禁用返回上一个命令选项。

https://wiki.python.org/moin/CmdModule

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-11
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2011-11-01
    • 2018-03-17
    相关资源
    最近更新 更多