2

Python を使用してインタラクティブ ターミナル クライアントをスクリプト作成/自動化する必要があります。クライアントは 3 つの引数を受け取り、次のように実行されます。

>./myclient <arg1> <arg2> <arg3>
Welcome...
blah...
blah..
[user input]
some more blah... blah... for the input entered
blah.. 
blah..
[basically it accepts input and puts the output in the console until the user types 'quit']

これを Python で自動化し、コンソール出力をファイルに保存する必要があります。

4

2 に答える 2

7

おそらくpexpectを使用したいと思うでしょう(これは由緒ある期待の純粋な Python バージョンです)。

import pexpect
proc = pexpect.spawn('./myclient <arg1> <arg2> <arg3>')
proc.logfile = the_logfile_you_want_to_use
proc.expect(['the string that tells you that myclient is waiting for input'])
proc.sendline('line you want to send to myclient')
proc.expect(['another line you want to wait for'])
proc.sendline('quit') # for myclient to quit
proc.expect([pexpect.EOF])

あなたのケースを解決するには、このようなもので十分なはずです。ただし、pexpect にはさらに多くの機能があるため、より高度なユースケースについてはドキュメントを参照してください。

于 2012-05-03T15:28:30.387 に答える
7

http://docs.python.org/library/cmd.htmlをご覧ください。

コード例:

import cmd
import sys

class Prompt(cmd.Cmd):
    def __init__(self, stufflist=[]):
        cmd.Cmd.__init__(self)
        self.prompt = '>>> '
        self.stufflist = stufflist
        print "Hello, I am your new commandline prompt! 'help' yourself!"

    def do_quit(self, arg):
        sys.exit(0)

    def do_print_stuff(self, arg):
        for s in self.stufflist:
            print s

p = Prompt(sys.argv[1:])
p.cmdloop()

テスト例:

$ python cmdtest.py foo bar
Hello, I am your new commandline prompt! 'help' yourself!
>>> help

Undocumented commands:
======================
help  print_stuff  quit

>>> print_stuff
foo
bar
>>> quit

出力をファイルに保存するために、たとえば次のクラスを使用して、通常 stdout に出力されるものもファイルに書き込むことができます。

class Tee(object):
    def __init__(self, out1, out2):
        self.out1 = out1
        self.out2 = out2

    def write(self, s):
        self.out1.write(s)
        self.out2.write(s)

    def flush(self):
        self.out1.flush()
        self.out2.flush()

次のように使用できます。

with open('cmdtest.out', 'w') as f:
    # write stdout to file and stdout
    t = Tee(f, sys.stdout)
    sys.stdout = t

stdin 経由で読み込まれたコマンドがこの出力に表示されないことが問題ですが、これは簡単に解決できると思います。

于 2012-05-03T14:32:38.413 に答える