Py. Basic

1.基础语法

1.1 标识符

以单下划线开头 _foo的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用 from xxx import *而导入。
以双下划线开头的__foo代表类的私有成员,以双下划线开头和结尾的__foo__代表 Python 里特殊方法专用的标识,如 __init__()代表类的构造函数。

1.2 多行语句

使用斜杠( \)或者括号将一行的语句分为多行显示

total = item_one + \
        item_two + \
        item_three
days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

1.3 引号

Python 可以使用引号( ’ )、双引号( " )、三引号( ‘’’ 或 “”" ) 来表示字符串,引号的开始与结束必须的相同类型的。
其中三引号可以由多行组成,编写多行文本的快捷语法,常用于文档字符串,在文件的特定地点,被当做注释。

word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""

1.4 注释

python中单行注释采用 # 开头。

# 文件名:test.py

'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

1.5 输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上逗号 ,

# 不换行输出
print x,
print y,

# 不换行输出
print x,y

import sys; sys.stdout.write("x" + '\n')

# 不换行输出 py3
print(a, b, c, end = " ")

1.6 变量

Python 中的变量赋值不需要类型声明。

a = b = c = 1
a, b, c = 1, 2, "john"

1.7 标准数据类型

- Numbers(数字)

他们是不可改变的数据类型,这意味着改变数字数据类型会分配一个新的对象。当你指定一个值时,Number对象就会被创建:
var1 = 1
您也可以使用del语句删除一些对象的引用。
del var_a, var_b
在这里插入图片描述
在这里插入图片描述

- String(字符串)

如果你要实现从字符串中获取一段子字符串的话,可以使用 [头下标:尾下标] 来截取相应的字符串,其中下标是从 0 开始算起,可以是正数或负数,下标可以为空表示取到头或尾。
[头下标:尾下标] 获取的子字符串包含头下标的字符,但不包含尾下标的字符:

str = 'Hello World!'
 
print str           # 输出完整字符串
print str[0]        # 输出字符串中的第一个字符
print str[2:5]      # 输出字符串中第三个至第五个之间的字符串
print str[2:]       # 输出从第三个字符开始的字符串
print str * 2       # 输出字符串两次
print str + "TEST"  # 输出连接的字符串

列表截取可以接收第三个参数,参数作用是截取的步长,以下实例在索引 1 到索引 4 的位置并设置为步长为 2(间隔一个位置)来截取字符串:
在这里插入图片描述

#字符串运算符
str = 'hello champloo'
print str[:6]+"world"

#原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符
print '\n'
print r'\n'

#成员运算符 in 如果字符串中包含给定的字符返回 True
print  "yes" if "h" in str else "no"

#字符串格式化
print "My name is %s and age is %d !" % ('Zara', 21)

#三引号(triple quotes,保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式
cursor.execute('''
CREATE TABLE users (  
login VARCHAR(8), 
uid INTEGER,
prid INTEGER)
''')

'''
decode("gbk")作用为将gbk编码转为unicode编码 
encode("gbk")作用为将unicode编码转为gbk编码
'''

#显示汉字
import json
li = ['是的', '十多万']
print json.dumps(list,encoding='utf-8',ensure_ascii=False)
- List(列表) 有序

列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(即嵌套)。列表用 [] 标识。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
 
print list               # 输出完整列表
print list[0]            # 输出列表的第一个元素
print list[1:3]          # 输出第二个至第三个元素 
print list[2:]           # 输出从第三个开始至列表末尾的所有元素
print tinylist * 2       # 输出列表两次
print list + tinylist    # 打印组合的列表
print (range(10)[::2])   # 打印0-9的偶数
b = [i for i in a]		 # for循环 列表生成

j = nums2.index(i) # 根据值得到index

二维列表

list_2d = [[0 for i in range(5)] for i in range(5)]
list_2d[3].append(4)
print list_2d

enumerate遍历,得到下标和元素

