TransWikia.com

How to use Python's input() with External Evaluation?

Mathematica Asked on April 23, 2021

I want to use input() in Python code which runs in the Wolfram Notebook.

So I create an external evaluation cell by typing ">" and choosing Python. Then I define this function:

def func():
    x = input()
    print(x)

Then I try to call it:

func()

which makes Mathematica run forever and not evaluate.

Can I call Python’s input() from within the notebook?

2020-09-04 updt. "input() reads from standard input. There is no standard input when using a notebook."

yes, but Jupyter does support it though

One Answer

I found a trick using TemplateExpression <* *> and SetDelayed in Mathematica.

As an example, I try to define a python function like this, which duplicates the input string:

def func():
    return input()*2

the Mathematica code is:

pysession = StartExternalSession["Python"];
wlfunc[] := ExternalEvaluate[pysession, "<* InputString[] *> *2"]
ExternalEvaluate[pysession, "func = <* wlfunc *>"]

(Note that python function input is equivalent to Mathematica function InputString)

Now, the function func defined in the python session can get input from the FrontEnd of Mathematica:

ExternalEvaluate[pysession, "[func() for i in range(3)]"]

I should mention that this trick is quite limited, for example,

ExternalEvaluate[pysession, "func() + func()"]

will return a Failure, because the function is effectively defined in Mathematica rather than python. To avoid this, use

ExternalEvaluate[pysession, "<* wlfunc[] *> + <* wlfunc[] *>"]

Answered by Michael Chen on April 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP