Exchanging info between running C++ code and python script - python

I have a python script that is called inside a C++ program. The python script creates a directory based on the current time, puts files in there, and then execution returns to C++. I want to save a parameters file into the directory created in the python program.
I figure my options are:
Pass in the text to save in the parameters file to the Python program and have it create and save the file
Return the location of the directory to C++ from python so it knows where to save the file
Use C++ to locate the most recently created directory after execution of the python script and put file there
I'm not sure how to do any of this. My python script is not embedded. I use
std::string test = "python analyzeData2.py";
system(test.c_str());
to call a python script.
Any ideas how to do this?

I'd go with option B -- return the location of the directory to c++ from python so it knows where to save the file.
If you plan on using system(), something like this:
char* dirname[64];
FILE* fin;
system("python analyzeData2.py > created.log");
fin = fopen("created.log", "r");
fgets(dirname, sizeof(dirname), fin);
fclose(fin);
/* dirname has contents of created.log */
...

Related

How can I pass variables from Python back to C++?

I have 2 files - a .cpp file and a .py file. I use system("python something.py"); to run the .py file and it has to get some input. How do I pass the input back to the .cpp file? I don't use the Python.h library, I have two separate files.
system() is a very blunt hammer and doesn't support much in the way of interaction between the parent and the child process.
If you want to pass information from the Python script back to the C++ parent process, I'd suggest having the python script print() to stdout the information you want to send back to C++, and have the C++ program parse the python script's stdout-output. system() won't let you do that, but you can use popen() instead, like this:
#include <stdio.h>
int main(int, char **)
{
FILE * fpIn = popen("python something.py", "r");
if (fpIn)
{
char buf[1024];
while(fgets(buf, sizeof(buf), fpIn))
{
printf("The python script printed: [%s]\n", buf);
// Code to parse out values from the text in (buf) could go here
}
pclose(fpIn); // note: be sure to call pclose(), *not* fclose()
}
else printf("Couldn't run python script!\n");
return 0;
}
If you want to get more elaborate than that, you'd probably need to embed a Python interpreter into your C++ program and then you'd be able to call the Python functions directly and get back their return values as Python objects, but that's a fairly major undertaking which I'm guessing you want to avoid.

Is There A Way To Call A Python3 Function From PHP 7.4.7?

I have a PHP file in my server, and I want it to be able to call Python function from another file. In the Python file, I want to write some information into a text file (.txt). When I run the Python file on its own, it works, and the text file contains the content that I told it to have. But, when I try to call the Python file from my PHP file, it does not work. In addition, I am using a Microsoft Window's Operating System, but I accept answers for Linux (preferably Ubuntu/Debian) as that is where I am running my web server. But, in the end, what I want to be able to do is this:
PHP:
<?php
// Call helloWorld() from Test.py
?>
And my python:
def helloWorld():
print("Hello World!")
helloWorld() # Calls the above function
I have tried:
exec('python Test.py') // The files are in the same directory
shell_exec('python Test.py') // The files are in the same directory
If possible, although not necessary, it would be nice to have the actual PHP script, rather than just "try shell_exec()". Again, that is not mandatory.
Thank you in advance, and any help is appreciated.

Python Kodi - Force Python handling .pyo like .py

