1

Python は初めてで、定義済みの関数と引数を取り、if/then 形式で値を返す cmd を使用してインタラクティブ シェルに取り組んでいます。以下の例。しかし、私の問題は、ユーザーが関数を入力してユーザーに何かを返すたびに、Enter キーを押すと、最後に提供された出力を受け取ることです。

以下のコード例...しかし、基本的に、ユーザーがその問題について引数または関数を入力しない場合、私は何も表示したくないだけです "" または空のスペース。私は、else pass 引数でそれができると思っていましたが、明らかにそうではありませんでした。if と elif を試してみましたが、同じ結果でした。

「test arp」を使用した出力例。Enter キーを押すだけで、押された前の引数が返されます。

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 に答える