python如何使用代码运行助手
作者:爱喝马黛茶的安东尼 时间:2022-08-27 21:11:19
python代码运行助手是能在网页上运行python语言的工具。因为python的运行环境在很多教程里都是用dos的,黑乎乎的界面看的有点简陋,所以出了这python代码运行助手,作为ide。
实际上,python代码运行助手界面只能算及格分,如果要找ide,推荐使用jupyter。jupyter被集成到ANACONDA里,只要安装了anacoda就能使用了。
1、要打开这运行助手首先要下载一个learning.py,如果找不到可以复制如下代码另存为“learning.py”,编辑器用sublime、或者notepad++。
#!/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='执行超时')
except subprocess.CalledProcessError as e:
r = dict(error='Error', output='执行错误')
print('Execute done.')
return [json.dumps(r).encode('utf-8')]
if __name__ == '__main__':
main()
2、再用一个记事本写如下的代码:
@echo off
python learning.py
pause
另存为‘运行.bat'
3、把“运行.bat”和“learning.py”放到同一目录下。
4、双击运行“运行.bat",之后会弹出黑色的dos窗口,这个窗口不要关闭。
5、输入网址对应的网址和端口,整个过程就完成了。
知识点扩展:
Python在线运行代码助手
#!/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','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','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','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','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='执行超时')
except subprocess.CalledProcessError as e:
r = dict(error='Error',output='执行错误')
print('Execute done.')
return [json.dumps(r).encode('utf-8')]
if __name__ == '__main__':
main()
来源:https://www.py.cn/faq/python/14023.html
标签:python,代码运行
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mysql 5.7.13 安装配置方法图文教程(win10)
2024-01-14 06:51:48
![](https://img.aspxhome.com/file/2023/6/105496_0s.jpg)
CentOS7系统搭建LAMP及更新PHP版本操作详解
2024-05-22 10:07:38
![](https://img.aspxhome.com/file/2023/4/124594_0s.png)
Python中使用ctypes调用C++的方法
2021-09-28 10:36:13
python实现的各种排序算法代码
2022-06-17 05:41:19
python编写微信远程控制电脑的程序
2023-08-15 17:04:38
![](https://img.aspxhome.com/file/2023/1/131161_0s.png)
Django模型中字段属性choice使用说明
2022-06-23 16:28:20
在ASP处理程序时,进度显示
2008-08-04 13:27:00
Javascript 继承机制的实现
2024-04-23 09:15:23
![](https://img.aspxhome.com/file/2023/4/135664_0s.jpg)
教你为SQL Server数据库构造安全门
2009-01-20 11:34:00
HTTP协议详细介绍
2022-08-09 23:52:24
![](https://img.aspxhome.com/file/2023/2/112062_0s.png)
关于浏览器的一些观点
2008-08-06 12:48:00
![](https://img.aspxhome.com/file/UploadPic/20088/6/200886125027461s.gif)
Python3 解释器的实现
2023-08-09 17:08:53
python构建基础的爬虫教学
2023-09-28 04:24:38
![](https://img.aspxhome.com/file/2023/9/100949_0s.png)
go语言区块链学习调用智能合约
2024-04-30 10:01:34
![](https://img.aspxhome.com/file/2023/6/130736_0s.png)
python人工智能tensorflow函数tf.layers.dense使用方法
2022-03-09 21:52:34
使用matplotlib绘制图例标签中带有公式的图
2022-07-19 00:40:48
![](https://img.aspxhome.com/file/2023/4/82954_0s.jpg)
Go语言单例模式详解
2024-01-30 08:42:41
python超详细实现字体反爬流程
2022-08-30 22:39:03
![](https://img.aspxhome.com/file/2023/1/93541_0s.png)
Python通过解析网页实现看报程序的方法
2022-07-16 14:27:12
XHTML代码的基本应用
2007-10-26 12:32:00