gpt4 book ai didi

python - QProcess 将参数传递给 python 脚本

转载 作者:行者123 更新时间:2023-11-30 05:07:39 26 4
gpt4 key购买 nike

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))

mainwindow.cpp (QT Creator)

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 路径获取这个变量,我如何用 Qpr​​ocess 给 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();
}
}

关于python - QProcess 将参数传递给 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47276571/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com