首页 > 编程语言 >本地线上运行python代码

本地线上运行python代码

时间:2022-10-17 09:01:18浏览次数:49  
标签:code return name get python py environ 线上 本地

http://localhost:39093/
1、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='执行超时')
    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、运行bat文件的代码
@echo off
python learning.py
pause
3、运行.bat文件和learning.py文件放同一目录下

image.png

1、点击运行.bat文件启动环境
2、在浏览器内输入localhost:39093
image.png

标签:code,return,name,get,python,py,environ,线上,本地
From: https://www.cnblogs.com/Sultan-ST/p/16797898.html

相关文章

  • 使用BCP + Polybase 实现本地数据迁移到Azure DB
    使用BCP+Polybase实现本地数据迁移到AzureDB 一、背景最近因为要做一些实验的缘故,需要在AzureDB上准备一些带数据的数据库。AdventureWorks2019和AdventureWor......
  • [oeasy]python0007-调试程序_debug
    ​ 调试程序......
  • 盘点一个Python自动化办公的实战案例
    大家好,我是皮皮。一、前言前几天在Python钻石交流群【Hxy任我肥】问了一个Python自动化办公的问题,提问截图如下:想要的效果是下图这样的:准确来说,这个都不算是问题了,而......
  • python系列13:python中Path常用功能
     1.基本功能 建议使用pathlib模块来处理文件和文件夹,可以跨平台。pathlib提供path对象来操作,包括目录和文件。In[1]:frompathlibimportPathIn[2]:p=Path()In......
  • python学习第三周总结
    文件操作文件的读写模式文件的操作模式文件相关操作文件内光标移动文件内容修改函数前戏函数的语法结构函数的定义和调用函数的分类函数......
  • ROS2基本命令与简单列子(python与C++)
    初次学习ROS2机器操作系统,本博客将简单入门记录于此。 一. ros2安装:sudoapt-getinstallcurl&&curl http://fishros.com/tools/install/ros-foxy|bash二.编......
  • python学习——爬取数据到mysql
    承接上文,上次把数据爬取到了excel中,这次在上次代码的基础上进行修改,将数据直接上传到mysql中#-*-coding:utf-8-*-importrequestsfrombs4importBeautifulSoupim......
  • 65、记录使用科大讯飞的声纹识别从官方的Python Demo转C++ Demo路程
    基本思想:需要将声纹识别的demo集成到项目中,奈何官方只提供了py版本和java版本,需要c++版本,逐开发和记录一下,只是简单复现其py代码一、官方代码的和手册的地址 这里将py代码......
  • 【Python】Centos7安装Python3和pip
    安装Python3#wgethttps://www.python.org/ftp/python/3.6.2/Python-3.6.2.tar.xz#tar-xvJfPython-3.6.2.tar.xz#cdPython-3.6.2#./configure--prefix=/data......
  • python第三周总结
    每周总结文件操作1.文件概念与打开方式1.文件的概念就是操作系统暴露给用户操作硬盘的快捷方式eg:双击一个文件其实是从硬盘将数据加载到内存ctrl......