QProcess CLI 命令 - 'Bad parameter' 指定输出保存位置时

QProcess CLI Command - 'Bad parameter' when specifying output save location

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

似乎保存 cli 命令的输出不算作 QProcess 的可识别 argument/parameter(据我所知,其余代码工作正常)。

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 的问题。我可以停止它的唯一方法是在我的 PyQt5 程序 运行 所在的 cli 中使用 exit 命令(关闭应用程序只是让文本文件继续更新),这并不理想对于带有 GUI 的程序。如果有人对此有解决方案,那么也许我可以回去。

使用QProcess setStandardOutputFile方法将处理结果保存到文件中。