与Python cmd模块的交互

时间:2016-08-08 06:13:00

标签: python windows cmd stdout stdin

我有一个使用cmd模块的程序,如下所示:

import cmd


class Prog(cmd.Cmd):

    prompt = '>>'

    def do_reverse(self, line):
        print line[::-1]

    def do_exit(self, line):
        return True

if __name__ == '__main__':
    Prog().cmdloop()

我想写程序stdin并以编程方式从stdout读取。我试图实现如下目标:

from subprocess import Popen, PIPE


class ShellDriver(object):
    def __init__(self, process):
        self.process = process
        self.prompt = '>>'
        self.output = ''
        self.read()

    def read(self):
        while not self.output.endswith(self.prompt):
            chars = self.process.stdout.read(1)
            if chars == '':
                break
            self.output += chars

        result = self.output.replace('\n' + self.prompt, '')
        self.output = ''
        return result

    def execute(self, command):
        self.process.stdin.write(command + '\n')
        return self.read()

if __name__ == '__main__':
    p = Popen(['python', 'prog.py'], stdin=PIPE, stdout=PIPE)
    cmd = ShellDriver(p)
    print cmd.execute('reverse abc')
    cmd.execute('exit')

然而,当我从PyCharm运行此代码时,它工作正常,但是当我从命令行运行它时,它会挂起。据我所知,控制台(运行阅读器脚本的控制台和程序控制台)之间存在冲突,因为他们正在尝试使用相同的管道,而这个问题在PyCharm中并不存在,因为它将I \ O重定向到其自己的控制台。

有没有办法让它在系统控制台中运行?

我在Windows上(最好是跨平台解决方案)和Python 2.7

1 个答案:

答案 0 :(得分:0)

终于找到了答案。默认情况下,解释器以缓冲模式工作,以块的形式将数据发送到stdout,以避免它应该以{{1​​}}命令行参数在无缓冲模式下运行:

-u