list = ['sd', 444, "山东", 66]
for i, j in enumerate(list):
    print i, j

列表的反转

list = [1, 2, 3, 4, 5]

def reverse(li):
    RevList = []
    for i in range(len(li)):
        RevList.append(li.pop())
    return RevList

list = reverse(list)
print list

列表反转2(swap)

def reverse(li):
    for i in range(0, len(li) / 2):
        li[i], li[-i - 1] = li[-i - 1], li[i]


list = [1, 2, 3, 4, 5]
reverse(list)
print list

range遍历(间隔2)

s = 'kjhgertyubn'
for i in range(0,len(s),2):
    print s[i]

列表的删除

a.remove(2) # 删除值为2 的元素
del a[2] # 删除index为2 的元素

清除空值

a = [1, 2, "", "", 4, 2, 6]
print a
b = [i for i in a if i != '']
print  b

在这里插入图片描述

- Tuple(元组) 只读

元组是另一个数据类型,类似于 List(列表)。
元组用 () 标识。内部元素用逗号隔开。但是元组不能二次赋值,相当于只读列表。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 )
list = [ 'runoob', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000    # 元组中是非法应用
list[2] = 1000     # 列表中是合法应用
- Dictionary(字典)key-value对

列表是有序的对象集合,字典是无序的对象集合。
字典用"{ }"标识。字典由索引(key)和它对应的值value组成。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
 
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
 
 
print dict['one']          # 输出键为'one' 的值
print dict[2]              # 输出键为 2 的值
print tinydict             # 输出完整的字典
print tinydict.keys()      # 输出所有键
print tinydict.values()    # 输出所有值

del dict['Name']  # 删除键是'Name'的条目
dict.clear()      # 清空词典所有条目
del dict          # 删除词典

nums1[i1] = d.get(nums1[i1],-1) # d是字典,查找ke为nums1[i1]的值,若没有,返回-1

1.8 运算符

a**b = a的b次幂
a//b = 商的整数部分 9//2=4 , -9//2=-5

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
 
if ( a in list ):
   print "1 - 变量 a 在给定的列表中 list 中"
else:
   print "1 - 变量 a 不在给定的列表中 list 中"
 
if ( b not in list ):
   print "2 - 变量 b 不在给定的列表中 list 中"
else:
   print "2 - 变量 b 在给定的列表中 list 中"

拷贝/引用

 a=[1,2,3,4,5]
 b=a   #引用
 c=a[:]   #拷贝
>>> id(a)
4410359536
>>> id(b)
4410359536
>>> id(c)
4410358240

2.快捷键

1.shift +enter 自动回车,跳入下一行
2.ctrl+d 快速复制上行的内容至下一行
3.Ctrl+alt+L 调整代码格式
4.双击shift 全局查找

3.语句

if

a = [1,2,3]
b = a if len(a) != 0 else "" #if else 简写
print(b)

while

numbers = [12,37,5,42]
even = []
odd = []
while len(numbers)>0:
    number = numbers.pop()  #列表的操作 pop,append
    if(number%2 == 0):
        even.append(number)
    else:
        odd.append(number)

print even
print odd

while

import random

s = int(random.uniform(1, 10))  #获取随机数(1-9)
m = int(input("输入整数 1-10:")) #输入int
# t = raw_input("输入:")
print m
while m != s:
    if m > s:
        print '大了'
        m = int(input("输入整数:"))
    if m < s:
        print '小了'
        m = int(input("输入整数:"))
    if m == s:
        print 'ok'
        break

de->bin

#!/usr/bin/env python
#coding=utf-8


denum = input("输入十进制数:")
print denum,"(10)",
binnum = []
# 二进制数
while denum > 0:
    binnum.append(str(denum % 2)) # 栈压入
    denum //= 2
print '= ',
while len(binnum)>0:
    import sys
    sys.stdout.write(binnum.pop()) # 无空格输出print ' (2)'
print ' (2)'


#使用自带的bin函数
print bin(334343).replace('0b','')

for

str = 'champloo'
for i in str:
    print '当前字母:', i
fruits = ['banana', 'apple']
for i in fruits:
    print i
for i in range(len(fruits)):
    print fruits[i]

for else

import time
import random

while 1:
    num = int(random.uniform(10, 40))
    for i in range(2, num): n
    if num % i == 0:
        j = num / i
        print '%d 等于 %d * %d' % (num, i, j)
        time.sleep(1)
        break
    else:
        print num, '这是一个质数'
        time.sleep(1)

prime = []
for num in range(2, 100):
    for i in range(2, num):
        if num % i == 0:
            break
    else:
        prime.append(num)

print prime

冒泡排序

list = [9, 6, 0, 1, 6, 2, 7, 4]
for i in range(len(list)):
    for j in range(i + 1):
        if list[i] < list[j]:
            # 实现两个变量的交换
            list[i], list[j] = list[j], list[i]
print list

获得系统时间

import time

# 调用asctime()函数
localtime = time.asctime(time.localtime(time.time()))
print localtime
# 格式化日期
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
# 获取时间戳
print time.time()
#打印日历
import calendar

cal = calendar.month(2019, 1)
print cal
#判断是否为闰年
print calendar.isleap(2018)

import time
#判断是一年中的第几天
print time.strptime('2015-6-7', '%Y-%m-%d')[7]
#格式化打印
print "{}号是{}年第{}天".format(7,2015,d)

import

import os
os.rename()#使用对象来调用函数

from os import *
rename()#直接调用函数
reload(os)#重新装载该模块

4.函数

在这里插入图片描述
不定长函数

def printInfo(str, *strs):
    "打印输入的参数"
    print "打印:"
    print str
    print "------"
    for s in strs:
        print s
    return

匿名函数

sum = lambda a, b: a + b

print sum(10, 20)

全局变量

arg = 0
def set_globle():
    global arg  # 声名了全局变量
    arg = 1
    
set_globle()
print arg

关键字参数

def printme( str ):
   "打印任何传入的字符串"
   print str;
   return;
 
#调用printme函数
printme( str = "My string");

默认参数

def printinfo(name, age=30):
  print name
  print age

printinfo('tom')

return

#test1
def funx(x):
    def funy(y):
        return x*y
    return funy

print funx(7)(8)#返回一个对象
#test2
def funx(x):
    def funy(y):
        return x*y
    return funy()

print funx(7)(8)#返回一个函数返回值 报错

查看函数描述

def printstr(s):
    '''打印字符串
    '''
    print s


print (printstr.__doc__)

将函数作为参数被调用

sum = lambda a, b: a + b

def add(func, a, b):
    return func(func(a, b), func(a, b))

print add(sum, 2, 3)

5.异常处理

# 触发异常
def detectlevel(level):
    if level < 1:
        raise Exception, "Invalid Level"


try:
    detectlevel(0)
except Exception, err:
    print  err
else:
    print 'pass'

6.File I/O

file object = open(file_name [, access_mode][, buffering])

  • file_name:要访问的文件名称的字符串值。
  • access_mode:决定了打开文件的模式:只读,写入,追加等。这个参数是非强制的,默认文件访问模式为只读®。
  • buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

在这里插入图片描述

模式描述
r以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
r+打开一个文件用于读写。文件指针将会放在文件的开头。
w打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
w+打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
a打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
模式rr+ww+aa+
++++
+++++
创建++++
覆盖++
从头开始++++
从尾开始++
文件定位

tell():当前文本中指针的位置
seek(offset [,from])改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。
如果from被设为0: 将文件的开头作为移动字节的参考位置。
如果设为1: 则使用当前的位置作为参考位置。
如果它被设为2: 那么该文件的末尾将作为参考位置。

# 打开文件,写入
f = open("test.txt", "w+")

f.write("hellooo\n444\nchamp")
# 打开文件,读取
f = open("test.txt", "r+")
str = f.read()
print str

#语句结束自动关闭file
with open("renamed.txt", 'r') as f:
    print f.read()
print f.closed #True

# 文件定位
position = f.tell()
print "当前指针位置:", position
# 重置指针
position = f.seek(0, 0)
#f.seek(os.SEEK_SET)
print f.read()

#改名,删除文件
import os

os.rename("a.txt", "b.txt")  # 将a.txt改名为b.txt
os.remove("a.txt")  # 删除a.txt

#创建目录
os.mkdir("test")

#给出当前的目录
print os.getcwd()

#删除目录
os.remove("test")

7.类

class employee:
    """员工类"""
    count = 0  # 类变量

    # 构造函数、初始方法
    def __init__(self, name):
        self.name = name
        employee.count += 1

    def display(self):
        print "total emploee: ", employee.count
        print "name:" + self.name
        print self
        print self.__class__


e = employee("dd")
e.display()
print '-------------'
# 内置类属性
print employee.__dict__  # 类的数据属性
print employee.__doc__  # 文档字符串
print employee.__name__  # 类名
print employee.__module__  # 类定义所在的模块
print employee.__bases__  # 父类

继承


...

class child(parent):
    def __init__(self):
        print '调用子类构造器'

    def childmethod(self):
        print '调用子类方法'


c = child()
c.childmethod()
#父类方法
c.setInfo(66)
c.getInfo()

运算符重载

class Member:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    # 改变str,打印的方式
    def __str__(self):
        return 'Member (%d %d)' % (self.a, self.b)

    # 重载add方法
    def __add__(self, other):
        return Member(self.a + other.a, self.b + other.b)


m1 = Member(2, 10)
m2 = Member(5, -2)

print m1
print m2
print m1 + m2

类属性和方法

class Member:
    __info = '666'


m = Member()
print m
# print m.__info 无法访问
print m._Member__info  # 可以访问私有属性

继承

class a:
    def foo(self):
        print "called A"

class b(a):
    pass

class c(a):
    def foo(self):
        print "called c"

# 加入object,调用c类,否则调用a类
#a是经典类,按照深度优先的方法搜索,路径是b-a-c,c是新式类,按照广度优先的方法去搜索,路径是b-c-a。继承了object类的是新式类。
class d(b, c, object):
    pass

dt = d()
dt.foo()

私有方法的使用

class tmp:
    def __init__(self):
        self.__name = '666'

    def __foo(self):
        print self.__name

    def call_foo(self):
        """利用实例方法来调用私有方法"""
        self.__foo()


t = tmp()
t.call_foo()

8.数据库操作

import MySQLdb
手动创建database,设置用户名和密码

#py2
#import MySQLdb

#py3
import pymysql

__user = 'root'
__password = '123456'
__dbname = 'PYdb'

# 打开数据库连接
db = pymysql.connect("localhost", __user, __password, __dbname, charset='utf8')

# 使用cursor()方法获取操作游标
cursor = db.cursor()

# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()

print ("Database version : %s " % data)

# 如果已存在,删除表
cursor.execute("DROP TABLE IF EXISTS NAME")

# 插入新表name
sql = """CREATE TABLE NAME (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME   CHAR(20),
         AGE INT,
         SEX CHAR(1)
         )"""

cursor.execute(sql)

# sql插入语句
sql_insert = "INSERT INTO NAME(FIRST_NAME,\
                LAST_NAME, AGE, SEX) \
                VALUES ('%s','%s','%s','%s') " % \
             ('Yefan', 'Zhuang', 20, 'M')

try:
    # 执行插入操作
    cursor.execute(sql_insert)
    print "insert success"
    # 向数据库提交
    db.commit()
except:
    # 发生错误时回滚
    print 'error'
    db.rollback()

sql_select = "SELECT * FROM NAME  \
             WHERE AGE = '%s'  \
             AND SEX = '%s'" % \
             (20, 'M')

try:
    cursor.execute(sql_select)
    results = cursor.fetchall()
    for row in results:
        fname = row[0]
        lname = row[1]
        age = row[2]
        sex = row[3]
        # 打印结果
        print "fname=%s, lname=%s, age=%s, sex=%s" % \
              (fname, lname, age, sex)
    print 'success'
    db.commit()

except:
    print "ERROR: fecth error"

# 关闭数据库连接
db.close()

9. Py3

查看安装绝对路径

import sys
>>> sys.path
1.print () 必须带括号
2.Unicode
中国 = 'china'
print(中国)						#china
3.除法,结果保留浮点数
import math

print(1/2)						#0.5
#截取整数部分,像2.7一样计算
print(math.trunc(1 / 2))		#0
4.二进制
print(bin(100))
5.数据类型 (去除long,增加bytes)
b = b'china'
print(type(b))		#<class 'bytes'>
print(b)			#b'china'
s = b.decode()		#china
print(s)

10. 正则表达式

ex1 :span() 在起始位置匹配
print(re.match('www', 'www.baidu.com').span())  
# (0, 3)
ex2:group()
line = 'you are pretty one'
matchObj = re.match('([a-z]+) are (.*?) ([a-z]+)', line)

if matchObj:
    print("groups :", matchObj.groups())    # groups : ('you', 'pretty', 'one')
    print("group 0:", matchObj.group())     # group 0: you are pretty one
    print(matchObj.span(0))                 # (0, 18)
    print("group 1:", matchObj.group(1))    # group 1: you
    print(matchObj.span(1))                 # (0, 3)
    print("group 2:", matchObj.group(2))    # group 2: pretty
    print(matchObj.span(2))                 # (8, 14)
else:
    print("no match!")
ex3:search&match
line3 = 'you are a dog'
print(re.match(r'dog', line3))           # None
print(re.search(r'dog', line3).group())  # dog
ex4:替换
phone = '189-6943-6832 # 这是一个电话'

num = re.sub(r'#.*$', '', phone)    # 删除注释
print(num)          # 189-6943-6832 

num = re.sub(r'[^0-9]', '', phone)  # 删除数字以外的
print(num)          # 18969436832
ex5: 将一个函数作为参数
def double(match):
    num = int(match.group('num'))
    # return '@'
    return str(num * 2)


s = 'asc334VDS6g612'
print(re.sub('(?P<num>\d+)', double, s))    # asc668VDS12g1224
ex6:生成pattern
pattern = re.compile('([a-z]+)', re.I)  # 等于[A-z]
m = pattern.match('Hello , pretty')
print(m.groups())           # ('Hello',)
ex7:findall
pattern = re.compile(r'\d+')  # 查找数字
str = 'one1two23three4FOUR56SIX'
print(pattern.match(str))   # None
print(pattern.search(str))
print(pattern.findall(str))  # 匹配所有,['1', '23', '4', '56']
it = pattern.finditer(str)  # 匹配所有 返回迭代器
for m in it:
    print(m.group())
ex8:split:分割后返回列表
print(re.split('\W+', 'ds,4 r,_44$'))       # ['ds', '4', 'r', '_44', '']
print(re.split('3', 'xxxxxx'))  # 如果找不到匹配的字符串,split不会对其分割,['xxxxxx']
ex9: 修改时间格式
time = '2019-01-29'
print(re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', time))     # 01/29/2019
ex10:捕获并放入组中
pattern = re.compile(r'(?P<test>[a-z]+) ([a-z]+)', re.I)
m = pattern.match('Hello uuc')
print(m.groups())           # ('Hello', 'uuc')
print(m.group('test'))      # Hello
ex11:\b:匹配单词边界
ret = re.findall(r'o\b', 'ollio lode')      # ['o']
ret = re.findall(r'o', 'ollio lode')        # ['o', 'o', 'o']
print(ret)
ex12:小写字母开头的单词
s = 'i Am a gOOD one'
result = re.findall(r'\b[a-z][a-zA-Z]*\b', s)
print(result)                   # ['i', 'a', 'gOOD', 'one']

11. CGI 编程

配置Apache(Mac 自带)
https://www.jianshu.com/p/68b11edc055e
https://blog.csdn.net/wanxue0804/article/details/79434058
(参考)

  1. /Directory 搜索并修改,两处
  2. LoadModule cgi_module libexec/apache2/mod_cgi.so
    去掉此项注释
  3. 修改DocumentRoot 目录到 /Users/champloo/sites(自建)
  4. 去掉 ScriptAliasMatch 注释并修改目录
  5. 去掉 AddHandler 注释并添加 .py
  6. 重启`sudo apachectl restart
  7. 给文件设置权限 $: chmod 755 hello.py
进入工作目录 $cd /etc/apache2  
恢复备份$sudo cp httpd.conf.bak httpd.conf
使用vim编辑 $sudo vim httpd.conf
i 编辑 :wq 保存退出 :q! 不保存退出
1.查看环境变量
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

print("Content-type: text/html")
print('')
print("<meta charset=\"utf-8\">")
print("<h2>环境变量: </h2><br>")
print("<ul>")
for key in os.environ.keys():
    print("<li><span style='color:green'>%30s </span> : %s </li>" % (key, os.environ[key]))
print("</ul>")

2. GET 方法

url实例:将浏览器网址改为:
http://localhost/Py3/hello_get.py?name=百度&url=www.baidu.com
Web_Test.py:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# CGI处理模块
import cgi, cgitb

# 创建 FieldStorage 的实例化
form = cgi.FieldStorage()

# 获取数据
site_name = form.getvalue('name')
site_url  = form.getvalue('url')

print ("Content-type:text/html")
print ('')
print ("<html>")
print ("<head>")
print ("<meta charset=\"utf-8\">")
print ("<title>CGI 测试实例</title>")
print ("</head>")
print ("<body>")
print ("<h2>%s官网:%s</h2>" % (site_name, site_url))
print ("</body>")
print ("</html>")

在这里插入图片描述
通过表单使用get方法向服务器发送数据,提交的服务器脚本文件是Web_Test.py,以下是html代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CGI Test</title>
</head>
<body>
<form action="Web_Test.py" method="get"> //若使用POST方法,将get 改为 post
网址名称:<input type="text" name="name"> <br/>
网址 URL:<input type="text" name="url" />
<input type='submit' value="提交" />
</form>
</body>
</html>
3.CGI component
#!/usr/bin/python
# -*- coding: UTF-8 -*-


# CGI处理模块
import cgi, cgitb

# 创建 FieldStorage 的实例化
form = cgi.FieldStorage()

# 通用
print("Content-type:text/html")
print('')
print("<html>")
print("<head>")
print("<meta charset=\"utf-8\">")
print("<title>CGI 测试</title>")
print("</head>")
print("<body>")

# 接受字段数据 - checkbox
if form.getvalue('google'):
    google_flag = "是"
else:
    google_flag = "否"

if form.getvalue('baidu'):
    baidu_flag = "是"
else:
    baidu_flag = "否"

print("<h2>Checkbox</h2>")
print("<h3>选择百度? %s</h3>" % baidu_flag)
print("<h3>选择谷歌? %s</h3>" % google_flag)
print("<p>---------------------------------</p>")


# 接受字段数据 - radio
if form.getvalue('site'):
    site = form.getvalue('site')
else:
    site = '提交数据为空'
print("<h2>Radio</h2>")
print("<h3>选中的网站是 %s</h3>" % site)
print("<p>---------------------------------</p>")

# 接受字段数据 - textarea
if form.getvalue('textcontent'):
    text_content = form.getvalue('textcontent')
else:
    text_content = '没有内容'
print("<h2>Textarea</h2>")
print("<h3>输入的内容是: %s</h3>" % text_content)
print("<p>---------------------------------</p>")

# 接受字段数据 - dropdown
if form.getvalue('dropdown'):
    dropdown_content = form.getvalue('dropdown')
else:
    text_content = '没有内容'
print("<h2>dropdown</h2>")
print("<h3>输入的内容是: %s</h3>" % dropdown_content)
print("<p>---------------------------------</p>")

print("</body>")
print("</html>")

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CGI Test</title>
</head>
<body>
<!--相同的格式-->
    
<form action="/Py3/component.py" method="POST" target="_blank">
<!--checkbox-->
<h2>Checkbox</h2>
<input type="checkbox" name="baidu" value="on" /> 百度
<input type="checkbox" name="google" value="on" /> Google
<p>--------------------------</p>
<!--Radio-->
<h2>Radio</h2>
<input type="radio" name="site" value="baidu" /> 百度
<input type="radio" name="site" value="google" /> Google
<p>--------------------------</p>
<!--textarea-->
<h2>Textarea</h2>
<textarea name="textcontent" placeholder="在这里输入内容" cols="40" rows="4">
</textarea>
<p>--------------------------</p>
<!--dropdown-->
<h2>Dropdown</h2>
<select name="dropdown">
<option value="Baidu" selected>百度</option>
<option value="Google">Google</option>
</select>
    
<p>--------------------------</p>
<input type='submit' value="提交" />
</form>
</body>
</html>
4.Cookie设置
#!/usr/bin/python
# -*- coding: UTF-8 -*-

#
# 设置cookie
print("Content-type:text/html")
print('Set-Cookie: name="陈";expires=Wed, 28 Aug 2016 18:30:30')
print('')
print("""
<html>
<head>
<meta charset="utf-8">
<title>Cookie 设置</title>
</head>
<body>
<h1>
Cookie sets OK
</h1>
</body>
</html>
""")

5.文件

html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>File test</title>
</head>
<body>
 <form enctype="multipart/form-data" 
                     action="/Py3/save_file.py" method="post">
   <p>选中文件: <input type="file" name="filename" /></p>
   <p><input type="submit" value="上传" /></p>
   </form>
</body>
</html>

py

#!/usr/bin/python
# -*- coding: UTF-8 -*-


import cgi, os
import cgitb;

cgitb.enable()

form = cgi.FieldStorage()

# 获取文件名
fileitem = form['filename']

# 检测文件是否上传
if fileitem.filename:
    # 设置文件路径
    fn = os.path.basename(fileitem.filename.replace("\\", "/"))
    open('/tmp/' + fn, 'wb').write(fileitem.file.read())

    message = '文件 "' + fn + '" 上传成功'

else:
    message = '文件没有上传'

print("""\
Content-Type: text/html\n
<html>
<head>
<meta charset="utf-8">
<title>File 上传</title>
</head>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,))

12.多线程

import time
import threading

def loop1(s1, s2):
    print(s1, s2)
    print("start loop1 at ", time.ctime())
    time.sleep(4)
    print("end loop1 at ", time.ctime())
    
def main():
    print("start at ", time.ctime())
    threading.Thread(target=loop1, args=("sss", "ddd")).start()  # 函数后没有括号
    threading.Thread(target=loop2).start()
    print("all done at", time.ctime())

继承类Thread

import time
import threading


class MyThread(threading.Thread):
    def __init__(self, arg):
        super(MyThread, self).__init__()
        self.arg = arg

    def run(self):
        time.sleep(2)
        print("the args for this is {0}".format(self.arg))


for i in range(5):
    t = MyThread(i)
    t.start()
    t.join()
print("main thread is down")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值