#!/usr/bin/env python3#-*-coding:utf-8-*-R ' ' learning.py A Python 3 tutorial from http://www.liaoxuefeng.com Usage : Python3 learning.py "Import sys def check_version (): v = sys.version_info if v.major = = 3 and V.minor >= 4 : Return True print (' Your current Python is%d.%d. Please use Python 3.4. ' Percent (V.major, V.minor)) return False if not check_version (): Exit (1) Import OS, io, JSON, SU bprocess, tempfilefrom urllib import parsefrom wsgiref.simple_server import make_server EXEC = Sys.executableport = 39093 HOST = ' local.liaoxuefeng.com:%d '% porttemp = tempfile.mkdtemp (suffix= ' _py ', prefix= ' learn_python_ ') INDEX = 0 def main () : httpd = make_server (' 127.0.0.1 ', PORT, application) print (' Ready to Python code on PORT%d ... '% port) Httpd.s Erve_forever () def get_name (): Global Index index = index + 1 return ' test_%d '% index def write_py (name, code) : Fpath = Os.path.join (TEMP, '%s.py '% name) with open (Fpath, ' W ', encoding= ' UTF-8 ') as F:f.write (' code wrote to:%s '% Fpath) return Fpath def decode (s): Try:retu RN S.decode (' utf-8 ') except Unicodedecodeerror:return s.decode (' GBK ') def application (environ, start_response) : host = Environ.get (' http_host ') method = Environ.get (' request_method ') path = Environ.get (' path_info ') if me Thod = = ' GET ' and path = = '/': Start_response (' $ OK ', [(' Content-type ', ' text/html ')]) return [b '<title>Learning Python</title>' If method = = ' GET ' and path = = '/env ': Start_response (' $ OK ', [(' Content-type ', ' text/html ')]) L = [ b<title>Env</title>' for K, V in Environ.items (): p = '%s =%s '% (k, str (v))) L.append (P.encode (' Utf-8 ')) L.append (b '') return L if host! = Host or Method! = ' POST ' or path! = '/run ' or not environ.get (' content_type ', '). Lower () . StartsWith (' application/x-www-form-urlencoded '): Start_response (' Bad Request ', [' content-type ', ' application/ JSON ')]) return [b ' {"Error": "Bad_request"} '] s = environ[' wsgi.input '].read (int (environ[' content_length '])) Q s = Parse.parse_qs (S.decode (' utf-8 ')) if not ' code ' in Qs:start_response (' ['] ', [' Content-type ', ' Application/json ')] return [b ' {"Error": "Invalid_params"} '] name = qs[' name '][0] if ' name ' in Qs Else Get_name () Code = qs[' code '][0] headers = [(' Content-type ', ' Application/json ')] origin = Environ.get (' Http_origin ', ') If Origin.find ('. liaoxuefeng.com ') = = -1:start_response (' Bad Request ', [(' Content-type ', ' Application/json ')] return [b ' {"Error": "Invalid_origin"} '] Headers.append ((' Access-control-allow-origin ', origin) Start_respon Se (' OK ', headers) R = dict () Try:fpath = write_py (name, code) print (' Execute:%s '% (EXEC, fpath)) r[' output '] = Decode (Subprocess.check_output ([EXEC, Fpath], stderr=subprocess. STDOUT, timeout=5)) except subprocess. Calledprocesserror as E:r = Dict (error= ' Exception ', Output=decode (e.output)) except subprocess. timeoutexpired as E:r = dict (error= ' timeout ', output= ' execution timeout ') except subprocess. Calledprocesserror as E:r = dict (error= ' error ', output= ' execute error ') print (' Execute done ') return [Json.dumps (R). Encode (' Utf-8 ')] if __name__ = = ' __main__ ': Main ()