Function Repository Resource:

StartPythonSession

Source Notebook

Simplify launching of a new Python session

Contributed by: Arnoud Buzing

ResourceFunction["StartPythonSession"][dependencies]

starts a new Python session, given a list of dependencies.

Details

ResourceFunction["StartPythonSession"] greatly simplifies the creation of a new Python session, which is normally done with the more general StartExternalSession function.
Automatically creates a new virtual environment for the list of dependencies.
The environment name is a SHA1 hash of the list of dependencies.

Examples

Basic Examples

Start a new Python session that includes the "scipy" package:

In[1]:=
session = ResourceFunction["StartPythonSession"][{"scipy"}]
Out[1]=

Import the package in the session:

In[2]:=
ExternalEvaluate[session, "import scipy"]

Load an external function, here the Python version of a fast fourier transform:

In[3]:=
fft = ExternalFunction[session, "scipy.fft.fft"]
Out[3]=

Generate some random real numbers:

In[4]:=
r = RandomReal[1, 10]
Out[4]=

Compute the FFT via Python:

In[5]:=
py = fft[r] // Normal
Out[5]=

Compute the equivalent FFT with Fourier. Note that the option FourierParameters is used here to match the Python result:

In[6]:=
wl = Fourier[r, FourierParameters -> {1, -1}]
Out[6]=

Compute the distance between the two results:

In[7]:=
EuclideanDistance[py, wl]
Out[7]=

Terminate the external session:

In[8]:=
DeleteObject[session]

Publisher

WolframExternalFunctions

Requirements

Wolfram Language 14.0 (January 2024) or above

Version History

  • 1.0.0 – 08 May 2024

License Information