1. 如何添加路径

主要有以下两种方式:

1> 临时的

import sys

sys.path.append('C:\Users\Victor\Desktop')

2> 永久的

在Linux的配置文件中如/etc/bashrc添加:

export PYTHONPATH=$PYTHONPATH:/home/oracle

2. 如何将Python程序打包为exe文件

1> 下载py2exe文件并安装

http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/

注意:选择对应的版本和位数,我Windows上的Python版本是64位的,下载32位的py2exe提示找不到对应的python版本

2> 编写测试程序hello.py

  1. print "Hello,world"
  2. raw_input('Press<Enter>')

3> 编写setup.py --名字随意

  1. from distutils.core import setup
  2. import py2exe
  3. setup(console=['hello.py'])

4> 切换到程序当前目录

python setup.py py2exe

最后会在当前目录下生成一个dist文件夹,里面会有一个hello.exe和其它ddl文件,双击hello.exe即可执行。效果如下:

3. 如何捕捉异常

  1. try:
  2. x=input('Enter the first number: ')
  3. y=input('Enter the second number: ')
  4. print x/y
  5. except Exception,e:
  6. print e

4. win32com模块下载地址

http://sourceforge.net/projects/pywin32/files/pywin32/

因为本机是win8系统,用的是python 2.6.6 AMD64,对应的应选择2.6 64位的,刚开始选择的是pywin32-219.win-amd64-py2.6.exe,安装过程中报“ImportError: DLL load failed: 找不到指定的模块”错误,在网上也没有查到问题原因和解决方案,最后试着选择了pywin32-217.win-amd64-py2.6.exe,竟然是OK了,估计还是版本不兼容。

5. 在执行python ez_setup.py install时报以下错误

  1. 使用“”个参数调用“DownloadFile”时发生异常:“在 WebClient 请求期间发生异常。”
  2. 所在位置 行: 字符:
  3. + [System.Net.WebRequest]::DefaultWebProxy.Credentials = [System.Net.CredentialCac ...
  4. + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  5. + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
  6. + FullyQualifiedErrorId : WebException

解决方法:

当前执行路径中有中文,需将该脚本放到英文路径下。

6. PEP8

https://www.python.org/dev/peps/pep-0008/

7. 如何打印I love you

比较low的写法

  1. words = ['I', 'love', 'you']
  2. a = ""
  3. for word in words:
  4. a += word + ' '
  5. print a

高级写法

  1. print ' '.join(words)

8. 把'I , love, , you'输出为['I', 'love', 'you']

比较low的写法

  1. words = 'I , love, , you'
  2. word_list = words.split(',')
  3. result = []
  4. for word in word_list:
  5. if word.strip():
  6. result.append(word.strip())
  7. print result

高级写法

  1. print [word.strip() for word in words.split(',') if word.strip()]

9. 对字典进行排序 

  1. >>> scores={'LiLei': 94, 'lily': 80, 'lucy': 75, 'HanMeimei': 90}
  2. >>> sorted(scores.items(), key=lambda i : i[1], reverse=True)
  3. [('LiLei', 94), ('HanMeimei', 90), ('lily', 80), ('lucy', 75)]

10. 如何只打印字典的key

  1. >>> for k,v in scores.items():
  2. ... print k,v
  3. ...
  4. LiLei 94
  5. lily 80
  6. lucy 75
  7. HanMeimei 90
  8. >>> for item in scores:
  9. ... print item
  10. ...
  11. LiLei
  12. lily
  13. lucy
  14. HanMeimei

11. 如何打印列表的下标

  1. >>> a = [1, 2, 3]
  2. >>> for index,item in enumerate(a):
  3. ... print index,item
  4. ...
  5. 0 1
  6. 1 2
  7. 2 3

12. 如何对列表进行去重操作

  1. >>> a = [1,2,3,1,1,3,2,1,4,5,6]
  2. >>> list(set(a))
  3. [1, 2, 3, 4, 5, 6]

13. 如何对字符串进行反转

  1. >>> word='hello'
  2. >>> word[::-1]
  3. 'olleh'

14. a,b值如何相互替换

a,b = b,a

15. 最大值,最小值,乘积

  1. >>> numbers=[1,2,3,4,5]
  2. >>> max(numbers)
  3. 5
  4. >>> min(numbers)
  5. 1
  6. >>> reduce(lambda x,y:x+y,numbers)
  7. 15
  8. >>> reduce(lambda x,y:x*y,numbers)

16. 如何求1~20每个数的平方

  1. >>> map(lambda x:x*x,xrange(1,21))
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
  3. >>> [x**2 for x in range(1,21)]
  4. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]

