python - 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 的程序来说并不理想。如果有人对此有解决方案,那么也许我可以回到它。
解决方案
使用QProcess
setStandardOutputFile
方法将过程的结果保存到文件中。
推荐阅读
- javascript - 如果刷新页面,JS不会重新提交表单
- javascript - 浏览器扩展:防止脚本被执行
- javascript - 如何在这个数组中添加所有值?它每次都创建一个新的 CLIENT 数组并将值推送给它
- go - 通过client-go在端口转发中升级连接错误
- opengl - OpenGL 网格 + 镜像变换 = 错误的光照
- react-native - Pod install 在升级 react-native 版本后删除 React
- javascript - 编写通用的 React 输入钩子
- excel - 缩短大小写选择 [公式填充] 代码,因为过程太大
- android - Android fastindex 滚动回收器视图
- pip - 在 GCP Composer Airflow 上安装私有依赖的任何成功案例?