Yes, absolutely!
I'm actually making some finishing touches to a major revamp of the Python package that should be included with the upcoming Macaulay2 1.25.11 release. They should make running Python code even simpler. In the meantime, here's one way to do with the current state of the package:
Let's say we have the following Python code in the file foo.py:
def f(x):
return x**2
y = f(5)
And let's say that foo.py is in the directory /my/python/dir on our system. In M2, we can do the following:
i1 : needsPackage "Python";
i2 : sys = import "sys";
i3 : sys@@"path"@@append "/my/python/dir";
i4 : foo = import "foo";
(Note that @@ is playing the role of Python's . -- we're not able to overload . in Macaulay2 and @@ has similar precedence.)
foo is now a Python module object, and we can access all of its variables:
i5 : foo@@y
o5 = 25
o5 : PythonObject of class int
i6 : foo@@f
o6 = <function f at 0x73916c761440>
o6 : PythonObject of class function
i7 : foo@@f 7
o7 = 49
o7 : PythonObject of class int
And to convert to a Macaulay2 object, use "value":
i8 : value oo
o8 = 49