17. 判断

if name and langs and info:

等价于 if all((name , langs , info)):

18. 如何安装MySQLdb

pip install MySQL-python

19. PyCharm中设置运行参数

run -> Edit Configuration -> Script parameters

20. 如何将dict转化kwargs

譬如:({'type':'Event'})如何转换为(type='Event')

使用**操作符即可

func(**{'type':'Event'})等价于func(type='Event')

21. Python sort、sorted高级排序技巧 

http://www.jb51.net/article/57678.htm

22. Python如果不指定编码方式,默认为ASCII

23. 文件替换

  1. import fileinput
  2. for line in fileinput.input('C:\Users\Victor\Desktop\passwd',inplace=1):
  3. print line.replace('daemon','Victor')

24. 如何计算一天前0点的timestamp

   第一种方法

  1. import datetime
  2. now = datetime.date.today()
  3. one_day_before = now + datetime.timedelta(days = -1)
  4. done_day_before_string=one_day_before.strftime('%Y-%m-%d')
  5. import time
  6. done_day_before_timestamp= time.mktime(time.strptime(done_day_before_string,'%Y-%m-%d'))
  7. print done_day_before_timestamp

第二种方法

  1. today=time.strptime(time.strftime('%Y-%m-%d'),'%Y-%m-%d')
  2. one_day_before_start=time.mktime(today)-24*60*60

25. Python open文件 读写模式说明

r 打开只读文件,该文件必须存在。

r+ 打开可读写的文件,该文件必须存在。

w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。

w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。

a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。

a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。

上述的形态字符串都可以再加一个b字符,如rb、w+b或ab+等组合,加入b 字符用来告诉函数库打开的文件为二进制文件,而非纯文字文件。不过在POSIX系统,包含Linux都会忽略该字符。

26. 如何将python字典里面的数据按照原始顺序遍历出来

  1. from collections import OrderedDict
  2. dict_1={1:'a',2:'b',4:'d',3:'c'}
  3. print dict_1
  4. dict_2=OrderedDict()
  5. dict_2[1]='a'
  6. dict_2[2]='b'
  7. dict_2[4]='d'
  8. dict_2[3]='c'
  9. print dict_2

27. Python的全局变量

python中,在文件中非函数和类里写的变量都是全局变量,注意if __name__ == '__main__':这个不是函数,所以这个下面写的变量也是全局变量。在函数中,要引用全局变量,如果只是读取,可以直接使用,无需声明global,但是如果要改动,不声明global的变量被认为是局部变量。

所以建议在函数中,先用global声明该变量,再使用,如果要使用同名的局部变量,那是容易让人误解的,那么最好的办法是先定义这个变量并给一个初值(否则初值为全局变量的值),并做注释,表明是故意使用这个变量的。当然这种方法很不好,最好的是全局变量用大写,或g_开头,其余变量小写,或不用g_开头。

28. 在win7下安装pip install MySQL-python时报如下错误:

  1. Command "C:\Python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\administrator\\appdata\\local\\temp\\pip-build-em3ubc\\MySQL-python\\set
  2. up.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\administrator\appdata\
  3. local\temp\pip-ujlaiv-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\administrator\appdata\local\
  4. temp\pip-build-em3ubc\MySQL-python\

解决方法:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python处下载对应版本的MySQL-python包

我是64位操作系统,故下载MySQL_python-1.2.5-cp27-none-win_amd64.whl

29. MySQLdb的相关文章

1> connect方法的参数

http://mysql-python.sourceforge.net/MySQLdb.html

2> 常用API

http://www.runoob.com/python/python-mysql.html

30. 如何生成随机IP

  1. import random,socket,struct
  2. ip = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
  3. print ip

31. Python循环字典的三种方式

  1. tel = {'jack': 4098, 'sape': 4139}
  2. for k,v in enumerate(tel):
  3. print k,v
  4.  
  5. for key in tel.keys():
  6. print key,tel[key]
  7.  
  8. for k,v in tel.iteritems():
  9. print k,v

32. 元祖的初始化

