溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python如何實現(xiàn)在線編譯器

發(fā)布時間:2021-08-03 12:24:48 來源:億速云 閱讀:300 作者:小新 欄目:開發(fā)技術

這篇文章給大家分享的是有關python如何實現(xiàn)在線編譯器的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

我們先來看一下效果(簡單的寫了一個):

python如何實現(xiàn)在線編譯器

python如何實現(xiàn)在線編譯器

python如何實現(xiàn)在線編譯器

原理:將post請求的代碼數(shù)據(jù)寫入了服務器的一個文件,然后用服務器的python編譯器執(zhí)行返回結果

實現(xiàn)代碼:

#flaskrun.py 
# -*- coding: utf-8 -*- 
# __author__="ZJL"  
from flask import Flask 
from flask import request 
from flask import Response 
import json 
import zxby  
app = Flask(__name__) 
  
def Response_headers(content): 
  resp = Response(content) 
  resp.headers['Access-Control-Allow-Origin'] = '*' 
  return resp 
 
@app.route('/') 
def hello_world(): 
  return Response_headers('hello world!!!') 
 
@app.route('/run', methods=['POST']) 
def run(): 
  if request.method == 'POST' and request.form['code']: 
    code = request.form['code'] 
    print(code) 
    jsondata = zxby.main(code) 
    return Response_headers(str(jsondata)) 
 
@app.errorhandler(403) 
def page_not_found(error): 
  content = json.dumps({"error_code": "403"}) 
  resp = Response_headers(content) 
  return resp 
 
@app.errorhandler(404) 
def page_not_found(error): 
  content = json.dumps({"error_code": "404"}) 
  resp = Response_headers(content) 
  return resp 
 
@app.errorhandler(400) 
def page_not_found(error): 
  content = json.dumps({"error_code": "400"}) 
  resp = Response_headers(content) 
  return resp 
 
@app.errorhandler(405) 
def page_not_found(error): 
  content = json.dumps({"error_code": "405"}) 
  resp = Response_headers(content) 
  return resp 
 
@app.errorhandler(410) 
def page_not_found(error): 
  content = json.dumps({"error_code": "410"}) 
  resp = Response_headers(content) 
  return resp 
 
@app.errorhandler(500) 
def page_not_found(error): 
  content = json.dumps({"error_code": "500"}) 
  resp = Response_headers(content) 
  return resp 
 
if __name__ == '__main__': 
  app.run(debug=True)
#zxby.py 
# -*- coding: utf-8 -*- 
# __author__="ZJL" 
import os, sys, subprocess, tempfile, time  
# 創(chuàng)建臨時文件夾,返回臨時文件夾路徑 
TempFile = tempfile.mkdtemp(suffix='_test', prefix='python_') 
# 文件名 
FileNum = int(time.time() * 1000) 
# python編譯器位置 
EXEC = sys.executable 
  
# 獲取python版本 
def get_version(): 
  v = sys.version_info 
  version = "python %s.%s" % (v.major, v.minor) 
  return version 
  
# 獲得py文件名 
def get_pyname(): 
  global FileNum 
  return 'test_%d' % FileNum 
  
# 接收代碼寫入文件 
def write_file(pyname, code): 
  fpath = os.path.join(TempFile, '%s.py' % pyname) 
  with open(fpath, 'w', encoding='utf-8') as f: 
    f.write(code) 
  print('file path: %s' % fpath) 
  return fpath 
  
# 編碼 
def decode(s): 
  try: 
    return s.decode('utf-8') 
  except UnicodeDecodeError: 
    return s.decode('gbk') 
 
  # 主執(zhí)行函數(shù)  
 
def main(code): 
  r = dict() 
  r["version"] = get_version() 
  pyname = get_pyname() 
  fpath = write_file(pyname, code) 
  try: 
    # subprocess.check_output 是 父進程等待子進程完成,返回子進程向標準輸出的輸出結果 
    # stderr是標準輸出的類型 
    outdata = decode(subprocess.check_output([EXEC, fpath], stderr=subprocess.STDOUT, timeout=5)) 
  except subprocess.CalledProcessError as e: 
    # e.output是錯誤信息標準輸出 
    # 錯誤返回的數(shù)據(jù) 
    r["code"] = 'Error' 
    r["output"] = decode(e.output) 
    return r 
  else: 
    # 成功返回的數(shù)據(jù) 
    r['output'] = outdata 
    r["code"] = "Success" 
    return r 
  finally: 
    # 刪除文件(其實不用刪除臨時文件會自動刪除) 
    try: 
      os.remove(fpath) 
    except Exception as e: 
      exit(1) 
 
if __name__ == '__main__': 
  code = "print(11);print(22)" 
  print(main(code))

運行app.run()方法,通過post提交代碼,就ok了。我們可以對輸出結過做進一步的處理,我這只是為了解一下原理,就沒繼續(xù)了。

感謝各位的閱讀!關于“python如何實現(xiàn)在線編譯器”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI