#!/usr/bin/python
"""
Takes the textarea from run_python.html
and runs the code in that element.
"""
import cgi
from os import system
FORM = cgi.FieldStorage()
print("Content-Type: text/plain\n")
ERROR = False
try:
    CODE = FORM['code'].value
    print("your code is \n\n" + CODE)
except KeyError:
    print("please enter code")
    ERROR = True

if not ERROR:
    FILE = open('/tmp/code.py', 'w')
    FILE.write(CODE)
    FILE.close()
    print("\n... running the code ...\n")
    CMD = 'python /tmp/code.py > /tmp/out'
    RETVAL = system(CMD)
    if RETVAL != 0:
        print("the code has an error")
    else:
        FILE = open('/tmp/out', 'r')
        OUTP = FILE.readlines()
        print("the output is \n\n", OUTP[0])
