python中交互式命令的stdin

python中交互式命令的stdin,python,subprocess,stdout,stdin,interactive,Python,Subprocess,Stdout,Stdin,Interactive,我正试图用这里描述的类似方法将交互式LuaShell集成到python GUI中:目前的目标平台是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(o

我正试图用这里描述的类似方法将交互式LuaShell集成到python GUI中:目前的目标平台是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 shell在python交互模式下进行了一些尝试,尝试了一些类似于为stdout提供一个文件的解决方案:。然而,这只是在我停止pythonshell之后才将输出写入文件,这也似乎是stdin在某个地方被暂停了,并且只有在我退出shell之后才真正被传输。知道这里出了什么问题吗?

双向popen通常是有问题的,请仔细阅读可能发生的死锁。我建议您使用Lua作为库,而不是调用可执行文件。如果您一次将所有文件都传递出去,err=process.communicatelua,它会工作吗?无关:可以对多行字符串使用三重引号,也可以依赖隐式连接:“a”“b”-是单个字符串“ab”,即不使用反斜杠here@JohnZwinck我将相同的可执行文件用于不同的目的,这就是为什么我希望使用一个可执行文件。但是谢谢你的邀请suggestion@J.F.Sebastian是的,一次通过就行了。不幸的是,这不是一个选项,因为我想支持断点。这应该是一个开发和测试脚本的环境。感谢您提供有关字符串的提示,请将其更改。如果它同时工作,则可能是缓冲问题:add process.stdin.flush,在每行末尾添加\n。您也应该使用errQueue或使用单个队列。