In current versions of the Wolfram Language you can simply start a Python session in a virtual environment as follows (here I am using astropy
as an example, but you can do this with any Python package):
session = StartExternalSession[<|
"System" -> "Python",
"Evaluator" -> <|"Dependencies" -> {"astropy"}|>,
"SessionProlog" -> {
"from astropy.time import Time",
"from astropy.coordinates import get_body_barycentric",
"from astropy import units as u"
}|>]
Note how I specify the dependent astropy
package and how I am also running session initialization code. Now we can define a callable function with some python code:
EarthMarsDistance = ExternalFunction[session, "
def distance_earth_mars(date_str):
try:
time = Time(date_str)
earth = get_body_barycentric('earth', time)
mars = get_body_barycentric('mars', time)
separation = (mars - earth).norm()
distance_au = separation.to(u.au)
return distance_au.value
except ValueError:
return None
"]
This function computes the distance from Earth to Mars for a given ISO date string. You can call it directly from the Wolfram Language:
EarthMarsDistance[DateString[Now, "ISODateTime"]]
This gave the answer of 1.29486
(astronomial units) at the time of evaluation.
You can then also use the EarthMarsDistance
function in other Wolfram Language code, for example a plot over time:
ListLinePlot[
Table[
EarthMarsDistance[DateString[t, "ISODateTime"]],
{t, DateRange[Now, Now + Quantity[1000, "Days"]]}]]
Which gives a nice plot:

In this case you can do this directly in the Wolfram Language with the AstroDistance function:
AstroDistance[Entity["Planet", "Mars"]]
But if you have Python code that you would like to call from the Wolfram Language, then this is the route I suggest you take. I have attached a notebook with all the inputs from this comment.
Attachments: