Python function call from Matlab - error occurred "Conversion to int64 from py.NoneType is not possible."

8 Ansichten (letzte 30 Tage)
I want to call a python function from Matlab.
I have two Python files. one file can call the other file. The content of the file named, calculation.py is as follows
def addNumbers(a, b):
print("Sum is ", a + b)
def subtractNumbers(a, b):
print("Difference is ", a - b)
def multiplyNumbers(a, b):
print("Product is ", a * b)
def divideNumbers(a, b):
print("Division is ", a / b)
def modulusNumbers(a, b):
print("Remainder is ", a % b)
The content of the another python file named call_file.py is as follows
from calculation import addNumbers, multiplyNumbers
I wrote a matlab code to call call_flie.py. The matlab code is as follows
pyenv
path_add = fileparts(which("call_file.py"))
if count(py.sys.path,path_add)==0
insert(py.sys.path,int64(0),path_add)
end
pyOut = py.call_file.addNumbers(5, 2);
sum = int64(pyOut);
disp(sum)
I received the error "Error using int64
Conversion to int64 from py.NoneType is not possible.
Error in Test1 (line 8)
sum = int64(pyOut);
"
How can I solve the error?
Thank you.

Antworten (1)

Ayush Aniket
Ayush Aniket am 14 Jun. 2024
Hi Saswati,
The error message you are getting is due to the fact that the addNumbers function in your calculation.py Python file does not return any value; it only prints the result. When you try to convert the output of py.call_file.addNumbers(5, 2) to int64 in MATLAB, it fails because the Python function effectively returns None, which cannot be directly converted to an integer in MATLAB.
To solve this issue, you need to modify your Python functions in calculation.py to return their results instead of just printing them as shown below:
def addNumbers(a, b):
return a + b

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by