mario_sunny
mario_sunny

Reputation: 1432

Executing a Python file from within Python, feeding it input and retrieving output

I'm writing a web application where users may attempt to solve various programming problems. The user uploads an executable .py file and the application feeds it some pre-determined input and checks whether the output is correct. (similar to how Codeforce works)

Assuming I have uploaded the user's script, how do I execute the user's script from within my own Python script, feeding the user's script input that would be captured by a normal input() function, and retrieving the output from print() functions so that I can verify its correctness?

Upvotes: 0

Views: 272

Answers (1)

mario_sunny
mario_sunny

Reputation: 1432

Figured it out.

Note: If you are going to use this in a production environment, make sure you place restrictions on what the user can execute.

executor.py

import subprocess

# create process
process = subprocess.Popen(
        ['python3.4','script_to_execute.py'], # shell command
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
)

# encode string into bytes, since communicate function only accepts bytes
input_data = "Captured string".encode(encoding='UTF-8')

# send the input to the process, retrieve output of print() function
stdoutdata, stderrdata = process.communicate(input=input_data)

# decode output back into string
output_data = stdoutdata.decode(encoding='UTF-8')

print(output_data)

script_to_execute.py

input_data = input()

print("Input recieved!\nData: " + input_data)

Output of executor.py

Input recieved!
Data: Captured string

Upvotes: 1

Related Questions