用Python包装交互式CLI [英] Wrapping an interactive CLI in python

查看:107
本文介绍了用Python包装交互式CLI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 gnugo 包装在python脚本中.

I am trying to wrap gnugo in a python script.

我已经解决了SO中有关包装CLI应用程序的其他问题此处,尽管它们有所帮助,我无法使我的脚本完全正常工作.似乎在stdin的第一次输入后,该进程已被终止.

I've gone over the other questions in SO about wrapping CLI applications here and here and though they've helped somewhat, I haven't been able to get my script to work completely. It appears the process is killed after the first input from stdin.

脚本如下:

import subprocess 

proc = subprocess.Popen(['gnugo', '--mode', 'gtp'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)

c = raw_input('first command: ')

while True:
    r = proc.communicate(c)
    print 'gnugo says: ' + str(r)
    c = raw_input('next command: ')

我得到的错误是:

$ python testgnu.py
first command: play b c4
gnugo says: ('= \n\n', None)
next command: genmove w
Traceback (most recent call last):
  File "testgnu.py", line 8, in <module>
    r = proc.communicate(c)
  File "/usr/local/Cellar/python/2.7.3/lib/python2.7/subprocess.py", line 754, in communicate
    return self._communicate(input)
  File "/usr/local/Cellar/python/2.7.3/lib/python2.7/subprocess.py", line 1307, in _communicate
    self.stdin.flush()
ValueError: I/O operation on closed file

我正在运行python 2.7.3(这可能没关系,但gnugo版本是3.8).

I am running python 2.7.3 (and it probably doesn't matter but the gnugo version is 3.8).

其他问题中的一些答案建议 pexpect ,但我想使用很少的外部库.

Some answers in the other questions suggested pexpect but I'd like to use as few external libraries as possible.

推荐答案

您的问题是 Popen.communicate 在执行读写操作后关闭文件.

Your issue is that Popen.communicate closes the file after performing its reads and writes.

您将必须手动调用proc.stdin.write(...)发送过程文本,并proc.stdout.read*()读取文本:

You will have to manually call proc.stdin.write(...) to send the process text and proc.stdout.read*() to read text:

while True:
    proc.stdin.write(c)
    r = proc.stdout.readline()

这篇关于用Python包装交互式CLI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