在使用python的popen而不阻塞主工具时,将子进程输出写入文件

时间:2018-01-09 14:10:08

标签: python subprocess pyside

如何使用户可以启动子流程工具,同时仍然能够将错误日志写入文件?

当子进程启动另一个出错的python工具时,此工具会将错误输出写入日志文件。但问题是,当用户启动子进程时,它会阻塞主窗口并将其冻结,直到子进程关闭。

简单地在同一文件夹中创建这三个python文件并运行mainwindow.py工具并单击运行按钮。在同一文件夹中创建错误日志。

tool_01.py会创建错误输出

import sys
import os
import fake #CAUSE ERROR LOG WRITE
from PySide import QtGui, QtCore

class ToolWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ToolWindow, self).__init__(parent)
        self.resize(250, 100)
        self.ui_Run = QtGui.QLabel("Second Tool")
        self.setCentralWidget(self.ui_Run)

def main():
    app = QtGui.QApplication(sys.argv)
    ex = ToolWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

tool_02.py运行正确

import sys
import os
from PySide import QtGui, QtCore

class ToolWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(ToolWindow, self).__init__(parent)
        self.resize(250, 100)
        self.ui_Run = QtGui.QLabel("Working Tool")
        self.setCentralWidget(self.ui_Run)

def main():
    app = QtGui.QApplication(sys.argv)
    ex = ToolWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

MainWindow.py

import sys
import os
import subprocess
from PySide import QtGui, QtCore

################################################################################
# Main
################################################################################
class MainWindow(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(300, 200)

        self.ui_Run01 = QtGui.QPushButton("Run Tool 01 (CREATES ERROR)")
        self.ui_Run01.clicked.connect(self.run_tool_01)

        self.ui_Run02 = QtGui.QPushButton("Run Tool 02 (WORKING)")
        self.ui_Run02.clicked.connect(self.run_tool_02)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.ui_Run01)
        layout.addWidget(self.ui_Run02)
        self.setLayout(layout)

    def execute_tool(self, filepath):
        exe = sys.executable
        process = subprocess.Popen([exe, filepath], shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, cwd=os.path.dirname(filepath))
        output = process.communicate()[0]
        exitCode = process.returncode
        print 'output:', output
        print 'exit:', exitCode

        if exitCode != 0:
            self.logfile = os.path.abspath('log.txt')
            directory = os.path.dirname(self.logfile)

            if not os.path.exists(directory):
                os.makedirs(directory)

            with open(self.logfile, 'w') as f:
                f.write(output)

            print 'Log:', self.logfile
            return False

        return True

    def run_tool_01(self):
        self.execute_tool(os.path.abspath('tool_01.py'))

    def run_tool_02(self):
        self.execute_tool(os.path.abspath('tool_02.py'))


def main():
    app = QtGui.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

0 个答案:

没有答案