Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. embed a python function into my Qt App.
Forum Updated to NodeBB v4.3 + New Features

embed a python function into my Qt App.

Scheduled Pinned Locked Moved Solved General and Desktop
32 Posts 4 Posters 6.9k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • JonBJ Offline
    JonBJ Offline
    JonB
    wrote on last edited by JonB
    #22

    I'm keeping an eye on this thread. As I said right at the start

    You can indeed go down @jsulm's path, but embedding is a lot more involved than just running a subprocess.
    But as phrased if all you want to do is run an external script with some command-line arguments [...], it really is simple to do with QProcess, should take one minute to write.

    I do hope/presume that (for both your sakes) for use case here all this embedding is indeed required and worth the effort! :)

    V 1 Reply Last reply
    1
    • V vinaygopal

      @jsulm yes i clean the build run qmake and then build the file everytime i change the pro file

      #-------------------------------------------------
      #
      # Project created by QtCreator 2019-11-21T10:31:03
      #
      #-------------------------------------------------
      
      QT       += core gui networkauth
      
      greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
      
      TARGET = example_project
      TEMPLATE = app
      
      
      # The following define makes your compiler emit warnings if you use
      # any feature of Qt which has been marked as deprecated (the exact warnings
      # depend on your compiler). Please consult the documentation of the
      # deprecated API in order to know how to port your code away from it.
      DEFINES += QT_DEPRECATED_WARNINGS
      
      # You can also make your code fail to compile if you use deprecated APIs.
      # In order to do so, uncomment the following line.
      # You can also select to disable deprecated APIs only up to a certain version of Qt.
      #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
      
      CONFIG += c++11
      
      SOURCES += \
              main.cpp \
              google_widget.cpp
      
      HEADERS += \
              google_widget.h
      
      FORMS += \
              google_widget.ui
      
      # Default rules for deployment.
      qnx: target.path = /tmp/$${TARGET}/bin
      else: unix:!android: target.path = /opt/$${TARGET}/bin
      !isEmpty(target.path): INSTALLS += target
      
      DISTFILES += \
          upload_to_cloud.py
      
      
      #CONFIG += no_lflags_merge
      
      INCLUDEPATH="C:/Users/vinay/AppData/Local/Programs/Python/Python38/include"
      LIBS += $$PWD/../../../AppData/Local/Programs/Python/Python38/libs/python38.lib
      
      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on last edited by
      #23

      @vinaygopal Looks correct to me. I would try this:

      • Delete build directory
      • Run qmake
      • build

      https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      0
      • V vinaygopal

        When i click a button, i want to open up the python script (.py file) and run the python script written by me and exit python. I should be able to pass arguments to the python file through Qt c++? please help me out on how to achieve this. i did do some reading about QProcess class but i am not able to achieve this.

        J.HilkJ Offline
        J.HilkJ Offline
        J.Hilk
        Moderators
        wrote on last edited by J.Hilk
        #24

        @vinaygopal how dead set are you on Python as the scripting language?

        If it's not dictated and just a random selection, I'll want to offer 2 alternatives

        https://doc.qt.io/qt-5/qscriptengine.html#details
        and
        https://doc.qt.io/qt-5/qjsengine.html#details

        for QScript and JavaScript respectively, no external libs required


        Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


        Q: What's that?
        A: It's blue light.
        Q: What does it do?
        A: It turns blue.

        1 Reply Last reply
        0
        • JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by JonB
          #25

          @vinaygopal said in embed a python function into my Qt App.:
          @vinaygopal originally wrote just:

          i want to open up the python script (.py file) and run the python script written by me and exit python. I should be able to pass arguments to the python file through Qt c++? please help me out on how to achieve this. i did do some reading about QProcess class but i am not able to achieve this.

          If that is indeed all he wants to do, he may not need any integrated scripting, he may just need to make his QProcess attempt work and we would be done....

          If he would say why/what the script is supposed to do which requires embedding, we would all know what is required....

          1 Reply Last reply
          0
          • JonBJ JonB

            I'm keeping an eye on this thread. As I said right at the start

            You can indeed go down @jsulm's path, but embedding is a lot more involved than just running a subprocess.
            But as phrased if all you want to do is run an external script with some command-line arguments [...], it really is simple to do with QProcess, should take one minute to write.

            I do hope/presume that (for both your sakes) for use case here all this embedding is indeed required and worth the effort! :)

            V Offline
            V Offline
            vinaygopal
            wrote on last edited by
            #26

            @JonB @jsulm @J-Hilk ok alright! i give up on embedding python into my program! it just doesn't seem to work however this is the reason for me to use Python, i have a file in my local desktop and i have to send it to the cloud and make the image uploaded a public image these cases can be easily achieved using python if i have to do it with javascript i will have to do it using node JS which will complicate the app, so from QProcess i am able to open the python file inside the python file i have a function called upload blob and it takes two arguments how do i call this function blob and pass those 2 arguments to them using QProcess().

            My C++ code

                QApplication a(argc, argv);
                qDebug()<<"working"<<endl;
                int result=QProcess::execute("C:/Users/vinay/AppData/Local/Programs/Python/Python38/python.exe",QStringList("C:/Users/vinay/Documents/first_qml_training/example_project/upload_to_cloud.py")<<"C:/Users/vinay/Documents/python folder/player1.png"<<"tank.png");
                qDebug()<<result<<endl;
            

            My python function

            #!/usr/bin/env python
            # -*- coding: utf-8 -*-
            from gcloud import storage
            import os
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="C:/Users/vinay/Downloads/My First Example Project-507e91a5b594.json"
            
            def upload_blob(source_file_name, destination_blob_name):
                """Uploads a file to the bucket."""
                bucket_name="example_1995"
                storage_client = storage.Client()
                bucket = storage_client.get_bucket(bucket_name)
                blob = bucket.blob(destination_blob_name)
            
                blob.upload_from_filename(source_file_name)
            
                print('File {} uploaded to {}.'.format(
                    source_file_name,
                    destination_blob_name))
                    
            print("i am working")
            

            "

            JonBJ 1 Reply Last reply
            0
            • V vinaygopal

              @JonB @jsulm @J-Hilk ok alright! i give up on embedding python into my program! it just doesn't seem to work however this is the reason for me to use Python, i have a file in my local desktop and i have to send it to the cloud and make the image uploaded a public image these cases can be easily achieved using python if i have to do it with javascript i will have to do it using node JS which will complicate the app, so from QProcess i am able to open the python file inside the python file i have a function called upload blob and it takes two arguments how do i call this function blob and pass those 2 arguments to them using QProcess().

              My C++ code

                  QApplication a(argc, argv);
                  qDebug()<<"working"<<endl;
                  int result=QProcess::execute("C:/Users/vinay/AppData/Local/Programs/Python/Python38/python.exe",QStringList("C:/Users/vinay/Documents/first_qml_training/example_project/upload_to_cloud.py")<<"C:/Users/vinay/Documents/python folder/player1.png"<<"tank.png");
                  qDebug()<<result<<endl;
              

              My python function

              #!/usr/bin/env python
              # -*- coding: utf-8 -*-
              from gcloud import storage
              import os
              os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="C:/Users/vinay/Downloads/My First Example Project-507e91a5b594.json"
              
              def upload_blob(source_file_name, destination_blob_name):
                  """Uploads a file to the bucket."""
                  bucket_name="example_1995"
                  storage_client = storage.Client()
                  bucket = storage_client.get_bucket(bucket_name)
                  blob = bucket.blob(destination_blob_name)
              
                  blob.upload_from_filename(source_file_name)
              
                  print('File {} uploaded to {}.'.format(
                      source_file_name,
                      destination_blob_name))
                      
              print("i am working")
              

              "

              JonBJ Offline
              JonBJ Offline
              JonB
              wrote on last edited by JonB
              #27

              @vinaygopal
              Which is why I asked as I did at the start! Really wish you had said!

              So you simply want to pass some string filenames to a script which does something, right? No need for integrated scripting.

              You need to tell us what actually happens/goes wrong!

              First just make your Python script print out everything in sys.argv so we can see.

              Oh, I see, you haven't twigged that at all. You can't just write a function in a standalone Python script/program. You need to have a main program in your script, and access argv for the command-line arguments!

              import sys
              # Main entry point of app
              if __name__ == "__main__":
                  # args = sys.argv
                  # count = len(sys.argv)
                  while i < len(sys.argv):
                      arg = sys.argv[i]
                      print(arg)
              

              There are millions of examples on the web.

              Separately, you'd better hope all your commands etc are happy with those / path separators rather than native \. I don't want to debate this again with others: some Windows stuff is happy with /, some is not.

              V 1 Reply Last reply
              3
              • JonBJ JonB

                @vinaygopal
                Which is why I asked as I did at the start! Really wish you had said!

                So you simply want to pass some string filenames to a script which does something, right? No need for integrated scripting.

                You need to tell us what actually happens/goes wrong!

                First just make your Python script print out everything in sys.argv so we can see.

                Oh, I see, you haven't twigged that at all. You can't just write a function in a standalone Python script/program. You need to have a main program in your script, and access argv for the command-line arguments!

                import sys
                # Main entry point of app
                if __name__ == "__main__":
                    # args = sys.argv
                    # count = len(sys.argv)
                    while i < len(sys.argv):
                        arg = sys.argv[i]
                        print(arg)
                

                There are millions of examples on the web.

                Separately, you'd better hope all your commands etc are happy with those / path separators rather than native \. I don't want to debate this again with others: some Windows stuff is happy with /, some is not.

                V Offline
                V Offline
                vinaygopal
                wrote on last edited by vinaygopal
                #28
                This post is deleted!
                JonBJ 1 Reply Last reply
                0
                • V vinaygopal

                  This post is deleted!

                  JonBJ Offline
                  JonBJ Offline
                  JonB
                  wrote on last edited by JonB
                  #29

                  @vinaygopal
                  Why in the world would you try to access sys.argv[4:5] if you have said there 3 arguments?

                  Please copy my code and run, then you will see your args are sys.argv[1:3]. You can pass those as appropriate to any functions you write.

                  Yes, you are already passing your arguments on the command line from your C++ QProcess::execute() call.

                  Please do a little printing/debugging yourself to discover this.

                  V 1 Reply Last reply
                  0
                  • JonBJ JonB

                    @vinaygopal
                    Why in the world would you try to access sys.argv[4:5] if you have said there 3 arguments?

                    Please copy my code and run, then you will see your args are sys.argv[1:3]. You can pass those as appropriate to any functions you write.

                    Yes, you are already passing your arguments on the command line from your C++ QProcess::execute() call.

                    Please do a little printing/debugging yourself to discover this.

                    V Offline
                    V Offline
                    vinaygopal
                    wrote on last edited by
                    #30

                    @JonB sorry! i wasn't able to understand the code flow i made that comment thank you so much. this was such a fun ride.

                    i was able to achieve what i wanted to do. this forum is really helpful.

                    Thank you.

                    JonBJ 1 Reply Last reply
                    2
                    • V vinaygopal

                      @JonB sorry! i wasn't able to understand the code flow i made that comment thank you so much. this was such a fun ride.

                      i was able to achieve what i wanted to do. this forum is really helpful.

                      Thank you.

                      JonBJ Offline
                      JonBJ Offline
                      JonB
                      wrote on last edited by JonB
                      #31

                      @vinaygopal
                      I am glad we have helped you :)

                      Let me say one thing about asking questions here. As I have mentioned, you came in saying "QProcess doesn't work" and then pursued embedding, which as I suspected turned out to be a lot of work. Yet you did not need that, and could have had the QProcess solution in 5 minutes.

                      The moral is: it is usually worth explaining here exactly what you are actually trying to achieve in a few words, rather than "how do I embed" or similar-ish (unless you really know what you are talking about!). Often questions like that actually assume the wrong approach. The experts here will see your description and may save you a lot of time by proposing a simple method to achieve your goal.

                      V 1 Reply Last reply
                      2
                      • JonBJ JonB

                        @vinaygopal
                        I am glad we have helped you :)

                        Let me say one thing about asking questions here. As I have mentioned, you came in saying "QProcess doesn't work" and then pursued embedding, which as I suspected turned out to be a lot of work. Yet you did not need that, and could have had the QProcess solution in 5 minutes.

                        The moral is: it is usually worth explaining here exactly what you are actually trying to achieve in a few words, rather than "how do I embed" or similar-ish (unless you really know what you are talking about!). Often questions like that actually assume the wrong approach. The experts here will see your description and may save you a lot of time by proposing a simple method to achieve your goal.

                        V Offline
                        V Offline
                        vinaygopal
                        wrote on last edited by
                        #32

                        @JonB got it thanks will keep this in mind :)

                        1 Reply Last reply
                        0

                        • Login

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved