Qt中进程的相关操作使用QProcess类。
1. 进程间无通信
使用QProcess的execute()方法。
1 2 3 4 5 6 7 8 9 10
| QProcess process; QString cmd = "python"; QStringList argvs; argvs << "run.py" << QString::number(1) << "a" << "b"; int ret = process.execute(cmd, argvs); if (ret < 0) { qWarning() << "Process execute failed: " << ret << process.error(); } process.close();
|
对应的run.py文件为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import sys number_map = { "0": ("a", "b", "c"), "1": ("a1", "b1", "c1") }
def download_one(argv1, argv2, argv3): print("argv data", argv1, argv2, argv3) [a, b, c] = number_map.get(, ("0", "0", "0"))
def download_last(): while (True): [argv1, argv2, argv3] = input("input:").split() if argv1 == "exit": break print("input data", argv1, argv2, argv3) [a, b, c] = number_map.get(argv1, ("0", "0", "0"))
if __name__ == '__main__': download_one(sys.argv[1], sys.argv[2], sys.argv[3])
|
2. 进程间使用标准输入输出
QProcess调用python进程的并实现进程间的读写。使用QProcess的start()方法。
c++代码如下,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| QProcess process; QString cmd = "python"; QStringList argvs; argvs << "run.py"; process.start(cmd, argvs); if (!process.waitForStarted()) { qCritical() << "start process failed"; return; } process.waitForReadyRead(); qDebug() << "python to start" << process.readAll(); for (int index = 0; index < 10; index++) { int a = 1; QString b = "abc"; QString c = "c"; QString params = QString::number(a) + " " + b + " " + c + "\n"; process.write(params.toStdString().c_str()); bool ret = process.waitForBytesWritten(); if (!ret) { qWarning() << "Process execute failed: " << ret << process.error(); } process.waitForReadyRead(); QByteArray qba = process.readAll(); qDebug() << "python download log:" << qba; ... } } process.write("exit 0 0"); process.waitForFinished(3000); process.close();
|
python, run.py代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import sys number_map = { "0": ("a", "b", "c"), "1": ("a1", "b1", "c1") }
def download_last(): while (True): [argv1, argv2, argv3] = input("input:").split() if argv1 == "exit": break print("input data", argv1, argv2, argv3) [a, b, c] = number_map.get(argv1, ("0", "0", "0"))
if __name__ == '__main__': download_last()
|
3. 关闭指定的进程
程序运行中有时可以控制其他进程的关闭,比如使用多个QWebEngine,无法正常退出程序,在退出时,手动关闭这些Qtwebengineprocess.exe进程即可:
1 2 3 4 5 6 7 8 9 10
| void closeProcess(const QString appName) { QString cmd = "taskkill /im " + appName + " /f"; QProcess pro; pro.execute(cmd); pro.close(); }
closeProcess("Qtwebengineprocess.exe");
|
非Qt的c++程序中,可是使用system(“***”)方法实现进程的关闭:
- windows:
system("taskkill /f /t /im app.exe");