QProcess 将参数传递给 python 脚本
QProcess passing arguments to a python Script
from PIL import Image
def porcentaje(path):
im = Image.open(path, "r")
im.show()
width, height = im.size
type = im.mode
format = im.format
pixels=im.getdata()
n = len(pixels)
im=im.load()
nblack = 0
noblack=0
for pixel in pixels:
if pixel < 50:
nblack += 1
else:
noblack+=1
porcentajefinal=(nblack*100)/n
print(porcentajefinal)
return(porcentajefinal)
(porcentaje(path))
主窗口.cpp (QT 创建者(
void MainWindow::on_pushButton_2_clicked()
{
QString path = QFileDialog::getOpenFileName(this,
tr("All Files (*)"));
qDebug()<<path;
QDir dir1("D:/QTCProjects/prueba");
QFile file1("D:/QTCProjects/prueba/2_1.py");
QString script1 = "D:/QTCProjects/prueba/2_1.py";
QFile file2(script1);
qDebug() << dir1.exists() << file1.exists() << file2.exists();
// these all result in true, true true
QProcess *myProcess = new QProcess();
myProcess->start("python.exe D:/QTCProjects/prueba/2_1.py" );
myProcess->waitForFinished(-1);
qDebug() << "myProcess:" << myProcess->readAll(); }
这个 python 需要一个名为 path 的变量才能运行,我在 qtcreator 中使用 Qstring 路径获取此变量,我如何使用 Qprocess 为 python 提供此变量。
如果要通过终端将参数传递给脚本,请使用以下结构:
python.exe /path/of/your_script.py arg1 arg2 ... argn
然后要获取参数,我们必须使用 sys.argv,它是一个存储以下内容的列表:
['/path/of/your_script.py', 'arg1', 'arg2', ..., 'argn']
因此,在您的情况下,您应该通过以下方式获取参数 sys.argv[1]
:
2_1.py
from PIL import Image
import sys
def porcentaje(path):
im = Image.open(path, "r")
im.show()
width, height = im.size
type = im.mode
format = im.format
pixels=im.getdata()
n = len(pixels)
im=im.load()
nblack = 0
noblack=0
for pixel in pixels:
if pixel < 50:
nblack += 1
else:
noblack+=1
porcentajefinal=(nblack*100.0)/n
print(porcentajefinal)
return(porcentajefinal)
path = sys.argv[1]
porcentaje(path)
在Qt方面,python.exe是主程序,其他参数是参数,所以你的代码必须具有以下结构:
void MainWindow::on_pushButton_2_clicked()
{
QString path = QFileDialog::getOpenFileName(this, "All Files (*)");
qDebug()<<path;
if(!path.isEmpty()){
QDir dir("D:/QTCProjects/prueba");
QFileInfo info(dir, "2_1.py");
qDebug() << dir.exists() << info.exists();
QProcess process;
process.start("python.exe", QStringList()<< info.absoluteFilePath() << path);
process.waitForFinished(-1);
qDebug() << "myProcess:" << process.readAll();
}
}
相关文章:
- 如何在c++中使用system()来运行包含空格的python脚本
- 如何将真正的字符串从python c-api转换为python脚本
- 在从Qt调用的Python脚本中导入OpenCV崩溃
- 使用 Main() 返回值作为 python 脚本的参数
- 如何制作启动 Python 脚本的 linux 后台进程(在 c 中)
- 从Raspberry Pi / Linux上的Python脚本运行和停止C++程序
- C++ Python 并不总是执行 Python 脚本
- 从C++调用 Python 脚本以持续流式传输数据
- 将数据从 c++ 文件连续发送到 Python 脚本以进行进一步处理
- 错误,在嵌入在C++程序中的 python 脚本中使用 matplotlib 时
- 在使用PyInstaller冻结Python脚本时包含一个C++可执行文件
- 使用 pipe() 和 fdopen() 将数据从 Python 脚本传递到 Windows 中的C++应用程序
- Python 脚本到 c .obj 文件
- 从 c++ 运行 python 脚本时出现问题
- C++ :从C++脚本内部触发存储在我机器上的 python 脚本
- 从 c++ 中运行 python 脚本,找不到模块
- 参数从 Python 脚本传递到 C++ 使用 boost-python
- 无法从Linux,C ++执行"my_script" python脚本"main(filename)"功能;pModule = PyImport_Import(pName);返回空值
- 如何在C ++(qt)代码中使用python脚本?(网页抓取方面)
- 将对象从 python 脚本传递给 c++