码迷,mamicode.com
首页 > 编程语言 > 详细

python_study-1

时间:2017-03-10 18:19:03      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:cep   bytes   长度   join   use   wro   utf-8   stdout   on()   

# Author:larlly
‘‘‘
函数
1.在Python交互式命令行下,可以直接输入代码,然后执行,并立刻得到结果。
2.文本编辑器推荐俩款
http://www.sublimetext.com/
https://notepad-plus-plus.org/
3.python运行助手 learning.py
  1 # Author:larlly
  2 # python运行助手
  3 r‘‘‘
  4 learning.py
  5 
  6 A Python 3 tutorial from http://www.liaoxuefeng.com
  7 
  8 Usage:
  9 
 10 python3 learning.py
 11 ‘‘‘
 12 
 13 import sys
 14 
 15 def check_version():
 16     v = sys.version_info
 17     if v.major == 3 and v.minor >= 4:
 18         return True
 19     print(Your current python is %d.%d. Please use Python 3.4. % (v.major, v.minor))
 20     return False
 21 
 22 if not check_version():
 23     exit(1)
 24 
 25 import os, io, json, subprocess, tempfile
 26 from urllib import parse
 27 from wsgiref.simple_server import make_server
 28 
 29 EXEC = sys.executable
 30 PORT = 39093
 31 HOST = local.liaoxuefeng.com:%d % PORT
 32 TEMP = tempfile.mkdtemp(suffix=_py, prefix=learn_python_)
 33 INDEX = 0
 34 
 35 def main():
 36     httpd = make_server(127.0.0.1, PORT, application)
 37     print(Ready for Python code on port %d... % PORT)
 38     httpd.serve_forever()
 39 
 40 def get_name():
 41     global INDEX
 42     INDEX = INDEX + 1
 43     return test_%d % INDEX
 44 
 45 def write_py(name, code):
 46     fpath = os.path.join(TEMP, %s.py % name)
 47     with open(fpath, w, encoding=utf-8) as f:
 48         f.write(code)
 49     print(Code wrote to: %s % fpath)
 50     return fpath
 51 
 52 def decode(s):
 53     try:
 54         return s.decode(utf-8)
 55     except UnicodeDecodeError:
 56         return s.decode(gbk)
 57 
 58 def application(environ, start_response):
 59     host = environ.get(HTTP_HOST)
 60     method = environ.get(REQUEST_METHOD)
 61     path = environ.get(PATH_INFO)
 62     if method == GET and path == /:
 63         start_response(200 OK, [(Content-Type, text/html)])
 64         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>]
 65     if method == GET and path == /env:
 66         start_response(200 OK, [(Content-Type, text/html)])
 67         L = [b<html><head><title>ENV</title></head><body>]
 68         for k, v in environ.items():
 69             p = <p>%s = %s % (k, str(v))
 70             L.append(p.encode(utf-8))
 71         L.append(b</html>)
 72         return L
 73     if host != HOST or method != POST or path != /run or not environ.get(CONTENT_TYPE, ‘‘).lower().startswith(application/x-www-form-urlencoded):
 74         start_response(400 Bad Request, [(Content-Type, application/json)])
 75         return [b{"error":"bad_request"}]
 76     s = environ[wsgi.input].read(int(environ[CONTENT_LENGTH]))
 77     qs = parse.parse_qs(s.decode(utf-8))
 78     if not code in qs:
 79         start_response(400 Bad Request, [(Content-Type, application/json)])
 80         return [b{"error":"invalid_params"}]
 81     name = qs[name][0] if name in qs else get_name()
 82     code = qs[code][0]
 83     headers = [(Content-Type, application/json)]
 84     origin = environ.get(HTTP_ORIGIN, ‘‘)
 85     if origin.find(.liaoxuefeng.com) == -1:
 86         start_response(400 Bad Request, [(Content-Type, application/json)])
 87         return [b{"error":"invalid_origin"}]
 88     headers.append((Access-Control-Allow-Origin, origin))
 89     start_response(200 OK, headers)
 90     r = dict()
 91     try:
 92         fpath = write_py(name, code)
 93         print(Execute: %s %s % (EXEC, fpath))
 94         r[output] = decode(subprocess.check_output([EXEC, fpath], stderr=subprocess.STDOUT, timeout=5))
 95     except subprocess.CalledProcessError as e:
 96         r = dict(error=Exception, output=decode(e.output))
 97     except subprocess.TimeoutExpired as e:
 98         r = dict(error=Timeout, output=执行超时)
 99     except subprocess.CalledProcessError as e:
100         r = dict(error=Error, output=执行错误)
101     print(Execute done.)
102     return [json.dumps(r).encode(utf-8)]
103 
104 if __name__ == __main__:
105     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编码



python_study-1

标签:cep   bytes   长度   join   use   wro   utf-8   stdout   on()   

原文地址:http://www.cnblogs.com/luoliyu/p/6531609.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!