需在初始化元素后面添加个逗号

  1. >>> tuple1=('hello')
  2. >>> print len(tuple1)
  3. 5
  4. >>> tuple2=('hello',)
  5. >>> print len(tuple2)
  6. 1

33. match()和search()的区别?

match()函数只检测RE是不是在string的开始位置匹配, search()会扫描整个string查找匹配,

也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none

34. 判断指定文件是否存在

  1. if os.path.exists(r'/tmp/space_usage_123.txt'):
  2. os.remove(r'/tmp/space_usage_123.txt')

35. logging模块

  1. # coding=utf-8
  2. import logging
  3.  
  4. # 第一步,创建一个logger
  5. logger = logging.getLogger()
  6. logger.setLevel(logging.INFO) # Log等级总开关
  7.  
  8. # 第二步,创建一个handler,用于写入日志文件
  9. logfile = './log/logger.txt'
  10. fh = logging.FileHandler(logfile, mode='w')
  11. fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关
  12.  
  13. # 第三步,再创建一个handler,用于输出到控制台
  14. ch = logging.StreamHandler()
  15. ch.setLevel(logging.WARNING) # 输出到console的log等级的开关
  16.  
  17. # 第四步,定义handler的输出格式
  18. formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
  19. fh.setFormatter(formatter)
  20. ch.setFormatter(formatter)
  21.  
  22. # 第五步,将logger添加到handler里面
  23. logger.addHandler(fh)
  24. logger.addHandler(ch)
  25.  
  26. # 日志
  27. logger.debug('this is a logger debug message')
  28. logger.info('this is a logger info message')
  29. logger.warning('this is a logger warning message')
  30. logger.error('this is a logger error message')
  31. logger.critical('this is a logger critical message')

http://blog.csdn.net/liuchunming033/article/details/39080457

36. 如何引用其它模块

需要在目录中创建一个__init__.py文件,文件内容需引入当前目录中的模块 import t1

  1. [root@node1 python]# ls
  2. t2.py test
  3. [root@node1 python]# ls test/
  4. __init__.py __init__.pyc t1.py t1.pyc
  5. [root@node1 python]# cat t2.py
  6. #/usr/bin/python
  7. from test import t1
  8. t1.hello()
  9. [root@node1 python]# cat test/t1.py
  10. #!/usr/bin/python
  11. def hello():
  12. print 'hello,world'
  13. [root@node1 python]# cat test/__init__.py
  14. import t1
  15. [root@node1 python]# python t2.py
  16. hello,world

37. time模块转换图

格式化当前时间

print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())

38. getpass模块

输入密码时不会明文显示密码

getuser()取自于系统环境变量LOGNAME, USER, LNAME and USERNAME,优先级从左到右。

  1. #!/usr/bin/python
  2. import getpass
  3. password=getpass.getpass()
  4. print(password)
  5. print getpass.getuser()

39. 安装MySQL-python时报错

# pip install MySQL-python

  1. _mysql.c::: error: Python.h: No such file or directory

解决方法:# yum install python-devel

40. 执行python脚本时,报“libmysqlclient.so.18: cannot open shared object file: No such file or directory”错误。

解决方法:# ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib64/libmysqlclient.so.18

# ln -s /usr/local/mysql/lib/libmysqlclient.so.18 /usr/lib/libmysqlclient.so.18

41. 如何检测文件的字符集

pip install chardet

print chardet.detect(each_excel)

42. 安装MySQL-python时报“EnvironmentError: mysql_config not found”

设置环境变量,export PATH=$PATH:/usr/local/mysql/bin

43. No module named 'fcntl'

在windows版本的Python中没有这个模块

44. 脚本手动调用没有问题,但通过crontab调用却报 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

解决方法:

reload(sys)
sys.setdefaultencoding('utf-8')

45. UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

解决方法:

p.agent_info = u' '.join((agent_contact, agent_telno)).encode('utf-8').strip()

46. python安装完毕后,提示找不到ssl模块的解决步骤

http://www.cnblogs.com/yuechaotian/archive/2013/06/03/3115472.html

