python便签小记

2018-07-29 19952228 0

使用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安装所有

  1. gevent 异步框架
  2. twisted 异步框架
  3. APScheduler 定时任务
  4. scrapy 爬虫程序
  5. fabric 自动化部署工具
  6. selenium 结合phantomjs爬取ajax生成的动态网页
  7. flask pythonweb框架, tornado,django
  8. sqlalchemy 数据库ORM

子线程退出

  1. def _async_raise(self, tid, exctype):
  2. self.__del__()
  3. res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
  4. if res == 0:
  5. raise ValueError('nonexistent thread id')
  6. elif res > 1:
  7. ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), 0)
  8. raise SystemError('PyThreadState_SetAsyncExc failed')
  9. def terminate(self):
  10. if self.isAlive():
  11. for tid, tobj in threading._active.items():
  12. if tobj is self:
  13. self._async_raise(tid, SystemExit)

子进程可以直接使用terminate函数退出

pycurl安装错误

如果报错 No such file or directory: 'curl-config',安装openssl-dev

  1. 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的解决办法如下:

  1. pip uninstall pycurl -y
  2. export PYCURL_SSL_LIBRARY=openssl
  3. pip install pycurl --no-cache-dir

错误2的解决办法如下:

  1. pip uninstall pycurl -y
  2. export PYCURL_SSL_LIBRARY=nss
  3. pip install pycurl --no-cache-dir