python中的脚本和交互式终端客户端

时间:2012-05-03 10:46:08

标签: python

我需要使用python脚本/自动化交互式终端客户端。客户端接受三个参数并运行如下:

>./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中自动执行此操作,并将控制台输出保存在文件中。

对此有任何帮助,我们非常感谢......

2 个答案:

答案 0 :(得分:6)

您可以查看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读取的命令不会出现在此输出中,但我相信这很容易解决。

答案 1 :(得分:6)

你可能想要使用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能够提供更多功能,但请阅读文档以获取更多高级用例。