python如何使用代码运行助手


Posted in Python onJuly 03, 2020

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”放到同一目录下。

python如何使用代码运行助手

4、双击运行“运行.bat",之后会弹出黑色的dos窗口,这个窗口不要关闭。

python如何使用代码运行助手

5、输入网址对应的网址和端口,整个过程就完成了。

python如何使用代码运行助手

知识点扩展:

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()

到此这篇关于python如何使用代码运行助手的文章就介绍到这了,更多相关python代码运行助手用法内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python探索之URL Dispatcher实例详解
Oct 28 Python
python+VTK环境搭建及第一个简单程序代码
Dec 13 Python
Python(TensorFlow框架)实现手写数字识别系统的方法
May 29 Python
python使用mitmproxy抓取浏览器请求的方法
Jul 02 Python
python join方法使用详解
Jul 30 Python
对Python中一维向量和一维向量转置相乘的方法详解
Aug 26 Python
python3 中时间戳、时间、日期的转换和加减操作
Jul 14 Python
Python3基于plotly模块保存图片表格
Aug 03 Python
Pycharm学生免费专业版安装教程的方法步骤
Sep 24 Python
python基于exchange函数发送邮件过程详解
Nov 06 Python
Python使用psutil库对系统数据进行采集监控的方法
Aug 23 Python
利用For循环遍历Python字典的三种方法实例
Mar 25 Python
Python 3.10 的首个 PEP 诞生,内置类型 zip() 迎来新特性(推荐)
Jul 03 #Python
python3 简单实现组合设计模式
Jul 02 #Python
Django Session和Cookie分别实现记住用户登录状态操作
Jul 02 #Python
django 装饰器 检测登录状态操作
Jul 02 #Python
详解用Python爬虫获取百度企业信用中企业基本信息
Jul 02 #Python
django 实现后台从富文本提取纯文本
Jul 02 #Python
详解用Python调用百度地图正/逆地理编码API
Jul 02 #Python
You might like
PHP中使用mktime获取时间戳的一个黑色幽默分析
2012/05/31 PHP
基于OpenCart 开发支付宝,财付通,微信支付参数错误问题
2015/10/01 PHP
yii2使用ajax返回json的实现方法
2016/05/14 PHP
用PHP的socket实现客户端到服务端的通信实例详解
2017/02/04 PHP
PHP使用redis消息队列发布微博的方法示例
2017/06/22 PHP
小程序微信支付功能配置方法示例详解【基于thinkPHP】
2019/05/05 PHP
laravel 获取某个查询的查询SQL语句方法
2019/10/12 PHP
Jquery 绑定时间实现代码
2011/05/03 Javascript
js获取URL的参数的方法(getQueryString)示例
2013/09/29 Javascript
bootstrap laydate日期组件使用详解
2017/01/04 Javascript
详解AngularJS1.6版本中ui-router路由中/#!/的解决方法
2017/05/22 Javascript
微信小程序实现皮肤功能(夜间模式)
2017/06/18 Javascript
浅谈通过JS拦截 pushState和replaceState事件
2017/07/21 Javascript
微信小程序实现pdf、word等格式文件上传的方法
2019/09/10 Javascript
js将URL网址转为16进制加密与解密函数
2020/03/04 Javascript
解决vue elementUI 使用el-select 时 change事件的触发问题
2020/11/17 Vue.js
微信小程序学习之自定义滚动弹窗
2020/12/20 Javascript
python 获取本机ip地址的两个方法
2013/02/25 Python
Python实现两款计算器功能示例
2017/12/19 Python
Python中一个for循环循环多个变量的示例
2019/07/16 Python
Python实现的微信红包提醒功能示例
2019/08/22 Python
python框架Django实战商城项目之工程搭建过程图文详解
2020/03/09 Python
Python在字符串中处理html和xml的方法
2020/07/31 Python
Python 代码调试技巧示例代码
2020/08/11 Python
Django rest framework分页接口实现原理解析
2020/08/21 Python
《骆驼和羊》教学反思
2014/02/27 职场文书
关于读书的演讲稿400字
2014/08/27 职场文书
四风自我剖析材料
2014/09/30 职场文书
倡议书格式及范文
2015/04/29 职场文书
大学生创业计划书
2019/06/24 职场文书
2019年入党思想汇报格式与要求
2019/06/25 职场文书
行政后勤人员工作计划应该怎么写?
2019/08/16 职场文书
golang goroutine顺序输出方式
2021/04/29 Golang
Python 读写 Matlab Mat 格式数据的操作
2021/05/19 Python
python爬取豆瓣电影TOP250数据
2021/05/23 Python
一起来学习Python的元组和列表
2022/03/13 Python