2

The notebook I use asks for some user input. I can change code within the Jupyter Notebook but I cannot change the code of the Python libraries the Jupyter Notebook is relying on. The user input request comes from one of these libraries.

Is it possible to have Jupyter Notebook automatically send some predefined user input? That is to say, simulate the user input?

For example, in the following Jupyter Notebook cell, I would like to have Jupyter Notebook automatically inputs O during the user prompt so that the user doesn't have to enters any input themselves:

enter image description here

The user input comes from some library via this code:

inp = input ("Dataset with same name already exists.\nEnter 'O' to Overwrite or 'L' to Load the existing one." )
Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501

2 Answers2

2

My environment at the moment of answer:

jupyter core     : 4.6.3
jupyter-notebook : 6.1.4
ipython          : 7.19.0
ipykernel        : 5.3.4
jupyter client   : 6.1.7

You can use a context manager to temporarily replace input with the message you want to re-enter. This code should work in the scope of one cell:

from contextlib import contextmanager
import builtins

@contextmanager
def repeat(answer: str):
    try:
        original_input = builtins.input
        
        def mock_input(*args, **kwargs):
            return answer
        
        builtins.input = mock_input
        yield
    
    finally:
        builtins.input = original_input

        
#TEST
with repeat('O'):
    answer_1 = input('Continue?')
    answer_2 = input('Continue?')
    answer_3 = input('Continue?')
    
print(answer_1)
print(answer_2)
print(answer_3)

In case if it didn't work or if you'd like to replace input for more then one cell (suppose, you run several or all cells at one) you may try something like this:

from ipykernel.ipkernel import IPythonKernel

ipython_input = IPythonKernel._input_request

def my_input(*args, **kwargs):
    print('Hello world!')
    return ipython_input(*args, **kwargs)

IPythonKernel._input_request = my_input

Just replace the body of my_input with what you need.

As an alternative try to replace IPythonKernel.raw_input instead of _input_request which is the first method underhood of input in Jupyter.

Vitalizzare
  • 4,496
  • 7
  • 13
  • 32
0

I am not aware of any way to handle it without leaving the gentle grace of Python. However, you should be able to extend Python and set PyOS_ReadlineFunctionPointer to something that returns the desired value. Like here.

But I would definitely try to check for other kinds of solutions first. E.g. the display() method has some implementation - maybe its behavior can be changed. Or maybe the method itself could be changed. Or maybe you don't need to call it at all - maybe you can just do what it does while providing all the necessary input yourself.

Eugene Pakhomov
  • 9,309
  • 3
  • 27
  • 53