1

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()
4

1 回答 1

1

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

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

于 2014-07-17T03:34:01.787 回答