Python Class only works in %SYS namespace
After running many tests to kick the tires calling Python from COS (which worked fine) in any directory, I encountered problems when trying to access Python libraries like Numpy from any OTHER namespace. I saw some other posts about this but the resolution seems unclear. When I run the test program method numpytest below in %SYS it works just fine. If i run the Python method in any other namespace I get:
PITT>do ##class(test.python).numpytest()
DO ##CLASS(test.python).numpytest()
^
<OBJECT DISPATCH> *python object not found
Here is the test program - i did the install with IRISPIP on pandas and numpy and they ran fine.
{ ClassMethod numpytest() As %String [ Language = python ]
{
# do ##class(testnp.test).numpytest()
import numpy as np
import math
arr = np.array([1, 2, 3, 4, 5]) print(arr) x=np.random.randint(1, 15, 1) #generate a number between 1 and 15
print("Random num=",x) y=math.pi
print("This is pi:",y)
x="hello world"
print(x)
a=2+5
print("a=",a)
}
ClassMethod test() As %String [ Language = python ]
{
import pandas
print("In test python")
#df = pandas.read_json(json, orient="index")
}
ClassMethod Getdata() As %String
{
// do ##class(test.python).Getdata()
// calling Python from COS
set b=##class(%SYS.Python).Import("builtins")
set d=##class(%SYS.Python).Import("datetime")
set today=d.date.today()
write !,today.isoformat()
set d=##class(%SYS.Python).Import("math")
write !,d.pi
set np=##class(%SYS.Python).Import("numpy")
set a = np.array([3, 4])
set x= np.exp(4)
write !,b.float(x)
set rand = np.random.randint(1, 15, 1)
W !,"rand=",b.int(rand)
Quit x
}
Any tips or help would be most welcome!
Just a small hint, if you have more than one statement on one line, separate them with a semicolon
print('one'); print('two') # this is OK print('one') print('two') # syntax error
This works for me (pay attention to the semicolons!)
ClassMethod numpytest() As %String [ Language = python ] { import numpy as np import math arr = np.array([1, 2, 3, 4, 5]); print(arr); x=np.random.randint(1, 15, 1) # generate a number between 1 and 15 print("Random num=",x) y=math.pi print("This is pi:",y) x="hello world" print(x) a=2+5 print("a=",a) }
an the output is
USER>d ##class(Py.Demo).numpytest() [1 2 3 4 5] Random num= [13] This is pi: 3.141592653589793 hello world a= 7 USER>w $zv IRIS for UNIX (Ubuntu Server LTS for x86-64) 2021.2 (Build 649U) Thu Jan 20 2022 08:49:51 EST USER>
I think the problem is that this is a windows environment. For some reason IRIS is not looking in the correct spot for python libraries. But why is it working for %SYS only?????
There seems to be a missing configuration or PATH variable that needs set???
A missing configuration is a good starting point... I think on Windows as well as on Linux, first you have to install the packages you are interested in, see here. Then you can import them.