How to use python script in c++ (qt) code? (web-scraping aspect) - python

I want to build a gui application which allows to convert money with real-time exchange rate. I'm using MacOs and QtCreator (I have also PyCharm and VS Code, but I especially want to use QtCreator to make my gui)
Firstly I've created a Python script which gets me a real-time exchange rate from a stooq page. I did it, because I wanted to learn web Scraping.
Secondly, I've wanted to make a qui for it and I've already known how to use and write an application in Qt Creator in C++. So, I've created an app. First idea was to connect a python script to my c++ qt project. I've searched in the internet, but all I'd found were ideas to create dynamic library from python script. I don't know how to do it, especially in QtDesigner.
So, I made a brainstorm and I came to an idea. Why not saving an input to my python script from QtWindow to txt file, then calling python script and finally, save an output from python script to another txt file. Now I would just read real-time exchange rate from my txt file.
But I faced a problem. When I'm calling my python script, compiler says that I don't have packages used in script (requests and beautifullsoup). I checked that I have installed that libraries on my computer (terminal -> 'brew install requests', 'brew install bs4')
Unless I have it installed, Qt doesn't see it.
Do you have any idea how to say Qt that I have that stuff already installed or can you tell me an easier way to do add python script to c++ qt code or can you tell me an easier way to make web scraping? Because, based on my web searching, I did't find another that easy way to make Gui as Qt.
(Oh, and one more quick question: How can I tell Qt a path to file? As you can see in my code, I had to past full path, because Qt didn't see my file (I pasted in both in source folder, compile folder and a folder below) Remember - I'm using Mac. I know that on Windows only a filename would work.
Function in Qt c++ calling Python script:
void MainWindow::PythonScriptOpen()
{
std::string filename = "/Users/username/Desktop/programming/Currency_converter/Currency_Converter/currency_converter.py";
std::string command = "python ";
command += filename;
system(command.c_str());
}
Error:
Traceback (most recent call last): File
"/Users/username/Desktop/programming/Currency_converter/Currency_Converter/currency_converter.py",
line 3, in
import requests ImportError: No module named requests

You have to install requests by pip(3) install requests

Related

How do to use a python script in Unity?

I'm trying to run a face detection model in Unity. It gets input from the webcam, then spits out a face. But trying to make this work with C# has been an absolute nightmare. And despite all my suffering, I still haven't been able to make it work!
If I could use python, I'd be able to get it done easily. So, obviously, I want to find a way to get a python script working in Unity. But IronPython is the only thing I've been able to find, and it's outdated.
I need either knowledge of how to make IronPython work in spite of being outdated, or some other method. Please.
Unfortunately, Unity at this time does not support Python. Although, there is an asset that you can use a bit of Python with. I am not sure what you can do with this asset but I know it could help a minimal amount:https://assetstore.unity.com/packages/tools/integration/python-interpreter-645
Quick Note: Most programming languages work about the same way. If you figure out the documentation and grammar/punctuation for C#/UnityC#, you should be off just fine.
I try to use python once on Unity and I found a few ways:
There is a package call "IronPython" where you can add a python file to your unity project and then call a function from C# to your python code, to do that you should follow this:
We already know that we can use python to use .net internal calls.
Now we may use the same to start a console that can accept a scripting language in Unity engine.
To do this we have to include certain dll files.
These dll files must be present in Assets>plugins
IronPython.dll
IronPython.Modules.dll
Microsoft.Scripting.Core.dll
Microsoft.Scripting.dll
Microsoft.Scripting.Debugging.dll
Microsoft.Scripting.ExtensionAttribute.dll
Microsoft.Dynamic.dll
Once the Plugins are in place.
Initiate the Cs code
PythonEngine engine = new PythonEngine();
engine.LoadAssembly(Assembly.GetAssembly(typeof(GameObject)));
engine.ExecuteFile("Test.py");
Where test.py is the python code.
Initiate python side:
import UnityEngine from UnityEngine
import *
Debug.Log("Hello world from IronPython!")
References:
https://github.com/cesardeazevedo/Unity3D-Python-Editor
http://techartsurvival.blogspot.in/2013/12/embedding-ironpython-in-unity-tech-art.html
IronPython in Unity3D
the issue with this way is that most of the python module are not supported.
2.the second way is to create a file like json that contain the data you want to send to the json and then create an output json that send the output from the python script, this way is very limited with what you can send because the data must be contain in your json.
the last way that work for me is to install the Nuget package and copy the script from python to c# line by line with the relevent module installed in Unity and it's work for me, but copy a long code can take time.
this is a reference to the package:
https://github.com/GlitchEnzo/NuGetForUnity
and then to install the relevent package you should press on NuGet → Manage NuGet Packages and the choose the relevent package(for me it was Numpy and it work grate).
hope it will help you
I don't know how recent it is but there is a Unity package for python available on unity 2019.3 and further versions.
Warning the first versions of this package can't use Python3.
You can see more for yourself by the following link.
https://docs.unity3d.com/Packages/com.unity.scripting.python#2.0/manual/index.html
I hope this may help you.
We are thrilled to announce that Python for Unity 4.0.0-exp.5 is now available!
4.0.0-exp.5 is a major upgrade from our last public release, and incorporates a large number of changes. In summary:
Based on Python 3.7; scripts based on Python 2.7 will need to be ported.
Users no longer need to install Python on their system.
In-process Python is no longer reinitialized when the Unity domain reloads.
Removed the out-of-process API. The PySide example now runs in-process and is much simpler.
Limited support for a virtual environment workflow via the ProjectSettings/requirements.txt file.
Many bug fixes.
Documentation for the Python for Unity package is available here, and the full changelog can be found here.
This is an experimental release, and thus is not visible in Package Manager. To install this package, open Package Manager, click the + at the top left and select Add package by name.... Enter com.unity.scripting.python as the name and and 4.0.0-exp.5 as the version and click Add. Alternatively, you may edit Packages/manifest.json and add "com.unity.scripting.python": "4.0.0-exp.5", to the list of dependencies, or edit the existing entry for Python for Unity to update the version.
Soursce: https://forum.unity.com/threads/python-for-unity-release-announcements.1084688/
Documentation: https://docs.unity3d.com/Packages/com.unity.scripting.python#4.0/manual/index.html
Unity not supported python, But you Can write Python Code and run it by Socket programing, Create Server with python and send data,in C# Connect to server and use data sended with python.

How do I make a macOS app out of my Python program?

I've made this question because I had to go through the whole process of creating my own application using Apple's somewhat lacking documentation, and without the use of py2app. I wanted to create the whole application structure so I know exactly what was inside, as well as create an installer for it. The latter of these is still a mystery, so any additional answers with information on making a custom installer would be appreciated. As far as the actual "bundle" structure goes, however, I think I've managed to get the basics down. See the answer below.
Edit: A tutorial has been linked at the end of this answer on using PyInstaller; I don't know how much it helps as I haven't used it yet, but I have yet to figure out how to make a standalone Python application without the use of a tool like this and it may just be what you're looking for if you wish to distribute your application without relying on users knowing how to navigate their Python installations.
A generic application is really just a directory with a .app extension. So, in order to build your application, just make the folder without the extension first. You can rename it later when you're finished putting it all together. Inside this main folder will be a Contents folder, which will hold everything your application needs. Finally, inside Contents, you will place a few things:
Info.plist
MacOS
Resources
Frameworks
Here you can find some information on how to write your Info.plist file. Basically, this is where you detail information about your application.
Inside the MacOS you want to place your main executable. I'm not sure that it matters how you write it; at first, I just had a shell script that called python3 ./../Resources/MyApp.py. I didn't think this was very neat though, so eventually I called the GUI from a Python script which became my executable (I used Tkinter to build my application's GUI, and I wrote several modules which I will get to later). So now, my executable was a Python script with a shebang pointing to the Python framework in my application's Frameworks folder, and this script just created an instance of my custom Tk() subclass and ran the mainloop. Both methods worked, though, so unless someone points out a reason to choose one method over the other, feel free to pick. The one thing that I believe is necessary, is that you name your executable the SAME as your application (before adding the .app). That, I believe, is the only way that MacOS knows to use that file as your application's executable. Here is a source that describes the bundle structure in more detail; it's not a necessary read unless you really want to get into it.
In order to make your executable run smoothly, you want to make sure you know where your Python installation is. If you're like me, the first thing you tried doing on your new Mac was open up Terminal and type in python3. If this is the case, this prompted you to install the Xcode Command Line tools, which include an installation of Python 3.8.2 (most recent on Xcode 12). Then, this Python installation would be located at /usr/bin/python3, although it's actually using the Python framework located at
/Applications/Xcode.app/Developer/Library/Frameworks/Python3.framework/Versions/3.8/bin/python3
I believe, but am NOT CERTAIN, that you could simply make a copy of this framework and add it to your Frameworks folder in order to make the app portable. Make a copy of the Python3.framework folder, and add it to your app's Frameworks folder. A quick side note to be wary of; Xcode comes packaged with a lot of useful tools. In my current progress, the tool I am most hurting for is the Fortran compiler (that I believe comes as a part of GCC), which comes with Xcode. I need this to build SciPy with pip install scipy. I'm sure this is not the only package that would require tools that Xcode provides, but SciPy is a pretty popular package and I am currently facing this limitation. I think by copying the Python framework you still lose some of the symlinks that point to Xcode tools, so any additional input on this would be great.
In any case, locate the Python framework that you use to develop your programs, and copy it into the Frameworks folder.
Finally, the Resources folder. Here, place any modules that you wrote for your Python app. You also want to put your application's icon file here. Just make sure you indicate the name of the icon file, with extension, in the Info.plist file. Also, make sure that your executable knows how to access any modules you place in here. You can achieve this with
import os
os.chdir('./../Resources')
import MyModules
Finally, make sure that any dependencies your application requires are located in the Python framework site-packages. These will be located in Frameworks/Python3.framework/Versions/3.X.Y/lib/python3.x.y/site-packages/. If you call this specific installation of Python from the command line, you can use path/to/application/python3 -m pip install package and it should place the packages in the correct folder.
P.S. As far as building the installer for this application, there are a few more steps needed before your application is readily downloaded. For instance, I believe you need to use the codesign tool in order to approve your application for MacOS Gatekeeper. This requires having a developer license and manipulating certificates, which I'm not familiar with. You can still distribute the app, but anyone who downloads it will have to bypass the security features manually and it will seem a bit sketchy. If you're ready to build the installer (.pkg) file, take a look at the docs for productbuild; I used it and it works, but I don't yet know how to create custom steps and descriptions in the installer.
Additional resources:
A somewhat more detailed guide to the anatomy of a macOS app
A guide I found, but didn't use, on using codesign to get your app past Gatekeeper
A RealPython tutorial I found on using PyInstaller to build Python-based applications for all platforms

How to distribute C++ application which calls Python?

I know there is some way to call Python from C++, like Python/C API or Boost.Python. My question is, how can I distribute the application? For example, does user still need to install Python and Python packages on their machine?
My user case is: I want to use some Python code from my C++ code. The main application is written in C++. Then I am going to deploy my app. The goal is to make the app self contained, and user don't need to install Python and Python packages at all.
The possible steps may be :
1, calling Python from C++ via Python/C API or boost.Python from source code.
2, bring Python/C libraries together with application.
I hope after these 2 steps, my app will be a self-contained and standalone software. User can just copy the app folder to any other machines which has no Python installed.
Note that due to license issue, I can not use PyInstaller. I also meet some problems when trying to use "Nuitka" to make the Python part self contained. So I am now trying directly calling Python from C++. I know it will run on my developer machine. But needs to confirm that this solution can also make app self-contained and won't ask user to install Python.
Update: Now I feel I need to do something to make my app self-contained if I use Python/C to call python from C++ :
1, I need to bring all needed runtime with my app. (C++ runtime of course, and the python_version.dll)
2, I need to deploy a Python interpreter inside my app. Simply copy the Python folder from Python installation and remove some not needed files (like header files, lib files)
3, use Py_SetPythonHome function to points to the copied Python interpreter inside the app.
I'd say you're on the right track. Basically, you should obtain a Python (shared or static) library, compile your program with it, and of course bundle the Python dependencies you have with your program. The best documentation I've read is available here: https://docs.python.org/3.8/extending/embedding.html#embedding-python-in-another-application. Roughly, the process is:
Get a Python library from python.org and compile with ./configure --enable-shared (I believe omitting --enable-shared does only produce the python binary).
Compile your program. Have it reference the headers under Include and link the library. Note that you can obtain the compiler and linker flags you need as described here.
Call Python code from within your application using e.g. PyRun_SimpleString() or other functions from the C API. Note that you may also depend on the Python standard library (under Lib in the distribution) if there's any functionality you use from it.
If you linked against Python statically, at this point you're done, aside from bundling any Python code you depend on, which I'm not sure is relevant in your case.
I am suffering from the same problem, I had a project which is made up of C++ and python(embedded) and there is a problem of deployment/distribution.
After research, I got a solution which is not perfect (means it will be helpful to run your app in other system)
change visual studio in release mode and compile(you got a folder in your working directory)
install pyinstaller (pip install pyinstaller)
then navigate to pyinstaller folder and command:-pyinstaller.exe "your script_file_path.py"
-it will create a dist folder
copy that folder in working folder where exe exists.
remember.
dist folder and c/python code compiled by same version of python.
now good to go.
it will work.

How do I add a dependency to my application?

I'm currently working on an application called SatStressGUI, a GUI application written in Python, which was passed down to me from previous interns who have worked on it. It relies on dependencies such as wxPython (which, as most of you probably know, must be installed on the user's own computer before the application the user is trying to run runs properly if the application calls on the the wxPython library). In the gitHub, under contents->resources->lib->python2.5->sitepackages, you'll see all the libraries which the application is dependent on (wxPython is under the name wx, for example) copied and pasted. If I am correct, the existence of these libraries in sitepackages makes it so that the user does not have to manually install libraries such as wxPython themselves: the user can simply run the GUI application by downloading the whole package under "clone or download" in the main page and run the satstressgui executable file located in contents->MacOS. I believe there is a file somewhere, perhaps boot.py (located in contents->resources) that says, "hey, before the user runs this executable file, download the libraries under contents->resources->lib->python2.5->sitepackages."
All that being said, I want to add a new dependency to the program. I am trying to use FFMPEG, which is an external program that allows you to take a sequence of images and convert it to a video. In satstressgui.py, which is the main source code file for this application (located in contents->resources) I use the subprocess python module to call on the external program FFMPEG. Here is the code snippet:
#FFMPEG is an external program that converts a sequence of images to a video.
subprocess.call(['/usr/local/bin/ffmpeg', '-framerate', \
framerate, '-f', 'image2','-pattern_type', \
'glob', '-i', self.directory + '/orbit_*.png', \
'-r', '10', '-s', '620x380', self.directory +
".avi"])
At the moment, this works on my own computer because I have FFMPEG installed (in case it matters, I installed it using homebrew). How do I make it so that FFMPEG becomes a dependency in my program just like wxPython (i.e., I make it so that FFMPEG is "installed" on my user's computer before they run the application)? I've looked on FFMPEG's website and it looks as if there is a gitHub for it, but other than that I'm quite lost.
NOTE: I've also tried to use imageio (another Python library) to convert a sequence of images to a video in my application, but I've failed. I tried to copy and paste the files from imageio's gitHub to contents->resources->lib->python2.5->sitepackages, but whenever I try to "import imageio" it fails. This might be because I am adding the dependency wrong or because imageio only works on Python 2.6 and above and my program is written in Python 2.5. If someone could give me an answer to any of these questions and help me import a module such as imageio or add an external program such as FFMPEG as a dependency in my application, that'd be very much appreciated! I can't link imageio's main website because of some restrictions by Stack Overflow, but you should be able to find it by simply searching it up on google (the main website has a photo of an astronaut in it's top banner). I would more prefer a solution using FFMPEG, however, seeing as I've already implemented it in my code.
Thank you so much in advance for your help! I'm quite new to computer science and programming so I apologize if a lot of the clarifications or questions I'm asking are rudimentary.
Here is the link to the gitHub of my application: https://github.com/nhudoan/SatStressGUI
Here is the link to FFMPEG's main website: https://ffmpeg.org/download.html#repositories

Displaying graph using python online compiler with matlab library

I've written a program with python to display a graph with matlab library which displays it in a new window with python3. I would like to use an online compiler (https://www.tutorialspoint.com/execute_python_online.php) so that I would be able to share the program, but because this requires matlab to open a window, the online compiler fails. How am I able to solve this?
Can you just send the entire .py file to someone else so they can run it on their computer? As far as I know, there is no option for running Python code online without requiring a download / installation that is free where you can also install libraries (like matplotlib).

Categories