How to use code running assistant in python

Python code running assistant is a tool that can run python language on web pages. Because the running environment of python uses DOS in many tutorials, the dark interface looks a bit crude, so this python code running assistant is released as an ide.

In fact, the python code running assistant interface can only be considered as a passing score. If you are looking for an ide, jupyter is recommended. Jupyter is integrated into ANACONDA and can be used as long as anacoda is installed.

1、 To open this running assistant, first download a learning.py. If you can’t find it, you can copy the following code and save it as “learning.py”. Use sublime or notepad++ as the editor.

#! /usr/bin/envpython3
#- *- coding:utf-8-*-
r'''
learning.py
APython3tutorialfromhttp://www.liaoxuefeng.com
Usage:
python3learning.py
'''
importsys
defcheck_version():
v=sys.version_info
ifv.major==3andv.minor =4:
returnTrue
print('Yourcurrentpythonis%d.%d.PleaseusePython3.4.'%(v.major,v.minor))
returnFalse
ifnotcheck_version():exit(1)
importos,io,json,subprocess,tempfile
fromurllibimportparse
fromwsgiref.simple_serverimportmake_server
EXEC=sys.executable
PORT=39093
HOST='local.liaoxuefeng.com:%d'%PORT
TEMP=tempfile.mkdtemp(suffix='_py',prefix='learn_python_')
INDEX=0defmain():
httpd=make_server('127.0.0.1',PORT,application)print('ReadyforPythoncodeonport%d...'%PORT)
httpd.serve_forever()defget_name():
globalINDEX
INDEX=INDEX+1return'test_%d'%INDEX
defwrite_py(name,code):
fpath=os.path.join(TEMP,'%s.py'%name)withopen(fpath,'w',encoding='utf-8')asf:
f.write(code)print('Codewroteto:%s'%fpath)
returnfpath
defdecode(s):try:
returns.decode('utf-8')
exceptUnicodeDecodeError:
returns.decode('gbk')defapplication(environ,start_response):
host=environ.get('HTTP_HOST')
method=environ.get('REQUEST_METHOD')
path=environ.get('PATH_INFO')
ifmethod=='GET'andpath=='/':start_response('200OK',[('Content-Type','text/html')])return[b'<html <head <title LearningPython</title </head <body <formmethod="post"action="/run"<textareaname="code"style="width:90%;height:600px"</textarea <p <buttontype="submit" Run</button 
< /p </form </body </html ']
ifmethod=='GET'andpath=='/env':start_response('200OK',[('Content-Type','text/html')])
L=[b'<html <head <title ENV</title </head <body ']
fork,vinenviron.items():
p='<p %s=%s'%(k,str(v))
L.append(p.encode('utf-8'))
L.append(b'</html ')
returnL
ifhost!=HOSTormethod!='POST'orpath!='/run'ornotenviron.get('CONTENT_TYPE','').lower().startswith('application/x-www-form-urlencoded'):start_response('400BadRequest',[('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'))
ifnot'code'inqs:start_response('400BadRequest',[('Content-Type','application/json')])return[b'{"error":"invalid_params"}']
name=qs['name'][0]if'name'inqselseget_name()
code=qs['code'][0]
headers=[('Content-Type','application/json')]
origin=environ.get('HTTP_ORIGIN','')
iforigin.find('.liaoxuefeng.com')==-1:start_response('400BadRequest',[('Content-Type','application/json')])return[b'{"error":"invalid_origin"}']
headers.append(('Access-Control-Allow-Origin',origin))start_response('200OK',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))
exceptsubprocess.CalledProcessErrorase:
r=dict(error='Exception',output=decode(e.output))
exceptsubprocess.TimeoutExpiredase:
r=dict(error='Timeout',output='Execution timeout')
exceptsubprocess.CalledProcessErrorase:
r=dict(error='Error',output='Execution error')print('Executedone.')return[json.dumps(r).encode('utf-8')]
if__name__=='__main__':main()

2、 Use a notepad to write the following code:

@ echooff
pythonlearning.py
pause

Save as'Run.bat'

3、 Put "run.bat" and "learning.py" in the same directory.

4、 Double-click to run "Run.bat", and then a black dos window will pop up. Do not close this window.

5、 Enter the URL and port corresponding to the URL, and the whole process is complete.

Knowledge point expansion:

Python online code assistant

#! /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 +1return'test_%d'% INDEX
def write_py(name,code):
fpath = os.path.join(TEMP,'%s.py'% name)withopen(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 elseget_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='Execution timeout')
except subprocess.CalledProcessError as e:
r =dict(error='Error',output='Execution error')print('Execute done.')return[json.dumps(r).encode('utf-8')]if __name__ =='__main__':main()

So far this article on how to use the code running assistant for python is introduced. For more related Python code running assistant usage content, please search for the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will support ZaLou more in the future. Cn!

Recommended Posts

How to use code running assistant in python
How to use SQLite in Python
How to use and and or in Python
How to use the round function in python
How to use the zip function in Python
How to use the format function in python
How to set code auto prompt in python
How to comment python code
How to use python tuples
python how to view webpage code
How to use hanlp in ubuntu
How to use python thread pool
How to omit parentheses in Python
How to write classes in python
How to filter numbers in python
How to read Excel in Python
How to view errors in python
How to write return in python
How to understand variables in Python
How to clear variables in python
How to delete cache files in python
How to represent null values in python
How to save text files in python
How to use PYTHON to crawl news articles
How to write win programs in python
How to run id function in python
How to custom catch errors in python
How to write try statement in python
How to define private attributes in Python
How to add custom modules in Python
How to understand global variables in Python
How to view installed modules in python
How to open python in different systems
How to sort a dictionary in python
How to add background music in python
How to represent relative path in python
How to configure TensorFlow use environment in Ubuntu
How to install python in ubuntu server environment
How to simulate gravity in a Python game
How to use dpkg command in Ubuntu system
Teach you how to write games in python
How to delete files and directories in python
How to install the downloaded module in python
How to write a confession program in python
Python how to move the code collectively right
How to perform continuous multiplication calculation in python
How to understand the introduction of packages in Python
How to use Putty to log in to ubuntu installed in VirtualBox
How to understand a list of numbers in python
Example of how to automatically download pictures in python
How to save IE as an attachment in python
How to create a Python virtual environment in Ubuntu 14.04
Python code to find bugs (2)
Python code to find bugs(7)
Python code to find bugs(4)
Python code to find bugs (3)
Python code to find bugs(9)
How to write Pythonic code
How to learn python quickly
How to uninstall python plugin
Python code to find bugs(6)