1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python交互式命令_在python中运行交互式命令

python交互式命令_在python中运行交互式命令

时间:2024-05-11 16:46:43

相关推荐

python交互式命令_在python中运行交互式命令

如果正在与子进程生成的程序通信,则应签出Non-blocking read on a subprocess.PIPE in python。我的应用程序也遇到了类似的问题,发现使用队列是与子流程进行持续通信的最佳方式。

至于从用户获取值,您始终可以使用raw_input()内置函数获取响应,对于密码,请尝试使用^{}模块从用户获取非回显密码。然后可以解析这些响应并将其写入子进程的stdin。

我最后做了如下的事情:import sys

import subprocess

from threading import Thread

try:

from Queue import Queue, Empty

except ImportError:

from queue import Queue, Empty # python 3.x

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 Empty:

return outStr

p = subprocess.Popen("cmd", stdin=subprocess.PIPE, stdout=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

outThread.start()

errThread.start()

try:

someInput = raw_input("Input: ")

except NameError:

someInput = input("Input: ")

p.stdin.write(someInput)

errors = getOutput(errQueue)

output = getOutput(outQueue)

一旦创建了队列并启动了线程,就可以循环从用户那里获取输入、从进程中获取错误和输出、处理并向用户显示它们。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。