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)文章
對(duì)python中xlsx,csv以及json文件的相互轉(zhuǎn)化方法詳解
今天小編就為大家分享一篇對(duì)python中xlsx,csv以及json文件的相互轉(zhuǎn)化方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12
使用Python實(shí)現(xiàn)簡(jiǎn)單的爬蟲框架
爬蟲是一種自動(dòng)獲取網(wǎng)頁內(nèi)容的程序,它可以幫助我們從網(wǎng)絡(luò)上快速收集大量信息。下面我們將學(xué)習(xí)如何使用 Python 編寫一個(gè)簡(jiǎn)單的爬蟲框架,感興趣的可以了解一下2023-05-05
python進(jìn)階之多線程對(duì)同一個(gè)全局變量的處理方法
今天小編就為大家分享一篇python進(jìn)階之多線程對(duì)同一個(gè)全局變量的處理方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-11-11
python GUI庫圖形界面開發(fā)之PyQt5下拉列表框控件QComboBox詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5下拉列表框控件QComboBox詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-02-02
python中argparse模塊及action='store_true'詳解
argparse?是一個(gè)用來解析命令行參數(shù)的?Python?庫,它是?Python?標(biāo)準(zhǔn)庫的一部分,這篇文章主要介紹了python中argparse模塊及action=‘store_true‘詳解,需要的朋友可以參考下2023-02-02
python基于itchat實(shí)現(xiàn)微信群消息同步機(jī)器人
本篇文章主要介紹了python基于itchat實(shí)現(xiàn)微信群消息同步機(jī)器人,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02

