xineta5158
xineta5158

Reputation: 127

Docker accepting input to python script

I am simulating an online IDE using docker.

Each time user submits their code, an image will be generated and be run. It is working as expected, however when the code asks for input e.g

print("Begin script")
x = input("Enter your name")
print("you entered")
print(x)

python code to run docker:

container = subprocess.Popen(["docker", "run","-it", "--rm", "--name",imageName,imageName])

enter image description here

enter image description here I am unable to pass in input to the python script. It does not even print the prompt "Test input" into terminal I have tried using docker attach command, and I am enter able to enter into terminal, but it is not sending input to python script

Upvotes: 0

Views: 1674

Answers (2)

Niket
Niket

Reputation: 73

I am really sorry that it doesn't answer your question directly, but I am sure it would help.
I think you are trying to make an entire docker container for every user. You don't strictly need that if you only plan to allow them to use your service as a simple IDLE.
You could use something like socat or xinetd to achieve the same. Here is an example that uses socat to run a python script for anyone who connects to the server: https://gitlab.com/Milkdrop/xmas-2020/-/tree/master/misc/complaint

Also, I recommend AGAINST using exec() or eval() to allow others to execute code on your system. Actually, you should not use them in general either.

Upvotes: 0

AKX
AKX

Reputation: 169407

Via comments:

subprocess.run(["docker", "run","-ti", "--rm", "--name",imageName,imageName], capture_output=True)

You're using a function that is described to (emphasis mine)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.

You also say

it does not even print the prompt of the input message

This is because you've explicitly told subprocess.run() to capture the output instead of allowing it to be printed to stdout. If you were to print the return value of that call, you'd possibly see the output.

If you just want some static input to be piped to the process and get the output, you could use

proc = subprocess.run(..., input="123\n", capture_output=True)
print(proc.stdout)

to simulate someone entering 123 and a newline.

If you want an interactive experience, you will need to use subprocess.Popen() instead. Wiring the stdin/stdout/stderr pipes is somewhat tricky, especially if you need a TTY-like experience.

Upvotes: 1

Related Questions