Hey guys i definitely getting crazy
i want to force Python to handle a .pyo like a .py
i got kodi xbmc forked and getting crazy
i already tried out and changed multiple lines and nothing changed?
i linked them here:
const std::string ADDON_PYTHON_EXT = "*.py";
changed this line to *.pyo
return URIUtils::HasExtension(m_strPath, ".py"); changed this line to. .pyo
i thought that would be enough after compiling, still nothing happens when try to open a add-on
still python does not load .pyo files and does not handle them as .py
btw: i figured out deleting all .py files in the folder and just let the first loaded .py file there so 1 -> .py and the others are all .pyo the add-on works.
but when deleting this firstly loaded .py and using this as a .pyo
it fails.
So what do i have to change that it always use .pyo
First UPDATE:
i tried it out,
it does indeed work as a workaround
Created a dummy -> include.py
with just 1 line import service was enough.
But i want to fix this directly in kodi.
in documentions
"If there is a current pyc file, this is taken as the compiled version, so no compile step has to be taken before running the command. Otherwise the py file is read, the compiler has to compile it"
So easy said,
execute .py if not available check if .pyo
but i cannot find where to change / add this method
i cannot find even the method right for the execution
Second Update:
i added these lines in githublink to file
//pyoextension == script
std::string pyoextension = script;
//Check if the file does exist
if (!CFile::Exists(script, false))
{
//pyoextension append o to get -> .pyo
pyoextension = script + "o";
//Check if pyoextension exist -> .pyo
//if not nothing exist throw error
if (!CFile::Exists(pyoextension, false)){
CLog::Log(LOGERROR, "%s - Not executing non-existing script %s", __FUNCTION__, script.c_str());
return -1;
}
LanguageInvokerPtr invoker = GetLanguageInvoker(pyoextension);
return ExecuteAsync(pyoextension, invoker, addon, arguments);
}
LanguageInvokerPtr invoker = GetLanguageInvoker(script);
return ExecuteAsync(script, invoker, addon, arguments);
Checking if the the add-on does not exist as a .py file checking if the .pyo file is there, and execute that instead. But still the checking does work, but it still throws an error out that it cannot start the script
Changing such line (const std::string ADDON_PYTHON_EXT = "*.py"; changed this line to *.pyo) is not a good solution
Main reason is that the kodi is configured to use .py extension to be load from addon.xml file which tradition is followed by all the addon. Changing such headers file will only result to work addon only in your custom build kodi and you have to modify all other addon along with it.
The solution I prefer most is you should follow below steps:
Create a function in your python script (let's call it as function named service() which execute all the necessary code from your file named service.py)
Now create a python file (include.py) to include it in addon.xml containing code as below:
include.py
import service
service.service()
It might not even be worth it, Kodi is moving to python3 soon, and python3 dropped pyo files. It might use pyc then, but that's not sure right now.

Running a Python script from Access VBA

I'm having trouble finding many resources, but I'm trying to get vba to run a python script
Const pyScript = "C:\Test\Weekend_Exceptions\Weekend_Exception.py"
Dim dblRetVal As Double
dblRetVal = Shell("C:\Python34\python.exe " & pyScript)
I know my python script works and should output a file, but its not. Additionally the vba is not tirggering a debug flag so I'm not sure where I am wrong. Any advice would be appreciated.
You don't give too much details so i'll make some assumptions
Probably your python script read some local file this will cause your script to raise a FileNotFoundError and exit
To make the test copy the entire arg string to Shell, in your case "C:\Python34\python.exe C:\Test\Weekend_Exceptions\Weekend_Exception.py", open a cmd with Win+r , paste and run, not being in the right directory should raise the same error.
If this is the problem, make a makestuff.bat file with the code
#echo off
#cd C:\Test\Weekend_Exceptions\
#C:\Python34\python.exe Weekend_Exception.py
#echo on
Then call the bat from Shell("C:\Place\of\your\bat\makestuff.bat")
Return with more details to we work on a solution
Here is how I did:
I created a File1.bat to open the File2.py. The code in File1.bat is:
#echo off
#h:
#cd H:\Path\Cronus\Rangers
#C:\Python3\python.exe File2.py
#echo on
Note that File2.py is inside H:\Path\Cronus\Rangers folder. That's why we need to open it before.
I created a function in VBA to open a .bat file:
Option Compare Database
Function MacroPythonSARH()
On Error GoTo MacroPythonSARH_Err
Call Shell("H:\Path\Cronus\Rangers\File1.bat", 1)
MacroPythonSARH_Exit:
Exit Function
MacroPythonSARH_Err:
MsgBox Error$
Resume MacroPythonSARH_Exit
End Function

Python C API - Call C function from embedded python (callback)

I have a .cpp file loading python file and calling a function. I have a logger class in the .cpp and I want to use it from .py file.
Example:
# python-file.py
def FunctionCalledFromC_API():
log("some string")
log("some error", error)
log("some debug info", debug)
# etc...
And the .cpp
// cpp-file.cpp
// Load python file, do stuff...
PyObject *args = PyTuple_New(0);
PyObject_CallObject(pFunctionCalledFromC_API, args);
Py_DECREF(args);
I want that the log("some string") function of the .py file calls my logger.log(...) function from the C++ application.
As Markku K. suggested, I made all my app a DLL and I'll try soon.
That's what I'll do (for people with the same question):
Make my app a single DLL
Make an executable to run it (obvious)
Make a Python file containing the functions (example: logger.log()). That functions should call the DLL's equivalent functions.
Do "trial&error" until it works ;)
EDIT:
After a lot of "trial&error", I've found a way to do it!
Using boost::python to expose my API and the standard Python API to load the .py file I made this work!
But I'll have to start the application with a python file importing the shared object and calling the main function :(
Anyway, Thanks Markku K. for your help!

Categories

Resources