首页 > 解决方案 > QProcess CLI 命令 - 指定输出保存位置时出现“错误参数”

问题描述

我正在使用 QProcess 运行典型的 cli 命令,例如“ping”或“netstat”。我希望它连续运行,直到我告诉它停止。我在下面提供了使用“ping”命令的代码的精简版本。如果我从 cmd 提示符运行命令“ping -t 192.168.0.1 > test.txt”,它工作正常,但是当我尝试在下面的程序中运行它时,它会产生错误“参数错误 > test.txt”。

看来,保存 cli 命令的输出并不能算作 QProcess 的可识别参数/参数(据我所知,其余代码工作正常)。

from PyQt5 import QtCore, QtGui, QtWidgets
import os
import psutil

## Define origin path.
scriptpath = os.path.realpath(__file__)
scriptpath = scriptpath.replace(os.path.basename(__file__), "")
os.chdir(scriptpath)
origin = os.getcwd()

## Establish UI and interactions.
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        # event actions
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QVBoxLayout(central_widget)

        process_btn = QtWidgets.QPushButton("process")
        process_btn.clicked.connect(self.process)

        end_btn = QtWidgets.QPushButton("end")
        end_btn.clicked.connect(self.end)

        lay.addWidget(process_btn)
        lay.addWidget(end_btn)

        self.process = QtCore.QProcess(self)
        self._pid = -1

    @QtCore.pyqtSlot()
    def process(self):
        program = 'ping'
        arguments = ['-t', '192.168.0.1', '> test.txt'] # Ping 10 times to the router address and save output.
        self.process.setProgram(program)
        self.process.setArguments(arguments)
        ok, pid = self.process.startDetached()
        if ok:
            self._pid = pid

    @QtCore.pyqtSlot()
    def end(self):
        if self._pid > 0:
            p = psutil.Process(self._pid)
            p.terminate()
            self._pid = -1

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_()) 

有没有办法将通过 QProcess 运行的 cli 命令的输出保存到文本文件中?

注意:我曾尝试实现相同的功能,subprocess.call('ping -t 192.168.0.1 > test.txt', shell=True)但后来遇到了无法停止 ping 的问题。我可以阻止它的唯一方法是exit在运行我的 PyQt5 程序的 cli 中使用命令(关闭应用程序只是让文本文件继续更新),这对于带有 GUI 的程序来说并不理想。如果有人对此有解决方案,那么也许我可以回到它。

标签: pythonpyqt5qprocess

解决方案


使用QProcess setStandardOutputFile方法将过程的结果保存到文件中。


推荐阅读