python便签小记
使用pth文件扩展python环境
原理上Python运行环境查找库文件本质是对sys.path列表的遍历,所以要导入我们自己的库,可以使用这几种方法:
在文件中使用sys.path.append将库的路径添加进去
调整PYTHONPATH环境变量
将库文件放到sys.path的路径中(比如/usr/local/lib/python2.7/dist-packages)
这些方法都不够方便.最简单的方法是用.pth文件来实现.Python在遍历已知库文件目录的过程中,如果见到一个.pth文件就灰将文件中所记录的路径加到sys.path中,比如在/usr/local/lib/python2.7/dist-packages添加一个.pth文件,文件内容是我们的库路径就可以了.
python常用库
pip 使用 pip list或pip freeze查看所有安装的模块
将需要安装的模块写入一个requirements.txt文件中
使用pip install -r requirements.txt安装所有
gevent 异步框架
twisted 异步框架
APScheduler 定时任务
scrapy 爬虫程序
fabric 自动化部署工具
selenium 结合phantomjs爬取ajax生成的动态网页
flask python的web框架, tornado,django
sqlalchemy 数据库ORM
子线程退出
def _async_raise(self, tid, exctype):
self.__del__()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
if res == 0:
raise ValueError('nonexistent thread id')
elif res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), 0)
raise SystemError('PyThreadState_SetAsyncExc failed')
def terminate(self):
if self.isAlive():
for tid, tobj in threading._active.items():
if tobj is self:
self._async_raise(tid, SystemExit)
子进程可以直接使用terminate函数退出
pycurl安装错误
如果报错 No such file or directory: 'curl-config'
,安装openssl-dev
sudo apt install libcurl4-openssl-dev libssl-dev
由于libcurl的源码编译因素,在安装pycurl可能会导致以下两种错误。
错误1:ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
错误2:ImportError: pycurl: libcurl link-time ssl backend (nss) is different from compile-time ssl backend (openssl)
错误1的解决办法如下:
pip uninstall pycurl -y
export PYCURL_SSL_LIBRARY=openssl
pip install pycurl --no-cache-dir
错误2的解决办法如下:
pip uninstall pycurl -y
export PYCURL_SSL_LIBRARY=nss
pip install pycurl --no-cache-dir