来自python的交互式命令的stdin

时间:2015-02-01 12:35:21

标签: python subprocess stdout stdin interactive

我尝试使用与此处描述的类似方法将交互式lua shell集成到我的python GUI中:Running an interactive command from within python目标平台现在是windows。我希望能够逐行提供lua解释器。

import subprocess
import os
from queue import Queue
from queue import Empty
from threading import Thread
import time


def enqueue_output(out, queue):
  for line in iter(out.readline, b''):
    queue.put(line)
  out.close()

lua = '''\
-- comment
print("A")
test = 0
test2 = 1
os.exit()'''

command = os.path.join('lua', 'bin', 'lua.exe')
process = (subprocess.Popen(command + ' -i', shell=True,
           stdin=subprocess.PIPE, stderr=subprocess.PIPE,
           stdout=subprocess.PIPE, cwd=os.getcwd(), bufsize=1,
           universal_newlines=True))

outQueue = Queue()
errQueue = Queue()

outThread = Thread(target=enqueue_output, args=(process.stdout, outQueue))
errThread = Thread(target=enqueue_output, args=(process.stderr, errQueue))

outThread.daemon = True
errThread.daemon = True

outThread.start()
errThread.start()

script = lua.split('\n')
time.sleep(.2)
for line in script:
  while True:
    try:
      rep = outQueue.get(timeout=.2)
    except Empty:
      break
    else:  # got line
      print(rep)
  process.stdin.write(line)

我收到的唯一输出是lua.exe shell的第一行。似乎对stdin的写作实际上并没有发生。我有什么想念吗?

使用-i开关运行外部lua文件实际上有效并产生预期的输出,这使我认为该问题已连接到stdin。

我在python交互模式中尝试了一下,使用python shell尝试类似于stdout的文件解决方案:Interactive input/output using python。但是,一旦我停止了python shell,这只会将输出写入文件,这看起来似乎stdin在某处停止并且只有在我退出shell时才实际传输。任何想法在这里出了什么问题?

0 个答案:

没有答案
相关问题