Executing a Python file from within Python, feeding it input and retrieving output
<p>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 <a href="http://www.codeforces.com/problemset" rel="nofollow">Codeforce</a> works)</p>

<p>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 <code>input()</code> function, and retrieving the output from <code>print()</code> functions so that I can verify its correctness?  </p>

<p>Figured it out.</p>

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

<p><strong>executor.py</strong></p>

<pre><code>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)
</code></pre>

<p><strong>script_to_execute.py</strong></p>

<pre><code>input_data = input()

print("Input recieved!\nData: " + input_data)
</code></pre>

<p><strong>Output of executor.py</strong></p>

<pre><code>Input recieved!
Data: Captured string
</code></pre>

python python-3.x execution