47. python 2.7源码安装

  1. yum install -y gcc zlib zlib-devel openssl openssl-devel readline-devel sqlite-devel bzip2-devel gdbm-devel libdbi-devel ncurses-libs libffi-devel
  2. wget https://www.python.org/ftp/python/2.7.17/Python-2.7.17.tgz
  3. tar xf Python-2.7.17.tgz
  4. cd Python-2.7.17
  5. ./configure --prefix=/usr/local
  6. vim Modules/Setup
  7. 去掉注释
  8. _ssl _ssl.c \
  9. -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
  10. -L$(SSL)/lib -lssl -lcrypto
  11. make && make install
  12.  
  13. wget https://files.pythonhosted.org/packages/c2/f7/c7b501b783e5a74cf1768bc174ee4fb0a8a6ee5af6afa92274ff964703e0/setuptools-40.8.0.zip
  14. unzip setuptools-40.8..zip
    cd setuptools-40.8.0
    python2. setup.py install
  1. wget https://files.pythonhosted.org/packages/4c/4d/88bc9413da11702cbbace3ccc51350ae099bb351febae8acc85fec34f9af/pip-19.0.2.tar.gz
  2. tar xvf pip-19.0..tar.gz
  3. cd pip-19.0.
  4. python2. setup.py install

48. timestamp to datetime

datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

49.  多个or语句合并

  1. 'Tom' in s or 'Bob' in s
  2.  
  3. any(name in s for name in ('Bob', 'Ed'))

50. 字典排序,基于value值,但value是个列表

  1. sorted(myDict.items(), key=lambda i: i[][], reverse=True)

51. pip安装指定版本的包

  1. pip install robotframework==2.8.

52. 多线程模拟MySQL并发操作

  1. #!/usr/bin/python
  2. import threading,pymysql
  3.  
  4. import time
  5.  
  6. def thread_print(i):
  7. conn = pymysql.connect("192.168.244.10","pt_user","pt_pass")
  8. cursor = conn.cursor()
  9. sql="select sleep(100)"
  10. cursor.execute(sql)
  11. cursor.close()
  12. conn.close()
  13.  
  14. threads = []
  15.  
  16. for i in range(30):
  17. threads.append(threading.Thread(target=thread_print,args=(i,)))
  18.  
  19. for th in threads:
  20. th.start()
  21.  
  22. for th in threads:
  23. th.join()

53. 对IP进行排序

  1. def split_ip(ip):
  2. """Split a IP address given as string into a 4-tuple of integers."""
  3. return tuple(int(part) for part in ip.split('.'))
  4. ips=["192.168.244.10","192.168.12.234","10.10.12.2"]
  5. ips=sorted(ips,key=split_ip)

54. 使用豆瓣源安装python包

  1. pip3. install Django==3.0. -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

55.  ImportError: No module named main

  1. Traceback (most recent call last):
  2. File "/usr/bin/pip", line , in <module>
  3. from pip._internal.cli.main import main
  4. ImportError: No module named main

解决方法:python -m pip install -U pip==8.0.1

56.

Python碎碎念的更多相关文章

  1. Linux碎碎念

    在学习Linux过程中,有许多有用的小技巧.如果放在纸质的笔记本上,平时查阅会相当不方便.现在以一种“碎碎念”的方式,汇集整理在此,目前还不是很多,但随着学习.工作的深入,后续会陆陆续续添加更多的小技 ...

  2. 一些关于Linux入侵应急响应的碎碎念

    近半年做了很多应急响应项目,针对黑客入侵.但疲于没有时间来总结一些常用的东西,寄希望用这篇博文分享一些安全工程师在处理应急响应时常见的套路,因为方面众多可能有些杂碎. 个人认为入侵响应的核心无外乎四个 ...

  3. 一个谷粉和3年的Google Reader重度使用者的碎碎念

    2013-03-14 上午看到Andy Rubin辞去Android业务主管职务.由Chrome及应用高级副总裁继任的新闻,还在想这会给Android带来什么,中午刷微博的时候就挨了当头一棒:Goog ...

  4. Jerry的碎碎念:SAPUI5, Angular, React和Vue

    去年我去一个国内客户现场时,曾经和他们IT部门的一位架构师聊到关于在SAP平台上进行UI应用的二次开发时,UI框架是选用UI5还是Vue这个话题. 我们代表SAP, 向客户推荐使用UI5是基于以下六点 ...

  5. 结对编程ending-我和洧洧的碎碎念

    应该是第一次和队友分工合作去完成一个项目,其中也经历了跳进不少坑又被拉回来的过程,总体来说这对于我俩也的确是值得纪念的一次经历. 我的碎碎念时间…… 对比个人项目和结对编程项目二者需求,前者重在面对不 ...

  6. C语言 · 分分钟的碎碎念

    算法提高 分分钟的碎碎念   时间限制:1.0s   内存限制:256.0MB      问题描述 以前有个孩子,他分分钟都在碎碎念.不过,他的念头之间是有因果关系的.他会在本子里记录每一个念头,并用 ...

  7. 最近关于Qt学习的一点碎碎念

    最近关于Qt学习的一点碎碎念 一直在使用Qt,但是最近对Qt的认识更加多了一些.所以想把自己的一些想法记录下来. Qt最好的学习资料应该是官方的参考文档了.对Qt的每一个类都有非常详细的介绍.我做了一 ...

  8. Java实现 蓝桥杯VIP 算法提高 分分钟的碎碎念

    算法提高 分分钟的碎碎念 时间限制:1.0s 内存限制:256.0MB 问题描述 以前有个孩子,他分分钟都在碎碎念.不过,他的念头之间是有因果关系的.他会在本子里记录每一个念头,并用箭头画出这个念头的 ...

  9. python日常碎碎念

    关于取命令行中参数的方法 1,sys.argv 这个方法自动获取参数,并split.一般情况下第一个元素是程序的名字.即 python script.py arg1 arg2 然后sys.argv返回 ...

