# Author:larlly
'''
函数
1.在Python交互式命令行下,可以直接输入代码,然后执行,并立刻得到结果。
2.文本编辑器推荐俩款
http://www.sublimetext.com/
https://notepad-plus-plus.org/
3.python运行助手 learning.py
 # Author:larlly
# python运行助手
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()

    需要支持HTML5的浏览器:
IE >= 9
Firefox
Chrome
Sarafi 输出函数 print()
输入函数 input()
退出函数 exit() 3.x默认支持中文 2.x需要添加 #-*- coding:utf-8 -*-
'''
print('100 + 200 =',100+200 )
print("hello world ","你好,世界")
print(1024 * 768) #python基础 #print absolute value of an integet a = 100
if a>=0:
print(a)
else:
print(-a) #print 俩行\ \本身也需要转义
print('\\\n\\') #转义太多,可以考虑r''
print(r'\\\\t\\') #如果字符串内部有很多换行,用\n写在一行里不好阅读,为了简化,Python允许用'''...'''的格式表示多行内容
print('''line1
... line2
... line3''')
#上面是在交互式命令行内输入,注意在输入多行内容时,提示符由>>>变为...,提示你可以接着上一行输入。如果写成程序,就是: print('''line1
line2
line3''') #多行字符串'''...'''还可以在前面加上r使用 #布尔值可以用and/or/not 对应 与/或/非
print(True)
print(False)
print(True and False)
print(True or False)
print(not True) #在Python中,通常用全部大写的变量名表示常量: #运算符/和//, /计算结果浮点数, //地板除,结果是整数
print(10/3)
print(10//3) #字符编码
# ASCII 一个字节 GB2312 Unicode 俩个字节 GBK GB18030 utf-8 可变长编码 #对于单个字符的编码,Python提供了ord()函数获取字符的整数表示,chr()函数把编码转换为对应的字符 print(ord('A'))
print(ord("中"))
print(chr(123)) #以Unicode表示的str通过encode()方法可以编码为指定的bytes,
name = 'abc'
print(name.encode('ascii'))
name1 = '且听风吟'
print(name1.encode('utf-8')) #我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法:
#name2 = "b'abc'"
#name3 = "b'\xe4\xb8\x94\xe5\x90\xac\xe9\xa3\x8e\xe5\x90\x9f'" 且听风吟的字节
print(b'abc'.decode('ascii'))
print(b'\xe4\xb8\x94\xe5\x90\xac\xe9\xa3\x8e\xe5\x90\x9f'.decode('utf-8')) #计算str长度(即字节数)函数 len()
print(len(b'abc'))
print(len(b'\xe4\xb8\x94\xe5\x90\xac\xe9\xa3\x8e\xe5\x90\x9f'))
print(len("且听分吟".encode('utf-8'))) #可见,1个中文字符经过UTF-8编码后通常会占用3个字节,而1个英文字符只占用1个字节 #py文件中申明了utf-8编码并不意味着你的.py文件就是UTF-8编码的,必须并且要确保文本编辑器正在使用UTF-8 without BOM编码

最新文章

  1. ASP.Net MVC 5 in Xamarin Studio 5.2
  2. 我的angularjs源码学习之旅3——脏检测与数据双向绑定
  3. 【小贴士】探一探javascript中的replace
  4. Atitit prj 项目管理与行政管理(1)------项目环境的概览与建立
  5. 【POJ 1679】The Unique MST(次小生成树)
  6. 70.Android开发知识点总结
  7. UVa 714 Copying Books(二分)
  8. Oracle里SID、SERVICE_NAME
  9. SQL语句中&amp;、单引号等特殊符号的处理
  10. eclipse出现每次修改代码报heap over错误,然后必须重启tomcat问题,修改过程
  11. sqlserver 批量删除存储过程(转)
  12. 数据字典 dba_free_space及相对文件号RELATIVE_FNO 小结
  13. makefile实例(2)-多个文件实例
  14. Oracle EBS-SQL (WIP-7):检查当月任务发放记录.sql
  15. BZOJ1078: [SCOI2008]斜堆
  16. C#如何根据类的名词创建类的实例
  17. Mybatis下的sql注入
  18. matlab练习程序(高斯牛顿法最优化)
  19. CSS选择符-----伪类选择符
  20. 24点小游戏app宣传文案

热门文章

  1. 返回枚举中的desciption
  2. Debian/Ubuntu pip default install to $HOME/.local
  3. 【腾讯云的1001种玩法】几种在腾讯云建立WordPress的方法(Linux)(二)
  4. 机器人学 —— 机器人感知(Location)
  5. Linux系统Vi/Vim编辑器的简单介绍、安装/卸载、常用命令
  6. [转]MapReduce:详解Shuffle过程
  7. jquery面试(2)
  8. IOS系统下虚拟键盘遮挡文本框问题的解决
  9. mousedown、mousemove、mouseup和touchstart、touchmove、touchend
  10. INFO Dispatcher:42 - Unable to find &#39;struts.multipart.saveDir&#39; property setting. Defaulting to javax.servlet.context.tempdir