我正在使用子进程模块启动子进程并连接到它的输出流(stdout).我希望能够在其标准输出上执行非阻塞读取.有没有办法让.readline非阻塞或在我调用之前检查流上是否有数据.readline?我希望这是可移植的,或至少在Windows和Linux下工作.
这是我现在如何做到的(.readline如果没有数据可用,则阻止它):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
Run Code Online (Sandbox Code Playgroud) 我有一个与用户交互的程序(就像一个shell),我想以交互方式使用python子进程模块运行它.这意味着,我希望有可能写入stdin并立即从stdout获取输出.我在这里尝试了许多解决方案,但它们似乎都不能满足我的需求.
我编写的代码基于在python中运行交互式命令
import Queue
import threading
import subprocess
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
def getOutput(outQueue):
outStr = ''
try:
while True: #Adds output from the Queue until it is empty
outStr+=outQueue.get_nowait()
except Queue.Empty:
return outStr
p = subprocess.Popen("./a.out", stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize = 1)
#p = subprocess.Popen("./a.out", stdin=subprocess.PIPE, stout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, universal_newlines=True)
outQueue = Queue()
errQueue = Queue()
outThread = Thread(target=enqueue_output, args=(p.stdout, outQueue))
errThread = Thread(target=enqueue_output, args=(p.stderr, errQueue))
outThread.daemon = True
errThread.daemon = True …Run Code Online (Sandbox Code Playgroud) 我对从python调用控制交互式CLI应用程序感兴趣.
我想在最基本的层面上我需要一个python脚本来启动主机操作系统上的CLI应用程序.管道从stdin到cli应用程序的任何内容,然后将cli应用程序的任何输出传递给stdout.
从这个基础对输入和输出进行一些处理应该非常简单
说实话,我可能只需要一个关于tecnique被调用的指针.我不知道我需要搜索什么.
我想实现与此非常相似的目标。
\n\n我的实际目标是从 python 中运行 Rasa。\n取自 Rasa\ 的站点:
\n\n\n\n\nRasa 是一个用于构建会话软件的框架:Messenger/Slack 机器人、Alexa 技能等。我们\xe2\x80\x99ll 在本文档中将其缩写为机器人。
\n
它基本上是一个在命令提示符下运行的聊天机器人。这就是它在 cmd 上的工作方式:\n
现在我想从 python 运行 Rasa,以便可以将其与基于 Django 的网站集成。即我想继续从用户那里获取输入,将其传递给rasa,rasa处理文本并给我一个输出,然后将其显示给用户。
\n\n我已经尝试过这个(到目前为止从cmd运行它)
\n\nimport sys\nimport subprocess\nfrom threading import Thread\nfrom queue import Queue, Empty # python 3.x\n\n\ndef enqueue_output(out, queue):\n for line in iter(out.readline, b\'\'):\n queue.put(line)\n out.close()\n\n\ndef getOutput(outQueue):\n outStr = \'\'\n try:\n while True: #Adds output from the Queue until it is empty\n outStr+=outQueue.get_nowait()\n except Empty:\n return outStr\n\np = subprocess.Popen(\'command_to_run_rasa\', \n stdin=subprocess.PIPE, \n …Run Code Online (Sandbox Code Playgroud) 考虑一个类似的命令
yum install boto
Run Code Online (Sandbox Code Playgroud)
当我在终端中执行时,继续进行是要我是/否
我可以在python中回应吗
os.system("yum install boto")
Run Code Online (Sandbox Code Playgroud)
接下来"Yes" 将通过相同的python代码传递到终端,以便安装。好吧,我认为这行不通。如果是在上述声明之后写成的
os.system("yes")
Run Code Online (Sandbox Code Playgroud)
请告诉我是否可行?
python ×5
subprocess ×3
command-line ×1
interactive ×1
io ×1
linux ×1
nonblocking ×1
os.system ×1
python-2.7 ×1
rasa-nlu ×1
stdin ×1
stdout ×1