Python在線運(yùn)行代碼助手
Python代碼運(yùn)行助手可以讓你在線輸入Python代碼,然后通過本機(jī)運(yùn)行的一個(gè)Python腳本來執(zhí)行代碼。原理如下:
在網(wǎng)頁輸入代碼:

點(diǎn)擊Run按鈕,代碼被發(fā)送到本機(jī)正在運(yùn)行的Python代碼運(yùn)行助手;
Python代碼運(yùn)行助手將代碼保存為臨時(shí)文件,然后調(diào)用Python解釋器執(zhí)行代碼;
網(wǎng)頁顯示代碼執(zhí)行結(jié)果:

下載
點(diǎn)擊右鍵,目標(biāo)另存為:learning.py
備用下載地址:learning.py
完整代碼:
#!/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.' % (v.major, v.minor))
return False
if not check_version():
exit(1)
import os, io, json, subprocess, tempfile
from urllib import parse
from wsgiref.simple_server import make_server
EXEC = sys.executable
PORT = 39093
HOST = 'local.liaoxuefeng.com:%d' % PORT
TEMP = tempfile.mkdtemp(suffix='_py', prefix='learn_python_')
INDEX = 0
def main():
httpd = make_server('127.0.0.1', PORT, application)
print('Ready for Python code on port %d...' % PORT)
httpd.serve_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)
print('Code wrote to: %s' % fpath)
return fpath
def decode(s):
try:
return 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 method == 'GET' and path == '/':
start_response('200 OK', [('Content-Type', 'text/html')])
return [b'<html><head><title>Learning Python</title></head><body><form method="post" action="/run"><textarea name="code" style="width:90%;height: 600px"></textarea><p><button type="submit">Run</button></p></form></body></html>']
if method == 'GET' and path == '/env':
start_response('200 OK', [('Content-Type', 'text/html')])
L = [b'<html><head><title>ENV</title></head><body>']
for k, v in environ.items():
p = '<p>%s = %s' % (k, str(v))
L.append(p.encode('utf-8'))
L.append(b'</html>')
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('400 Bad Request', [('Content-Type', 'application/json')])
return [b'{"error":"bad_request"}']
s = environ['wsgi.input'].read(int(environ['CONTENT_LENGTH']))
qs = parse.parse_qs(s.decode('utf-8'))
if not 'code' in qs:
start_response('400 Bad Request', [('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('400 Bad Request', [('Content-Type', 'application/json')])
return [b'{"error":"invalid_origin"}']
headers.append(('Access-Control-Allow-Origin', origin))
start_response('200 OK', headers)
r = dict()
try:
fpath = write_py(name, code)
print('Execute: %s %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='執(zhí)行超時(shí)')
except subprocess.CalledProcessError as e:
r = dict(error='Error', output='執(zhí)行錯(cuò)誤')
print('Execute done.')
return [json.dumps(r).encode('utf-8')]
if __name__ == '__main__':
main()
運(yùn)行
在存放learning.py的目錄下運(yùn)行命令:
C:\Users\michael\Downloads> python learning.py
如果看到Ready for Python code on port 39093...表示運(yùn)行成功,不要關(guān)閉命令行窗口,最小化放到后臺(tái)運(yùn)行即可:

試試效果
需要支持HTML5的瀏覽器:
IE >= 9
Firefox
Chrome
Sarafi
相關(guān)文章
Python錯(cuò)誤提示:[Errno 24] Too many open files的分析與解決
這篇文章主要給大家介紹了Python中出現(xiàn)錯(cuò)誤提示:[Errno 24] Too many open files的分析與解決,需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02
Python內(nèi)置的字符串處理函數(shù)詳細(xì)整理(覆蓋日常所用)
Python內(nèi)置的字符串處理函數(shù)整理,有字母處理、格式化相關(guān)、字符串搜索相關(guān)、字符串替換相關(guān)等等2014-08-08
python django集成cas驗(yàn)證系統(tǒng)
cas是什么東西就不多說了,簡而言之就是單點(diǎn)登陸系統(tǒng),一處登陸,全網(wǎng)有權(quán)限的系統(tǒng)均可以訪問2014-07-07
Pytorch卷積神經(jīng)網(wǎng)絡(luò)遷移學(xué)習(xí)的目標(biāo)及好處
這篇文章主要為大家介紹了Pytorch卷積神經(jīng)網(wǎng)絡(luò)遷移學(xué)習(xí)的目標(biāo)實(shí)現(xiàn)代碼及好處介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python數(shù)組轉(zhuǎn)換為矩陣的方法實(shí)現(xiàn)
本文主要介紹了python數(shù)組轉(zhuǎn)換為矩陣的方法實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

