python交互式命令_从python内部运行交互式命令
從用戶那里獲取值,您可以始終使用原始_輸入()內(nèi)置以獲取響應(yīng),對(duì)于密碼,請(qǐng)使用getpass模塊從您的用戶獲得不回顯密碼。然后,您可以解析這些響應(yīng)并將它們寫入您的子流程的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)
一旦隊(duì)列建立并線程啟動(dòng),您就可以循環(huán)從用戶獲得輸入、從進(jìn)程中獲取錯(cuò)誤和輸出,并將它們處理并顯示給用戶。
總結(jié)
以上是生活随笔為你收集整理的python交互式命令_从python内部运行交互式命令的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FLEXAIR 界面展示。
- 下一篇: file_exists函数总是返回fal