随机推荐

  1. Unity3d入门 - 关于unity工具的熟悉

    上周由于工作内容较多,花在unity上学习的时间不多,但总归还是学习了一些东西,内容如下: .1 根据相关的教程在mac上安装了unity. .2 学习了unity的主要的工具分布和对应工具的相关的功 ...

  2. Http状态码之:301、302重定向

    概念 301 Moved Permanently 被请求的资源已永久移动到新位置,并且将来任何对此资源的引用都应该使用本响应返回的若干个URI之一.如果可能,拥有链接编辑功能的客户端应当自动把请求的地 ...

  3. 游戏编程系列[1]--游戏编程中RPC协议的使用[3]--体验

    运行环境,客户端一般编译为.Net 3.5 Unity兼容,服务端因为用了一些库,所以一般为4.0 或往上.同一份代码,建立拥有2个项目.客户端引用: WindNet.Client服务端引用: OpL ...

  4. 调用AJAX做登陆和注册

    先建立一个页面来检测一下我们建立的用户名能不能用,看一下有没有已经存在的用户名吗 可以通过ajax提示一下 $("#uid").blur(function(){ //取用户名 va ...

  5. VisualStudio2013 如何打开之前版本开发的(.vdproj )安装项目

    当你的项目使用早于 visualstudio2013 的版本开发并且使用 Visual Studio Installer 制作安装项目时,在升级至 VS2013 后会发现新安装项目无法打开, VS20 ...

  6. [算法]——归并排序(Merge Sort)

    归并排序(Merge Sort)与快速排序思想类似:将待排序数据分成两部分,继续将两个子部分进行递归的归并排序:然后将已经有序的两个子部分进行合并,最终完成排序.其时间复杂度与快速排序均为O(nlog ...

  7. gRPC源码分析1-SSL/TLS

    引子 前几天看到微信后台团队分享了TLS相关文章,正好gRPC里TLS数据加密是很重要的一块,于是整理出了这篇文章. 在gRPC里,如果仅仅是用来做后端微服务,可以考虑不加密.本文太长,先给个大纲. ...

  8. 解决mysql插入数据时出现Incorrect string value: '\xF0\x9F...' for column 'name' at row 1的异常

    这个问题,原因是UTF-8编码有可能是两个.三个.四个字节.Emoji表情或者某些特殊字符是4个字节,而MySQL的utf8编码最多3个字节,所以数据插不进去. 我的解决方案是这样的 1.在mysql ...

  9. 萌新笔记——vim命令“=”、“d”、“y”的用法(结合光标移动命令,一些场合会非常方便)

    vim有许多命令,网上搜有一堆贴子.文章列举出各种功能的命令. 对于"="."d"."y",我在无意中发现了它们所具有的相同的一些用法,先举 ...

  10. 我想立刻辞职,然后闭关学习编程语言,我给自己3个月时间学习C语言!这样行的通吗

    文章背景,回答提问:我想立刻辞职,然后闭关学习编程语言,我给自己3个月时间学习C语言!这样行的通吗? 我的建议是这样:1. 不要辞职.首先说,你对整个开发没有一个简单的了解,或一个系统的入门学习.换句 ...