Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Passing arguments to Python function using QProcess



  • Hi everyone
    My goal is to pass the path of the file to the xml_writer_path function whose signature is xml_writer_path(pathFile) in storage_retrieval.py
    My code is:

    QString pathFile = QFileDialog::getSaveFileName(new QWidget, "Save file", "C:", "XML (*.xml);");
    QProcess p;
    QStringList arguments { "-c", "from storage_retrieval import xml_writer_path, sys; print(xml_writer_path(str(sys.argv[1])))", pathFile};
    p.start("python", arguments);
    p.waitForFinished();
    

    This code doesn't work. Any suggestions?


  • Lifetime Qt Champion

    Hi,

    What exactly does not work ?
    You should check if your process ends in error and if so what that error is.
    You should also checkout the standard output and error channels for anything printed there.



  • @giusirux
    Please act on what @SGaist has advised you.

    Try your command from outside of Qt at a terminal: I am not convinced the import is correct.

    Also you have chosen to pass pathFile using Qt / syntax. Are you on Linux/MacOS? If you are on Windows, when testing outside Qt please pass the path with /s to see whether that is acceptable to your xml_writer_path() method?



  • @SGaist @JonB Hi
    with xml_writer_path function, I write pathFile in a file which is located in my Qt project.
    The strange thing is that if I execute the command "python -c "from storage_retrieval import xml_writer_path, sys; print(xml_writer_path(str(sys.argv[1]))) C:/Users/Giusi/Desktop/test.xml " from cmd, the function is executed correctly.



  • @giusirux
    Then you must act on @SGaist 's:

    You should check if your process ends in error and if so what that error is.

    You should also checkout the standard output and error channels for anything printed there.

    Look at QProcess documentation/examples for these.

    I must also pick you up on the exactitudes:

    execute the command "python -c "from storage_retrieval import xml_writer_path, sys; print(xml_writer_path(str(sys.argv[1]))) C:/Users/Giusi/Desktop/test.xml " from cmd

    The correct will actually be:

    python -c "from storage_retrieval import xml_writer_path, sys; print(xml_writer_path(str(sys.argv[1])))" C:/Users/Giusi/Desktop/test.xml
    

    Note the position of the "s.



  • @JonB hi
    So, that's it
    133de85b-c08a-4a03-beb8-84fbde988042-image.png
    I don't know why there is "None"

    P.S. : when in the last answer I used the double quotes before "python" and after " C:/Users/Giusi/Desktop/test.xml", it was to mention the command I ran in cmd. I'm sorry I wasn't clear



  • @giusirux
    That looks good. The None is doubtless being printed somewhere or a return result, I wouldn't worry about it. [EDIT: Oh I see, it's the output from your print(...).]

    Now we must take you back to: you still have not explained how you know "This code doesn't work"?

    It is time you put in the code to show what is in stdard output/error when you run your QProcess.


  • Lifetime Qt Champion

    @giusirux said in Passing arguments to Python function using QProcess:

    xml_writer_path

    Does that method return anything to be printed ?



  • @SGaist nope. Its goal is to write pathFile in a file which is included in my Qt project


  • Lifetime Qt Champion

    Then seeing None printed is normal since that method returns None.



  • @JonB when I run my QProcess, nothing is happening.
    xml_writer_path 's goal is to write pathFile in a file which is included in my Qt project.
    In fact, when I run my QProcess, the file is not modified



  • @giusirux
    Last time of saying:

    It is time you put in the code to show what is in stdard output/error when you run your QProcess.



  • @JonB
    QObject::connect(buttonSave, &QPushButton::clicked, widget, saveFile);

    in saveFile:

    void saveFile() {
        //PYTHON
        qDebug() << "save File";
        QProcess p;
        QString filename = QFileDialog::getSaveFileName(new QWidget,
                                           "Save file", "C:",
                                           "XML (*.xml);");
        qDebug() << filename;
        QStringList arguments { "-c", "from storage_retrieval import xml_writer_path, sys; print(xml_writer_path(str(sys.argv[1])))", filename };
        p.start("python", arguments);
        p.waitForFinished();
        QMessageBox::information(widget," ","done");
        qDebug() << "end";
    }
    

    Application output:
    ad2a3111-9e30-4a8e-af14-1b91eaa0395e-image.png
    QMessageBox appears without problems.


  • Lifetime Qt Champion

    As already written, and quoted: read the standard output and standard error of your QProcess.



  • @SGaist yes, sorry.. So:

    void saveFile() {
        //PYTHON
        qDebug() << "save File";
        QProcess p;
        QString filename = QFileDialog::getSaveFileName(new QWidget,
                                           "Save file", "C:",
                                           "XML (*.xml);");
        qDebug() << filename;
        QStringList arguments { "-c", "from storage_retrieval import xml_writer_path, sys; print(xml_writer_path(str(sys.argv[1])))", filename };
        p.start("python", arguments);
        p.waitForFinished();
        qDebug() << p.readAllStandardOutput();
        qDebug() << "-----";
        qDebug() << p.readAllStandardError();
        QMessageBox::information(widget," ","done");
        qDebug() << "end";
    }
    

    b7d10d55-623f-4ea8-86be-d0c4a66db459-image.png

    in xml_writer_path:

    def xml_writer_path(filepath):
    
            try:
                    print("[+] Xml writer path in esecuzione...")
    
                    flag=0
                    with open("metadati_segmentazione.txt", "r") as input_file, open("metadati_segmentazione2.txt", "w") as output_file:
                            
                            for line in input_file:
                                    
                                    if line.startswith("#metadati_fase3"):
                                            flag=1
                                            output_file.write(line)
                                            
                                    elif line.startswith("s3name") and flag == 1:
                                            output_file.write(line.replace("s3name:","s3name:"+str(filepath)))
    
                                    else:
                                            output_file.write(line)
    
                    input_file.close()                
                    output_file.close()
    
                    os.remove("metadati_segmentazione.txt")
                    os.rename("metadati_segmentazione2.txt","metadati_segmentazione.txt")
    
                    print("[+] Esecuzione xml writer path terminata.")
    
            except:
                    print("[-] Error xml writer path.")
    


  • @giusirux
    This isn't what we meant, but never mind....

    Change your try to have print(filepath) as its first statement.

    Change your except to print full information about the exception. Never just put an except like you have with no detail into your code. You might even be better commenting out the try and the except lines while you debug your issue. Put further print statements into the body to see where the error is occurring. All this is what is expected of debugging a program problem.


  • Lifetime Qt Champion

    @giusirux said in Passing arguments to Python function using QProcess:

    metadati_segmentazione.txt

    Where is that file exactly located ?

    Do not use bare except, at least print the exception you got to know what is happening.



  • @SGaist @JonB thank you very much for all the advice!
    So, the problem was: "metadati_segmentazione.txt" was in the wrong position in my Qt project (it was in debug folder project and I don't know why).
    I'll mark this post as solved!
    Thank you again



  • @giusirux
    Yes, but please change that bare except with no detail, it just hides any problem which may occur!


Log in to reply