Group Abstract Group Abstract

Message Boards Message Boards

1
|
5.7K Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

How to import Python Libraries with ExternalEvaluate?

Posted 2 years ago

I want to use specific python libraries via the Mathematica frontend. This is possible as follows

In[30]:= ExternalEvaluate["Python", "from sympy import isprime; isprime(7)"]
Out[30]= True

However, if I directly try to evaluate the same using > at the beginning of a line to use an external code cell, this does not work. For instance,

from sympy import isprime; isprime(7)

gives as output,

Out[31] = Failure[[WarningSign] Message: No module named 'sympy' Tag: PythonError ]

How can we make this work from within external code cells?

POSTED BY: Asim Ansari
3 Replies

Recent versions of Wolfram Language support Python virtual environments that let you specify Python packages quite easily. For example, this creates a session with a Python virtual environment that includes the sympy package:

session = StartExternalSession[<|
   "System" -> "Python",
   "Evaluator" -> <|"Dependencies" -> {"sympy"}|>,
   "SessionProlog" -> "from sympy import symbols, Eq, solve"|>]

You can then use ExternalEvaluate and call Python code, for example:

ExternalEvaluate[session, "
x, y = symbols('x y')
equation = Eq(x**5 - 4, 0)
[complex(s) for s in solve(equation, x)]"]

The output will be a list of complex numbers:

{1.31951 + 0. I, 0.40775 - 1.25493 I, 0.40775 + 1.25493 I, -1.0675 - 0.775587 I, -1.0675 + 0.775587 I}

Of course you can solve this specific example directly in the Wolfram Language as well and much more elegantly:

SolveValues[x^5 == 4.0, x]

But if you have existing Python sympy code that you would like to integrate directly into the Wolfram Language, then this is the best way to do it. I have attached a notebook with the code from this comment.

Attachments:
POSTED BY: Arnoud Buzing
Posted 2 years ago
POSTED BY: Asim Ansari
Posted 2 years ago
POSTED BY: Alec Graves
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard