python使用总结

包管理

使用pip,安装pip

http://www.runoob.com/w3cnote/python-pip-install-usage.html

升级pip  python -m pip install --upgrade pip

安装权限不够的问题

sudo pip install networkx --user

$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py  # 下载安装脚本

$ sudo python get-pip.py    # 运行安装脚本

忽略某个库的版本更新

sudo pip install wechatpy[cryptography] --ignore-installed python-dateutil

python-dateutil在python的/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python目录下,有一个1.5的版本,卸载使用sudo权限都不够

1.python代码库,有很多开源的代码

https://pypi.python.org/pypi?%3Aaction=search&term=win32all&submit=search

如果出现错误:error: Unable to find vcvarsall.bat

则: SET VS90COMNTOOLS=%VS100COMNTOOLS%

2.shell启动python脚本

#!/bin/bash

python recv.py

如果要以后台形式运行,使用nohup python3 run.py >/dev/null 2>&1

3.print占位符

print ('hello %s age %d' %(self.__name, self.__age))

print ('hello age %d ' %(self.__age))

4. 开发工具

安装的时候选择 注册环境变量,这样在控制台命令窗口才能运行.py文件

  最好用的IDE,还是VS, 我使用的是VS2010,所以下载了PTVS 2.1 VS 2010插件,需要安装.net  framework 4.5

  可以像VS那样设置断点,调试,查看变量和堆栈 

使用Eclipse插件时,创建的工程,当前目录是以工程目录.pydevproject,.project开始的

mac下安装VSCode默认使用的是python3,如果要使用python2.7则在setting中添加python2.7的路径: python.pythonPath

验证方法

import platform

print(platform.python_version())

5. input() 和raw_input()

input 会假设用户输入的是合法的表达式(如果要输入字符串,我们得加上引号);而 raw_input 会假设输入的都是原始数据(字符串);

6. 字符串多行显示 首位添加 '''

7.多行字符串一行显示 ,使用\连接

8. 原始字符串

原始字符串不会把反斜杆当作特殊字符使用

path = r"C:\xiaoyu"

print path

取子串

test = text[0 : -1] 会少一位字符,取当前索引之后的整个子串

test = text[index : len(text)]

9. 解决中文错误

SyntaxError: Non-ASCII character '\xd6' in file ChineseTest.py

在文件的第一行加上#coding=gbk

10.判断是否是类的属性

(1)class student:

name = ''

#判断

if  True == hasattr(s, 'age'):

print "has age"

(2)使用dir方法

objlist = dir(k)

if 'att' in objlist:

    #do some thing you need

    print k.att

else:

    #error: has not attribute

    pass

网络异常 取消重新上传

11. 编码解码

encode和decode都是针对unicode进行“编码”和“解码”,所以encode是unicode->str的过程,decode是str->unicode的过程

12列表

list列表的append和extend的区别

mylist = []

youlist = []

test = []

list1 = ['xiaoxiaoyu']

list2 = ['xiaoyu']

list3 = ['xiaoyan']

mylist.extend(list1)

mylist.extend(list2)

mylist.extend(list3)

print mylist

##相当于向一维数组mylist中添加了元素,改变数组的大小

##['xiaoyu', 'xiaoyan', 'youlist']

if mylist[0] == 'xiaoxiaoyu':

del mylist[0]

print mylist

print len(mylist)

youlist.append(list1)

youlist.append(list2)

youlist.append(list3)

print youlist

#youlist本来是一个列表,append使得其每个元素也是个列表,youlist维度加1

#[['youlist'], ['xiaoyu'], ['xiaoyan']]

print len(youlist)

#每个元素都是列表

if youlist[0] == ['xiaoxiaoyu']:

del youlist[0]

print youlist

在函数中清空list使用list[:]

def EmailToDevOnly(to_list):

BeDevOnly = False

#BeDevOnly = True

if True == BeDevOnly:

to_list[:]=[]

to_list.append("123")

13. 字典

默认字典是无序的

使用sorted对字典的key进行排序(返回的是key的有序列表,原字典顺序不变)

排序listKey = sorted(dictDayNum.keys(), reverse=True)

判断一个值是否是键

if mykey in mydict.keys():

value = mydict['china']

print value

else:

print "not in keys"

数值与字符串进行转换

balance = float(rowinfo[1]) - float(rowinfo[2])

rowinfo[5] = str(balance)

14. class类

1.私有成员,构造函数,成员函数

class CTest:

def __init__(self, name, age, addr): #构造函数,python只能有一个构造函数,如果可以使用默认参数实现类多态

self.__name = name;

self.__age = age;

self.addr = addr;

print ('hello %s age %d' %(self.__name, self.__age))

def __del__(self):    #析构函数

print 'bye.....'

def __GetName(self):  #任何一个成员函数,第一个参数都是self

return self.__name;

def PrintAttr(self):

name = self.__GetName()

print ('hello name %s age %d' %(name, self.__age))

__name = 'fish'; #变量名之前加 __ 表示该变量是私有的

__age = 20; #私有的

addr = "shanghai"

def Test():

test = CTest("fish fish", 20, "pu dong ");

#name = test.__GetName(); #报错,私有成员函数不能访问

test.__age = 100;        #这地方,是python的一个缺陷,私有成员在类外还是可以修改

test.PrintAttr();

print(test.__age)

return 0;

15.数据库操作

conn = self.__get_master_connection(db_name)

cursor = conn.cursor()

cursor.execute(sql, params)

遇到问题: TypeError: %d format: a number is required, not str

解决办法: 传给sql的变量写对格式就行了. sql里不需要对对应的变量写%d,只写%s就可以了(所有的都写%s)

压缩zip包

zipFileName = "./sdkfile/" + str(userid) + "apisdk_php.zip" #tmpFileName有文件夹名的话,压缩包中也有文件夹路径,不过想改变文件夹深度的话,可以建立临时文件的方式压缩

f = zipfile.ZipFile(zipFileName, 'w' ,zipfile.ZIP_DEFLATED)

f.write(tmpFileName, "apisdk.php") # "apisdk.php" 压缩包中的新文件

f.close()

16.时间操作

整型时间和字符串时间互相转换

import time

import datetime

def GetTimeByStr(strSrcTime):

dictSrcTime = time.strptime(strSrcTime, "%Y-%m-%d %H:%M:%S")

iTaskTime = time.mktime(dictSrcTime)

return iTaskTime

def GetTimeStrByGivenValue(iSrcTime):

dictSrcTime = time.localtime(iSrcTime)

strTaskTime = time.strftime("%Y-%m-%d %H:%M:%S", dictSrcTime)

return strTaskTime

#获取一天的0份0时0秒时间戳

def GetDayBeginTimeStamp(iSrcTime):

day = datetime.datetime.fromtimestamp(iSrcTime)

dtDayBegin = datetime.datetime(day.year, day.month, day.day, 0, 0, 0)

iBeginTStamp = int(time.mktime(dtDayBegin.timetuple()))

return iBeginTStamp

17.对象的深拷贝和浅拷贝

http://blog.csdn.net/crazyhacking/article/details/30053941

a=b 只是增加一个引用,id(a)和id(b)是指向同一块内存地址,函数的返回值也是一样,比如

def Test():

name = 1

print id(name)

return name

if __name__ == '__main__': 

my = Test()

print id(my) #2个地址是一样的,python使用引用计数来管理内存的释放

copy.copy()只是浅拷贝,子对象还是指向同一块内存地址

copy.deepcopy()实现深拷贝

判断操作系统类型

importplatform

defBeWindowsSystem():

    return'Windows'inplatform.system()

defBeLinuxSystem():

    return'Linux'inplatform.system()

判断进程是否存在

def CheckProcessExist(strProcessName):

if True == BeLinuxSystem():

resLines = os.popen('ps -ef | grep python').readlines()

for line in resLines:

if strProcessName in line:

return True

return False

python发送邮件

# -*- encoding: utf-8 -*-

import os

import sys

import smtplib

from email.mime.text import MIMEText

def send_mail(to_list, sub, content):

mail_host = "mail.xxx.com.cn"

mail_user = "apigateman"

mail_pass = "xxx"

mail_postfix = "xxx.com.cn"

me=mail_user+"<"+mail_user+"@"+mail_postfix+">"

msg = MIMEText(content)

msg['Subject'] = sub

msg['From'] = me

msg['To'] = ";".join(to_list)

try:

s = smtplib.SMTP()

s.connect(mail_host)

s.login(mail_user,mail_pass)

s.sendmail(me, to_list, msg.as_string())

s.close()

print 'success'

#WDLOG.Info([('topic', 'send_mail'), ('from', me), ('mailTo', msg['To']), ('subject', sub)])

return True

except Exception, msg:

#WDLOG.Error([('topic', 'send_mail'), ('exception', str(msg))])

print 'fail.....'

#return False

if __name__ == '__main__':

to_list = []

to_list.append('xxxx@xxx.cn')

sub = 'topic'

content = '1236'

send_mail(to_list, sub, content)

18. map的使用

对可迭代函数'iterable'中的每一个元素应用‘function’方法,将结果作为list返回。

def add(x):

return 100 + x

if __name__ == '__main__':

hh = [1, 2, 3]

print map(add, hh)

19.Basic Authorization

dictHeader = {}

username = 'fish'

password = '111'

base64string = base64.encodestring('%s:%s' % (username, password))[:-1] #注意哦,这里最后会自动添加一个\n

authheader = "Basic %s" % base64string

dictHeader["Authorization"] = authheader

19.assert

age = None #空字符串,0,None,空的list, 字典,tuple都会抛assert

assert age, \

"validators and/or schema required"

性能

1.判断某个元素是否在字典里

第一段:

if(pos in fre_dist.keys()):

newvalue= fre_dist[pos]

第二段:

if(pos in fre_dist):

newValue=fre_dist[pos]

在处理3万条数据时,第二段代码的速度是第一段代码速度的上千倍。

原因是:第一段代码 fre_dist.keys()变成了list,python在检索list的时候是比较慢的,第二段代码 fre_dist是字典,python在检索字典的时候速度是比较快的

python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n),而dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1)

python虚拟目录(virtualenv)

切换到虚拟目录 source  myenv/bin/activate

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 11,131评论 0 10
  • 基础1.r''表示''内部的字符串默认不转义2.'''...'''表示多行内容3. 布尔值:True、False(...
    neo已经被使用阅读 5,703评论 0 5
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 8,127评论 0 9
  • 1. Python的hello-world: print ("Hello, Python!")、 完了 摇就完事儿...
    LunarShade阅读 5,488评论 0 0
  • @贰拾贰画生 感谢简明Python教程 输入输出 输入:raw_input string = raw_input(...
    贰拾贰画生阅读 7,442评论 4 21