Python私房菜----各种偏门和实用用法小计(持续更新中)

本文总结了Python编程中的多个实用技巧,包括globals函数的使用方法、plt绘图颜色设置、conda环境搭建、pyinstaller打包、with语句及faiss库的应用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. globals用法

用法:运行globals()返回的是当前所有的全局变量的字典


In [1]: globals()
Out[1]: 
{'In': ['', u'globals()'],
 'Out': {},
 '_': '',
 '__': '',
 '___': '',
 '__builtin__': <module '__builtin__' (built-in)>,
 '__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__name__': '__main__',
 '_dh': [u'/media/mychocer/project/densepose_original'],
 '_i': u'',
 '_i1': u'globals()',
 '_ih': ['', u'globals()'],
 '_ii': u'',
 '_iii': u'',
 '_oh': {},
 '_sh': <module 'IPython.core.shadowns' from '/media/mychocer/anaconda2/lib/python2.7/site-packages/IPython/core/shadowns.pyc'>,
 'exit': <IPython.core.autocall.ExitAutocall at 0x7fb2fffb1d50>,
 'get_ipython': <bound method TerminalInteractiveShell.get_ipython of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x7fb2fffab090>>,
 'quit': <IPython.core.autocall.ExitAutocall at 0x7fb2fffb1d50>}

In [2]: type(globals())
Out[2]: dict

In [3]: import os

In [4]: globals()
Out[4]: 
{'In': ['', u'globals()', u'type(globals())', u'import os', u'globals()'],
 'Out': {1: {...}, 2: dict},
 '_': dict,
 '_1': {...},
 '_2': dict,
 '__': {...},
 '___': '',
 '__builtin__': <module '__builtin__' (built-in)>,
 '__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__name__': '__main__',
 '__package__': None,
 '_dh': [u'/media/mychocer/project/densepose_original'],
 '_i': u'import os',
 '_i1': u'globals()',
 '_i2': u'type(globals())',
 '_i3': u'import os',
 '_i4': u'globals()',
 '_ih': ['', u'globals()', u'type(globals())', u'import os', u'globals()'],
 '_ii': u'type(globals())',
 '_iii': u'globals()',
 '_oh': {1: {...}, 2: dict},
 '_sh': <module 'IPython.core.shadowns' from '/media/mychocer/anaconda2/lib/python2.7/site-packages/IPython/core/shadowns.pyc'>,
 'exit': <IPython.core.autocall.ExitAutocall at 0x7fb2fffb1d50>,
 'get_ipython': <bound method TerminalInteractiveShell.get_ipython of <IPython.terminal.interactiveshell.TerminalInteractiveShell object at 0x7fb2fffab090>>,
 'os': <module 'os' from '/media/mychocer/anaconda2/lib/python2.7/os.pyc'>,
 'quit': <IPython.core.autocall.ExitAutocall at 0x7fb2fffb1d50>}

2. plt画图

我有一个2维的数组(np.array),我想要实现不同范围的值用不同的颜色表示,如0-0.1红色,0.1-0.2白色等等,

方法:

matplotlib.colors.LinearSegmentedColormap

3. conda 安装 opendr

直接pip安装会出现下面bug

/media/mychocer/.local/lib/python2.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:17:2: warning: #warning "Using deprecated NumPy API, disable it with " "#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
     #warning "Using deprecated NumPy API, disable it with " \
      ^
    In file included from opendr/contexts/ctx_mesa.c:663:0:
    opendr/contexts/OSMesa/include/GL/osmesa.h:258:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
     typedef void (*OSMESAproc)();
     ^
    opendr/contexts/ctx_mesa.c: In function ‘__pyx_pf_6opendr_8contexts_8ctx_mesa_13OsContextBase_150ShaderSource’:
    opendr/contexts/ctx_mesa.c:12788:49: warning: passing argument 3 of ‘glShaderSource’ from incompatible pointer type [-Wincompatible-pointer-types]
       glShaderSource(__pyx_v_shader, __pyx_v_count, (&__pyx_v_s), (&__pyx_v_len));
                                                     ^
    In file included from opendr/contexts/OSMesa/include/GL/gl.h:2085:0,
                     from opendr/contexts/gl_includes.h:10,
                     from opendr/contexts/ctx_mesa.c:662:
    opendr/contexts/OSMesa/include/GL/glext.h:5794:21: note: expected ‘const GLchar ** {aka const char **}’ but argument is of type ‘char **’
     GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar* *string, const GLint *length);
                         ^
    x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wl,-Bsymbolic-functions -Wl,-z,relro -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/opendr/contexts/ctx_mesa.o -Lopendr/contexts/OSMesa/lib -lOSMesa -lGL -lGLU -o build/lib.linux-x86_64-2.7/opendr/contexts/ctx_mesa.so -lstdc++
    /usr/bin/ld: cannot find -lOSMesa
    collect2: error: ld returned 1 exit status
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

解决方法:

先安装osmesa

conda install -c menpo osmesa

再安装opendr

pip install opendr

运行ipython

输入 import opendr.renderer

ImportError: libgcrypt.so.11: cannot open shared object file: No such file or directory

解决方法:

conda install -c clinicalgraphics libgcrypt11

 

4. pytinstaller

一些python脚本的运行,需要依赖于某些环境,但是对于移植来说非常不方便,每次在新的机器运行都必须要安装相应的环境,因此非常不便。

pyinstaller可以把这些依赖库以及脚本集合成一个可执行文件,在新的机器上可直接执行该可执行文件,无法安装依赖。

安装:

pip install pyinstaller

运行:

pyinstaller -F filename

5. conda创建python3的环境

conda create -n NAME python=3.5

6. pip加速安装

使用清华源可以加速安装

pip install easydict -i https://pypi.tuna.tsinghua.edu.cn/simple

7. conda安装opencv2

conda install -c menpo opencv

 8.python __enter__, __exit__ 和with的使用

class A:

    def __enter__(self):

          Implement FuncA

    def __exit__(self, type, value, trace):

          Implement FuncB

可参照https://www.cnblogs.com/lipijin/p/4460487.html

9. 求矩阵的k近邻--faiss

假设gallery是nxq,query是mxq,

index = faiss.IndexFlatL2(q)   # build the index
index.add(gallery)                  # add vectors to the index
D, I = index.search(query, k) # sanity check

详情可见https://github.com/facebookresearch/faiss/wiki/Getting-started

 10. python往文件写入文本时出现下面bug(python3.7)

UnicodeEncodeError: 'charmap' codec can't encode character '\x92' in position 36301: character maps to <undefined>

解决方案:在打开文件的时候,加入"encoding='utf-8' "

with open(fi, 'w', encoding='utf-8') as f:
    f.write(text)

 

 11. python多进程(multiprocessing)抛出错误提示

from multiprocessing import Pool
p = Pool()
p.apply_async(func, args=())

如果func有bug,该代码依然能正常运行,但是无法查看func中的错误信息。

为了显示func 中的错误信息,方便debug,可以进行下列改动

from multiprocessing import Pool
p = Pool()
res = p.apply_async(func, args=())
res.get()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值