您的位置:首页 > 其它

cmd和图形界面同时存在,且cmd命令一直不退出,如何和cmd命令交互的问题

2018-01-28 21:08 651 查看
# -*- coding: utf-8 -*-

"""
Module implementing Dialogimage.
"""

from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal
from PyQt5.QtWidgets import QDialog, QApplication

from  subprocess import Popen, PIPE, call, run
import subprocess
import threading

from Ui_image import Ui_Dialog
fp = open("ping.txt", 'w')
outfileno=fp.fileno()

fpin = open("input.txt", 'r')
infileno=fpin.fileno()

def cmdTread():
#cmd = "ping  -t www.baidu.com"

cmd=['ping','-t','www.baidu.com']
proc=Popen(cmd, stdout=outfileno, shell=True,  universal_newlines=True)
# 此处的stdout=outfileno为最关键的部分,将输出到文件中。由于ping一直运行,此时communicate并不能返回获取到输出信息,因而输出到文件中。 同时对于输入的交互,用什么命令测试下呢?
 try:
out, err=proc.communicate(input=infileno, timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
out, err=proc.communicate()
print("timeout")
print(out)
print(err)
print(cmd)
#os.system(cmd)
class Speech_Recognition_Thread(QThread):
finished_signal = pyqtSignal(str)

def __init__(self, parent = None):
super().__init__(parent)

def run(self):

cmdTread()
self.finished_signal.emit('over')

class Dialogimage(QDialog, Ui_Dialog):
"""
Class documentation goes here.
"""
def __init__(self, parent=None):
"""
Constructor

@param parent reference to the parent widget
@type QWidget
"""
super(Dialogimage, self).__init__(parent)
self.setupUi(self)

def _show_message(self, message):
print('message:', message)

@pyqtSlot()
def on_pushButton_clicked(self):
"""
Slot documentation goes here.
"""
# TODO: not implemented yet
# raise NotImplementedError
# cmdTread()
self.speech = Speech_Recognition_Thread()
self.speech.finished_signal.connect(self._show_message)
self.speech.start()

@pyqtSlot(bool)
def on_g3_toggled(self, checked):
"""
Slot documentation goes here.

@param checked DESCRIPTION
@type bool
"""
# TODO: not implemented yet
raise NotImplementedError

if __name__ == "__main__":
import sys
app = QApplication(sys.argv)

ui = Dialogimage()

ui.show()
sys.exit(app.exec_())

   

proc=Popen(cmd,stdin=PIPE, stdout=outfileno,  universal_newlines=True)

proc.stdin.flush()

 proc.stdin.write('3\n')

    proc.stdin.write('5\n')

缺少回车\n是不行的。universal_newlines为true,如果此值为false,则需要 proc.stdin.write(b'3\n')

主要需求:

     1) windows下 运行某个不会立即返回的命令,例如ping -t xxx,如何在python代码中和此命令交互:获取命令输出,并给命令新的输入值。

   百度到点资料,后续看看。

   https://stackoverflow.com/questions/16091112/python-pipe-to-popen-stdin
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