Python常用Tips

紅煌流星發表於2018-11-28
  • pip安裝使用-i引數指定源

指定豆瓣源,快如閃電:pip install -i http://pypi.douban.com/simple/

  • 使用sys.modules檢視匯入包的路徑
    sys.modules是一個全域性字典,可以通過它來了解當前環境載入了什麼包,包的路徑
>>> import sys
>>> print(sys.modules.keys()) # 檢視載入的包
dict_keys([`builtins`, `sys`, `_frozen_importlib`, `_imp`, `_warnings`, `_thread`, `_weakref`, `_frozen_importlib_external`, `_io`, `marshal`, `posix`, `zipimport`, `encodings`, `codecs`, `_codecs`, `encodings.aliases`, `encodings.utf_8`, `_signal`, `__main__`, `encodings.latin_1`, `io`, `abc`, `_weakrefset`, `site`, `os`, `errno`, `stat`, `_stat`, `posixpath`, `genericpath`, `os.path`, `_collections_abc`, `_sitebuiltins`, `sysconfig`, `_sysconfigdata_m_linux_x86_64-linux-gnu`, `_bootlocale`, `_locale`, `types`, `functools`, `_functools`, `collections`, `operator`, `_operator`, `keyword`, `heapq`, `_heapq`, `itertools`, `reprlib`, `_collections`, `weakref`, `collections.abc`, `importlib`, `importlib._bootstrap`, `importlib._bootstrap_external`, `warnings`, `importlib.util`, `importlib.abc`, `importlib.machinery`, `contextlib`, `zope`, `sitecustomize`, `apport_python_hook`, `readline`, `atexit`, `rlcompleter`])
>>> print(sys.modules.values())  # 檢視路徑
dict_values([<module `builtins` (built-in)>, <module `sys` (built-in)>, <module `importlib._bootstrap` (frozen)>, <module `_imp` (built-in)>, <module `_warnings` (built-in)>, <module `_thread` (built-in)>, <module `_weakref` (built-in)>, <module `importlib._bootstrap_external` (frozen)>, <module `io` (built-in)>, <module `marshal` (built-in)>, <module `posix` (built-in)>, <module `zipimport` (built-in)>, <module `encodings` from `/usr/lib/python3.6/encodings/__init__.py`>, <module `codecs` from `/usr/lib/python3.6/codecs.py`>, <module `_codecs` (built-in)>, <module `encodings.aliases` from `/usr/lib/python3.6/encodings/aliases.py`>, <module `encodings.utf_8` from `/usr/lib/python3.6/encodings/utf_8.py`>...
>>>import os
>>>print(sys.modules["os"]  # 檢視指定包的路徑
<module `os` from `/usr/lib/python3.6/os.py`>