Evaluate local Wolfram Language code directly from Python with a persistent kernel session.

Using a Wolfram notebook...

Create a local Wolfram Language session

Import the module:

from wolframclient.evaluation import WolframLanguageSession

Create a session using the default path:

session = WolframLanguageSession()
  • The default path depends on the environment and may also depend on the version of the Wolfram Engine being used.
  • To create a session with a nondefault path, provide the path to the Wolfram Engine as the first argument, e.g.: WolframLanguageSession(C:/Program Files/Wolfram Research/Mathematica/12.0/wolfram.exe).

Evaluate Wolfram Language expressions

Import the function:

from wolframclient.language import wlexpr

Compute the squares of an array of integers:

session.evaluate(wlexpr('Map[#^2 &, Range[5]]'))

End the the session

Terminate the session object:

session.terminate()
  • The session must be terminated to properly shut down the Wolfram Engine process.

Using a Jupyter notebook...

Create a local Wolfram Language session

Import the module:

Create a session using the default path:

  • The default path depends on the environment and may also depend on the version of the Wolfram Engine being used.
  • To create a session with a nondefault path, provide the path to the Wolfram Engine as the first argument, e.g.: WolframLanguageSession(C:/Program Files/Wolfram Research/Mathematica/12.0/wolfram.exe).

Evaluate Wolfram Language expressions

Import the function:

Compute the squares of an array of integers:

End the the session

Terminate the session object:

  • The session must be terminated to properly shut down the Wolfram Engine process.

Using the command line...

Create a local Wolfram Language session

Open a terminal window and invoke the Python interpreter:

$ python

Import the module:

>>> from wolframclient.evaluation import WolframLanguageSession

Create a session using the default path:

>>> session = WolframLanguageSession()
  • The default path depends on the environment and may also depend on the version of the Wolfram Engine being used.
  • To create a session with a nondefault path, provide the path to the Wolfram Engine as the first argument, e.g.: WolframLanguageSession(C:/Program Files/Wolfram Research/Mathematica/12.0/wolfram.exe).

Evaluate Wolfram Language expressions

Import the function:

>>> from wolframclient.language import wlexpr

Compute the squares of an array of integers:

>>> session.evaluate(wlexpr('Map[#^2 &, Range[5]]')) 
[1, 4, 9, 16, 25]

End the the session

Terminate the session object:

>>> session.terminate()

Exit the Python shell:

>>> exit()
  • The session must be terminated to properly shut down the Wolfram Engine process.

Notes

This workflow requires the Wolfram Client Library for Python to be installed. See the workflow Install the Wolfram Client Library for Python for more information.
The Python interpreter must be Python 3.5 (or higher).