DEV Community

Cover image for How to give user input in Kaggle Notebook
Karan Bhardwaj
Karan Bhardwaj

Posted on

How to give user input in Kaggle Notebook

Kaggle Notebook doesn't support interactive user input (e.g., using the input() method in Python) since it runs in a cloud environment where code cells are executed in sequence without waiting for user interaction.

So, in cases where we have to give user input, we can bring the environment variable to our rescue.

Assuming the case that there is a command named some_command when executed asks for input argument, let's say an API key. So the steps to pass the API key will be as follows:

1. Declare an environment variable

We use the os library to declare an environment variable.

import os

# Instantiate the API key as an environment variable
os.environ['API_KEY'] = "whatever_is_the_key"
Enter fullscreen mode Exit fullscreen mode

2. Passing the environment variable as a user input

Here, we will use the echo shell command to pass the API key as a user input argument to command some_command.

# run the shell command
!echo $API_KEY | some_command
Enter fullscreen mode Exit fullscreen mode

What happened above is that "echo $API_KEY" generated the output (in this case, the API key "whatever_is_the_key"), and "|" sent this output as an input argument to some_command.

This way, you can pass input arguments to the commands you need to execute.

In case you have to pass multiple input arguments, you can modify echo shell command as,

# Assume you have environment variables as I, ME, and YOU
!echo "$I" "$ME" "$YOU" | some_command
Enter fullscreen mode Exit fullscreen mode

This approach can be beneficial when automating tasks that require external inputs or when working with APIs in non-interactive environments like Kaggle

Happy Coding!🤗🤗

Top comments (0)