0
$\begingroup$

I'm trying to make a wrapper REPL for the free Wolfram Engine (on Cygwin, there are a bit of I/O issues) in Python, so I am using the wolframclient library. However, whenever I use D[x^2,x] as a test, instead of returning 2x, it gives Times[2, Global`x]. My code is below:

#!/usr/bin/env python
from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wlexpr
import readline
count=0

with WolframLanguageSession('/cygdrive/c/Users/School/Downloads/Mathematica/WolframKernel.exe') as session:
    while True:
        expr=input('In['+str(count)+']:= ')
        print('Out['+str(count)+']= '+str(session.evaluate(wlexpr(expr))))
        count+=1
    

Edit: ToString[expr,InputForm] helped with the expression, but is there a way to get % to expand to the last expression?

$\endgroup$

1 Answer 1

1
$\begingroup$

The problem seems to be $Line and Out[] are not updated. I don't know why but you could override those variables:

Python

from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wlexpr
count=1

with WolframLanguageSession(r"C:\Program Files\Wolfram Research\Mathematica\12.2\WolframKernel.exe") as session:

    # Beacuse Out is Protected, it should be Unprotected first
    session.evaluate(wlexpr('Unprotect[Out];'))

    while True:
        expr=input(f'In[{count}]:=')

        # Exit mechanism
        if expr == 'Quit[]':
            break

        # update $Line
        session.evaluate(wlexpr(f'$Line={count};'))

        # store result
        result=session.evaluate(wlexpr(expr))

        # update Out
        session.evaluate(wlexpr(f'Out[{count}]={result};'))

        # print result
        print(f'Out[{count}]={result}')

        count+=1

Command-Line

In[1]:= a=99
Out[1]= 99

In[2]:= b=123
Out[2]= 123

In[3]:= c=D[x^2,x]
Out[3]= Times[2, Global`x]

In[4]:= %
Out[4]= Times[2, Global`x]

In[5]:= %2
Out[5]= 123

In[6]:= Out[1]
Out[6]= 99
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.