4

Of course, I can use the this code:

session = StartExternalSession["Python"];
mmaVar1 = ExternalEvaluate[session, "a=[3,6,4];a"]

{3, 6, 4}

Then I can get a MMA variable mmaVar1, its name is assigned by Python. But I have to say it hard to write python code in a string line. So I like typing a > key into DefaultPythonSession:

enter image description here

But how to get the value of a in the DefaultPythonSession and assign to a MMA variable? This is my current method:

  • Find the order of the DefaultPythonSession by ExternalSessions[]: enter image description here

  • Then

    mmaVar2 = ExternalEvaluate[ExternalSessions[][[2]], "a"]
    

Dirty solution...

yode
  • 26,686
  • 4
  • 62
  • 167
  • Maybe SelectFirst[ExternalSessions["Python"], #["Name"] === "DefaultPythonSession" &] make it less dirty ;) – Ben Izd Jun 10 '22 at 09:01
  • 1
    Even better ExternalEvaluate`GetDefaultExternalSession["Python"] – Ben Izd Jun 10 '22 at 09:03
  • @BenIzd Magic!!!! – yode Jun 10 '22 at 09:26
  • @BenIzd Do you mind to add an answer? I think it can help to read for the following user – yode Jun 10 '22 at 13:22
  • Strongly related, if not duplicate: https://mathematica.stackexchange.com/q/250259/1871 – xzczd Jun 10 '22 at 13:47
  • @yode You didn't let me write comment. Astonished by your speed :D – Ben Izd Jun 10 '22 at 14:35
  • @BenIzd It is a awesome solution, which is better than all answers in that link given by xzczd – yode Jun 10 '22 at 14:40
  • Thanks for your kind words, I think that post has some differences from yours, there, the person wants to directly use the session's variable without knowing (I guess) that there are separate, here your main point was to find the default session in a clean matter ;) Even though I wrote one of the answers in the link, I really don't know the difference between ExternalEvaluate and ExternalValue. Maybe that should be the next question. – Ben Izd Jun 10 '22 at 14:52

1 Answers1

5

You could get DefaultPythonSession directly by:

ExternalEvaluate`GetDefaultExternalSession["Python"]

or if you prefer using ExternalSessions by:

SelectFirst[ExternalSessions["Python"], #["Name"] === "DefaultPythonSession" &]

You should also note, that starting fresh Mathematica, will not start a python session automatically, so if you didn't start one, the first method return unevaluated command while in the second method, you have the option to return whatever you want (default is Missing["NotFound"]).

Ben Izd
  • 9,229
  • 1
  • 14
  • 45