1、任何Python程序都可作为模块导入。
#将print('hello, world')保存到hello.py
>>> import hello
hello, world
2、文件的存储位置很重要(见后),假设文件存储在目录C:\python…中,要告诉解释器去哪里查找这个模块。
>>> import sys
>>> sys.path.append('C:/python')
这是告诉解释器,除了通常将查找的位置外,还应到目录C:/python中查找这个模块。
3、要查明模块包含什么,可以使用函数dir()
>>> dir(copy)
['Error', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_copy_dispatch', '_copy_immutable', '_deepcopy_atomic', '_deepcopy_dict', '_deepcopy_dispatch', '_deepcopy_list', '_deepcopy_method', '_deepcopy_tuple', '_keep_alive', '_reconstruct', 'copy', 'deepcopy', 'dispatch_table', 'error']
#其中有几个是下划线打头的,根据约定,意味着它们并非供外部使用。
#进行简单过滤
>>> [i for i in dir(copy) if not i.startswith('_')]
['Error', 'copy', 'deepcopy', 'dispatch_table', 'error']
变量_all_。
在编写模块时,设置_all_会很好用,因为模块可能包含大量其他程序不需要的变量、函数和类,比较周全的做法就是将它们过滤掉。_all_就是其这个作用。
copy.__all__
['Error', 'copy', 'deepcopy']
使用help获取帮助,标准函数help可以提供通常需要的所有信息。
>>> help(copy.copy)
Help on function copy in module copy:
copy(x)
Shallow copy operation on arbitrary Python objects.#指出只接受一个参数,且执行的是浅复制
See the module's __doc__ string for more info.
>>> help(copy.deepcopy)
Help on function deepcopy in module copy:
deepcopy(x, memo=None, _nil=[]) #help获取更多信息
Deep copy operation on arbitrary Python objects.#同理
See the module's __doc__ string for more info.
实际上,help的信息是从函数copy的文档字符串中提取的
>>> print(copy.copy.__doc__)
Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
>>> print(copy.deepcopy.__doc__)
Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
相比于直接查看文档字符串,使用help的优点是可获取更多的信息,如函数的特征标(即接收的参数,看上例deepcopy)
4、让模块可用
sys.path包含一个目录(表示为字符串)列表,解释器将在这些目录中查找模块。最理性的情况是:sys.path一开始就包含正确的目录(你的模块所在的目录)。
为此有两种方法:将模块放在正确的位置 和 告诉解释器去哪里查找。
第一种方法:
>>> import sys, pprint
>>> pprint.pprint(sys.path)
['E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev',
'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev',
'E:\\pycharm\\venv\\Scripts\\python36.zip',
'E:\\DLLs',
'E:\\lib',
'E:\\python',
'E:\\pycharm\\venv',
'E:\\pycharm\\venv\\lib\\site-packages',
'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg',
'E:\\pycharm\\venv\\lib\\site-packages\\pip-10.0.1-py3.6.egg',
'E:\\pycharm',
'E:/pycharm']
#注:如果打印的数据结构太大,一行容纳不下,可以使用模块pprint的函数pprint。它是一个卓越的打印函数,能更妥善地打印输出。
这里的要点是,每个字符串都表示一个位置,如果要让解释器能够找到模块,可将其放在其中任何一个位置中。但是目录site-packages是最佳选择,因为它就是用来放置模块的。
第二种方法:
将模块放在正确位置可能不是适合的解决方案,因为:
(1)、不希望python解释器的目录充斥着你编写的模块
(2)、没有必要的权限,无法将文件保存到Python解释器的目录中
(3)、想将模块放在其他地方
将模块放在其他地方,就要告诉解释器到哪里查找,而办法之一就是修改sys.path,但这种做法不常见。
标准做法是将模块所在的目录包含在环境变量PYTHONPATH中。
环境变量并不是Python解释器的一部分,而是操作系统的一部分。大致而言,它们类似于Python变量,但在Python解释器外面设置的。
除使用环境变量PYTHONPATH外,还可使用路径配置文件。这些文件的扩展名为.pth,位于一些特殊目录中,包括要添加到sys.path中的目录。
5、包
为组织模块,可将其编组为包。包其实是另一种模块,但它们可包含其他模块。
模块存储在扩展名为.py的文件中,而包则是一个目录。要被Python视为包,目录必须包含文件_init_.py。如果像普通模块一样导入包,文件_init_.py的内容就是包的内容。
要将模块放入包中,只需将模块文件放在包目录中即可。你还可以在包中嵌套其他包。例如,要创建一个名为drawing的包,其中包含模块shapes和colors。
文件/目录 | 描述 |
---|---|
~/python/ | PYTHONPATH目录 |
~/python/drawing/ | 包目录(包drawing) |
~/pyhon/drawing/init.py | 包代码(模块drawing) |
~/python/drawing/colors.py | 模块colors |
~/python/drawing/shapes.py | 模块shapes |
完成这些准备工作后,下面语句都是合法的:
import drawing #导入drawing包
import drawing.colors #导入drawing包中的模块colors
from drawing import shapes #导入模块shapes
5、模块sys
模块sys让你能够访问与Python解释器紧密相关的变量和函数。
函数/变量 | 描述 |
---|---|
argv | 命令行参数,包括脚本名 |
exit([arg]) | 退出当前程序,可通过可选参数指定返回值或错误信息 |
modules | 一个字典,将模块名映射到加载的模块 |
path | 一个列表,包含要在其中查找模块的目录的名称 |
platform | 一个平台标识符,如sunos5 或 win32 |
stdin | 标准输入流———— 一个类似于文件的对象 |
stdout | 标准输出流———— 一个类似于文件的对象 |
stderr | 标准错误流———— 一个类似于文件的对象 |
变量sys.argv包含传递给Python解释器的参数,其中包括脚本名。
函数sys.exit退出当前程序。可向它提供一个整数,指出程序是否成功,这是一种UNIX约定。在大多数情况下,使用该参数的默认值(0,表示成功)即可。也可以向它提供一个字符串,这个字符串将成为错误消息,对用户找出程序终止的原因很有帮助。在这种情况下,程序退出时将显示指定的错误信息以及一个表示失败的编码。
映射sys.modules将模块名映射到模块(仅限于当前已导入的模块)
>>> import sys
>>> sys.argv
['E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevconsole.py', '49313', '49314'] #第一项是脚本名
>>> sys.modules
{'builtins': <module 'builtins' (built-in)>, 'sys': <module 'sys' (built-in)>, '_frozen_importlib': <module 'importlib._bootstrap' (frozen)>, '_imp': <module '_imp' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_thread': <module '_thread' (built-in)>, '_weakref': <module '_weakref' (built-in)>, '_frozen_importlib_external': <module 'importlib._bootstrap_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'nt': <module 'nt' (built-in)>, 'winreg': <module 'winreg' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>, 'encodings': <module 'encodings' from 'E:\\lib\\encodings\\__init__.py'>, 'codecs': <module 'codecs' from 'E:\\lib\\codecs.py'>, '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from 'E:\\lib\\encodings\\aliases.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from 'E:\\lib\\encodings\\utf_8.py'>, '_signal': <module '_signal' (built-in)>, '__main__': <module '__main__' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevconsole.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from 'E:\\lib\\encodings\\latin_1.py'>, 'io': <module 'io' from 'E:\\lib\\io.py'>, 'abc': <module 'abc' from 'E:\\lib\\abc.py'>, '_weakrefset': <module '_weakrefset' from 'E:\\lib\\_weakrefset.py'>, 'site': <module 'site' from 'E:\\lib\\site.py'>, 'os': <module 'os' from 'E:\\lib\\os.py'>, 'errno': <module 'errno' (built-in)>, 'stat': <module 'stat' from 'E:\\lib\\stat.py'>, '_stat': <module '_stat' (built-in)>, 'ntpath': <module 'ntpath' from 'E:\\lib\\ntpath.py'>, 'genericpath': <module 'genericpath' from 'E:\\lib\\genericpath.py'>, 'os.path': <module 'ntpath' from 'E:\\lib\\ntpath.py'>, '_collections_abc': <module '_collections_abc' from 'E:\\lib\\_collections_abc.py'>, '_sitebuiltins': <module '_sitebuiltins' from 'E:\\lib\\_sitebuiltins.py'>, '_bootlocale': <module '_bootlocale' from 'E:\\lib\\_bootlocale.py'>, '_locale': <module '_locale' (built-in)>, 'encodings.gbk': <module 'encodings.gbk' from 'E:\\lib\\encodings\\gbk.py'>, '_codecs_cn': <module '_codecs_cn' (built-in)>, '_multibytecodec': <module '_multibytecodec' (built-in)>, 'types': <module 'types' from 'E:\\lib\\types.py'>, 'functools': <module 'functools' from 'E:\\lib\\functools.py'>, '_functools': <module '_functools' (built-in)>, 'collections': <module 'collections' from 'E:\\lib\\collections\\__init__.py'>, 'operator': <module 'operator' from 'E:\\lib\\operator.py'>, '_operator': <module '_operator' (built-in)>, 'keyword': <module 'keyword' from 'E:\\lib\\keyword.py'>, 'heapq': <module 'heapq' from 'E:\\lib\\heapq.py'>, '_heapq': <module '_heapq' (built-in)>, 'itertools': <module 'itertools' (built-in)>, 'reprlib': <module 'reprlib' from 'E:\\lib\\reprlib.py'>, '_collections': <module '_collections' (built-in)>, 'weakref': <module 'weakref' from 'E:\\lib\\weakref.py'>, 'collections.abc': <module 'collections.abc' from 'E:\\lib\\collections\\abc.py'>, 'importlib': <module 'importlib' from 'E:\\lib\\importlib\\__init__.py'>, 'importlib._bootstrap': <module 'importlib._bootstrap' (frozen)>, 'importlib._bootstrap_external': <module 'importlib._bootstrap_external' (frozen)>, 'warnings': <module 'warnings' from 'E:\\lib\\warnings.py'>, 'importlib.util': <module 'importlib.util' from 'E:\\lib\\importlib\\util.py'>, 'importlib.abc': <module 'importlib.abc' from 'E:\\lib\\importlib\\abc.py'>, 'importlib.machinery': <module 'importlib.machinery' from 'E:\\lib\\importlib\\machinery.py'>, 'contextlib': <module 'contextlib' from 'E:\\lib\\contextlib.py'>, 'mpl_toolkits': <module 'mpl_toolkits' (namespace)>, 'sysconfig': <module 'sysconfig' from 'E:\\lib\\sysconfig.py'>, 'encodings.cp437': <module 'encodings.cp437' from 'E:\\lib\\encodings\\cp437.py'>, '_pydev_imps': <module '_pydev_imps' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_imps\\__init__.py'>, '_pydev_imps._pydev_saved_modules': <module '_pydev_imps._pydev_saved_modules' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_imps\\_pydev_saved_modules.py'>, 'threading': <module 'threading' from 'E:\\lib\\threading.py'>, 'time': <module 'time' (built-in)>, 'traceback': <module 'traceback' from 'E:\\lib\\traceback.py'>, 'linecache': <module 'linecache' from 'E:\\lib\\linecache.py'>, 'tokenize': <module 'tokenize' from 'E:\\lib\\tokenize.py'>, 're': <module 're' from 'E:\\lib\\re.py'>, 'enum': <module 'enum' from 'E:\\lib\\enum.py'>, 'sre_compile': <module 'sre_compile' from 'E:\\lib\\sre_compile.py'>, '_sre': <module '_sre' (built-in)>, 'sre_parse': <module 'sre_parse' from 'E:\\lib\\sre_parse.py'>, 'sre_constants': <module 'sre_constants' from 'E:\\lib\\sre_constants.py'>, 'copyreg': <module 'copyreg' from 'E:\\lib\\copyreg.py'>, 'token': <module 'token' from 'E:\\lib\\token.py'>, 'socket': <module 'socket' from 'E:\\lib\\socket.py'>, '_socket': <module '_socket' from 'E:\\DLLs\\_socket.pyd'>, 'selectors': <module 'selectors' from 'E:\\lib\\selectors.py'>, 'math': <module 'math' (built-in)>, 'select': <module 'select' from 'E:\\DLLs\\select.pyd'>, 'queue': <module 'queue' from 'E:\\lib\\queue.py'>, 'xmlrpc': <module 'xmlrpc' from 'E:\\lib\\xmlrpc\\__init__.py'>, 'xmlrpc.client': <module 'xmlrpc.client' from 'E:\\lib\\xmlrpc\\client.py'>, 'base64': <module 'base64' from 'E:\\lib\\base64.py'>, 'struct': <module 'struct' from 'E:\\lib\\struct.py'>, '_struct': <module '_struct' (built-in)>, 'binascii': <module 'binascii' (built-in)>, 'datetime': <module 'datetime' from 'E:\\lib\\datetime.py'>, '_datetime': <module '_datetime' (built-in)>, 'decimal': <module 'decimal' from 'E:\\lib\\decimal.py'>, 'numbers': <module 'numbers' from 'E:\\lib\\numbers.py'>, '_decimal': <module '_decimal' from 'E:\\DLLs\\_decimal.pyd'>, 'http': <module 'http' from 'E:\\lib\\http\\__init__.py'>, 'http.client': <module 'http.client' from 'E:\\lib\\http\\client.py'>, 'email': <module 'email' from 'E:\\lib\\email\\__init__.py'>, 'email.parser': <module 'email.parser' from 'E:\\lib\\email\\parser.py'>, 'email.feedparser': <module 'email.feedparser' from 'E:\\lib\\email\\feedparser.py'>, 'email.errors': <module 'email.errors' from 'E:\\lib\\email\\errors.py'>, 'email._policybase': <module 'email._policybase' from 'E:\\lib\\email\\_policybase.py'>, 'email.header': <module 'email.header' from 'E:\\lib\\email\\header.py'>, 'email.quoprimime': <module 'email.quoprimime' from 'E:\\lib\\email\\quoprimime.py'>, 'string': <module 'string' from 'E:\\lib\\string.py'>, '_string': <module '_string' (built-in)>, 'email.base64mime': <module 'email.base64mime' from 'E:\\lib\\email\\base64mime.py'>, 'email.charset': <module 'email.charset' from 'E:\\lib\\email\\charset.py'>, 'email.encoders': <module 'email.encoders' from 'E:\\lib\\email\\encoders.py'>, 'quopri': <module 'quopri' from 'E:\\lib\\quopri.py'>, 'email.utils': <module 'email.utils' from 'E:\\lib\\email\\utils.py'>, 'random': <module 'random' from 'E:\\lib\\random.py'>, 'hashlib': <module 'hashlib' from 'E:\\lib\\hashlib.py'>, '_hashlib': <module '_hashlib' from 'E:\\DLLs\\_hashlib.pyd'>, '_blake2': <module '_blake2' (built-in)>, '_sha3': <module '_sha3' (built-in)>, 'bisect': <module 'bisect' from 'E:\\lib\\bisect.py'>, '_bisect': <module '_bisect' (built-in)>, '_random': <module '_random' (built-in)>, 'urllib': <module 'urllib' from 'E:\\lib\\urllib\\__init__.py'>, 'urllib.parse': <module 'urllib.parse' from 'E:\\lib\\urllib\\parse.py'>, 'email._parseaddr': <module 'email._parseaddr' from 'E:\\lib\\email\\_parseaddr.py'>, 'calendar': <module 'calendar' from 'E:\\lib\\calendar.py'>, 'locale': <module 'locale' from 'E:\\lib\\locale.py'>, 'email.message': <module 'email.message' from 'E:\\lib\\email\\message.py'>, 'uu': <module 'uu' from 'E:\\lib\\uu.py'>, 'email._encoded_words': <module 'email._encoded_words' from 'E:\\lib\\email\\_encoded_words.py'>, 'email.iterators': <module 'email.iterators' from 'E:\\lib\\email\\iterators.py'>, 'ssl': <module 'ssl' from 'E:\\lib\\ssl.py'>, 'ipaddress': <module 'ipaddress' from 'E:\\lib\\ipaddress.py'>, 'textwrap': <module 'textwrap' from 'E:\\lib\\textwrap.py'>, '_ssl': <module '_ssl' from 'E:\\DLLs\\_ssl.pyd'>, 'xml': <module 'xml' from 'E:\\lib\\xml\\__init__.py'>, 'xml.parsers': <module 'xml.parsers' from 'E:\\lib\\xml\\parsers\\__init__.py'>, 'xml.parsers.expat': <module 'xml.parsers.expat' from 'E:\\lib\\xml\\parsers\\expat.py'>, 'pyexpat.errors': <module 'pyexpat.errors'>, 'pyexpat.model': <module 'pyexpat.model'>, 'pyexpat': <module 'pyexpat' from 'E:\\DLLs\\pyexpat.pyd'>, 'xml.parsers.expat.model': <module 'pyexpat.model'>, 'xml.parsers.expat.errors': <module 'pyexpat.errors'>, 'gzip': <module 'gzip' from 'E:\\lib\\gzip.py'>, 'zlib': <module 'zlib' (built-in)>, '_compression': <module '_compression' from 'E:\\lib\\_compression.py'>, 'xmlrpc.server': <module 'xmlrpc.server' from 'E:\\lib\\xmlrpc\\server.py'>, 'http.server': <module 'http.server' from 'E:\\lib\\http\\server.py'>, 'html': <module 'html' from 'E:\\lib\\html\\__init__.py'>, 'html.entities': <module 'html.entities' from 'E:\\lib\\html\\entities.py'>, 'mimetypes': <module 'mimetypes' from 'E:\\lib\\mimetypes.py'>, 'posixpath': <module 'posixpath' from 'E:\\lib\\posixpath.py'>, 'shutil': <module 'shutil' from 'E:\\lib\\shutil.py'>, 'fnmatch': <module 'fnmatch' from 'E:\\lib\\fnmatch.py'>, 'bz2': <module 'bz2' from 'E:\\lib\\bz2.py'>, '_bz2': <module '_bz2' from 'E:\\DLLs\\_bz2.pyd'>, 'lzma': <module 'lzma' from 'E:\\lib\\lzma.py'>, '_lzma': <module '_lzma' from 'E:\\DLLs\\_lzma.pyd'>, 'socketserver': <module 'socketserver' from 'E:\\lib\\socketserver.py'>, 'copy': <module 'copy' from 'E:\\lib\\copy.py'>, 'argparse': <module 'argparse' from 'E:\\lib\\argparse.py'>, 'gettext': <module 'gettext' from 'E:\\lib\\gettext.py'>, 'pydoc': <module 'pydoc' from 'E:\\lib\\pydoc.py'>, 'inspect': <module 'inspect' from 'E:\\lib\\inspect.py'>, 'ast': <module 'ast' from 'E:\\lib\\ast.py'>, '_ast': <module '_ast' (built-in)>, 'dis': <module 'dis' from 'E:\\lib\\dis.py'>, 'opcode': <module 'opcode' from 'E:\\lib\\opcode.py'>, '_opcode': <module '_opcode' (built-in)>, 'pkgutil': <module 'pkgutil' from 'E:\\lib\\pkgutil.py'>, 'platform': <module 'platform' from 'E:\\lib\\platform.py'>, 'subprocess': <module 'subprocess' from 'E:\\lib\\subprocess.py'>, 'signal': <module 'signal' from 'E:\\lib\\signal.py'>, 'msvcrt': <module 'msvcrt' (built-in)>, '_winapi': <module '_winapi' (built-in)>, 'code': <module 'code' from 'E:\\lib\\code.py'>, 'codeop': <module 'codeop' from 'E:\\lib\\codeop.py'>, '__future__': <module '__future__' from 'E:\\lib\\__future__.py'>, '_pydevd_bundle': <module '_pydevd_bundle' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\__init__.py'>, '_pydevd_bundle.pydevd_constants': <module '_pydevd_bundle.pydevd_constants' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_constants.py'>, '_pydevd_bundle.pydevd_vm_type': <module '_pydevd_bundle.pydevd_vm_type' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_vm_type.py'>, '_pydev_bundle': <module '_pydev_bundle' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\__init__.py'>, '_pydev_bundle.fix_getpass': <module '_pydev_bundle.fix_getpass' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\fix_getpass.py'>, 'getpass': <module 'getpass' from 'E:\\lib\\getpass.py'>, '_pydevd_bundle.pydevd_vars': <module '_pydevd_bundle.pydevd_vars' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_vars.py'>, 'pickle': <module 'pickle' from 'E:\\lib\\pickle.py'>, '_compat_pickle': <module '_compat_pickle' from 'E:\\lib\\_compat_pickle.py'>, '_pickle': <module '_pickle' (built-in)>, '_pydevd_bundle.pydevd_custom_frames': <module '_pydevd_bundle.pydevd_custom_frames' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_custom_frames.py'>, 'pydevd_file_utils': <module 'pydevd_file_utils' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevd_file_utils.py'>, '_pydev_bundle._pydev_filesystem_encoding': <module '_pydev_bundle._pydev_filesystem_encoding' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\_pydev_filesystem_encoding.py'>, 'json': <module 'json' from 'E:\\lib\\json\\__init__.py'>, 'json.decoder': <module 'json.decoder' from 'E:\\lib\\json\\decoder.py'>, 'json.scanner': <module 'json.scanner' from 'E:\\lib\\json\\scanner.py'>, '_json': <module '_json' (built-in)>, 'json.encoder': <module 'json.encoder' from 'E:\\lib\\json\\encoder.py'>, 'ctypes': <module 'ctypes' from 'E:\\lib\\ctypes\\__init__.py'>, '_ctypes': <module '_ctypes' from 'E:\\DLLs\\_ctypes.pyd'>, 'ctypes._endian': <module 'ctypes._endian' from 'E:\\lib\\ctypes\\_endian.py'>, '_pydevd_bundle.pydevd_xml': <module '_pydevd_bundle.pydevd_xml' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_xml.py'>, '_pydev_bundle.pydev_log': <module '_pydev_bundle.pydev_log' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_log.py'>, '_pydevd_bundle.pydevd_extension_utils': <module '_pydevd_bundle.pydevd_extension_utils' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_extension_utils.py'>, 'pydevd_plugins': <module 'pydevd_plugins' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevd_plugins\\__init__.py'>, 'pkg_resources': <module 'pkg_resources' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\__init__.py'>, 'zipfile': <module 'zipfile' from 'E:\\lib\\zipfile.py'>, 'plistlib': <module 'plistlib' from 'E:\\lib\\plistlib.py'>, 'tempfile': <module 'tempfile' from 'E:\\lib\\tempfile.py'>, 'pkg_resources.extern': <module 'pkg_resources.extern' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\extern\\__init__.py'>, 'pkg_resources._vendor': <module 'pkg_resources._vendor' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\__init__.py'>, 'pkg_resources.extern.six': <module 'pkg_resources._vendor.six' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\six.py'>, 'pkg_resources._vendor.six': <module 'pkg_resources._vendor.six' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\six.py'>, 'pkg_resources.extern.six.moves': <module 'pkg_resources._vendor.six.moves' (object at 0x00000000036CFB38>)>, 'pkg_resources._vendor.six.moves': <module 'pkg_resources._vendor.six.moves' (object at 0x00000000036CFB38>)>, 'pkg_resources.py31compat': <module 'pkg_resources.py31compat' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\py31compat.py'>, 'pkg_resources.extern.appdirs': <module 'pkg_resources._vendor.appdirs' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\appdirs.py'>, 'pkg_resources._vendor.packaging.__about__': <module 'pkg_resources._vendor.packaging.__about__' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\__about__.py'>, 'pkg_resources.extern.packaging': <module 'pkg_resources._vendor.packaging' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\__init__.py'>, 'pkg_resources.extern.packaging.version': <module 'pkg_resources.extern.packaging.version' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\version.py'>, 'pkg_resources.extern.packaging._structures': <module 'pkg_resources.extern.packaging._structures' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\_structures.py'>, 'pkg_resources.extern.packaging.specifiers': <module 'pkg_resources.extern.packaging.specifiers' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\specifiers.py'>, 'pkg_resources.extern.packaging._compat': <module 'pkg_resources.extern.packaging._compat' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\_compat.py'>, 'pkg_resources.extern.packaging.requirements': <module 'pkg_resources.extern.packaging.requirements' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\requirements.py'>, 'pprint': <module 'pprint' from 'E:\\lib\\pprint.py'>, 'pkg_resources.extern.pyparsing': <module 'pkg_resources._vendor.pyparsing' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\pyparsing.py'>, 'pkg_resources.extern.six.moves.urllib': <module 'pkg_resources._vendor.six.moves.urllib' (object at 0x00000000036CFB38>)>, 'pkg_resources.extern.packaging.markers': <module 'pkg_resources.extern.packaging.markers' from 'E:\\pycharm\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.6.egg\\pkg_resources\\_vendor\\packaging\\markers.py'>, 'pydevd_plugins.extensions': <module 'pydevd_plugins.extensions' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevd_plugins\\extensions\\__init__.py'>, '_pydevd_bundle.pydevd_resolver': <module '_pydevd_bundle.pydevd_resolver' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_resolver.py'>, '_pydev_bundle.pydev_imports': <module '_pydev_bundle.pydev_imports' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_imports.py'>, '_pydev_imps._pydev_execfile': <module '_pydev_imps._pydev_execfile' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_imps\\_pydev_execfile.py'>, '_pydevd_bundle.pydevd_exec2': <module '_pydevd_bundle.pydevd_exec2' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_exec2.py'>, '_pydevd_bundle.pydevd_extension_api': <module '_pydevd_bundle.pydevd_extension_api' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_extension_api.py'>, 'xml.sax': <module 'xml.sax' from 'E:\\lib\\xml\\sax\\__init__.py'>, 'xml.sax.xmlreader': <module 'xml.sax.xmlreader' from 'E:\\lib\\xml\\sax\\xmlreader.py'>, 'xml.sax.handler': <module 'xml.sax.handler' from 'E:\\lib\\xml\\sax\\handler.py'>, 'xml.sax._exceptions': <module 'xml.sax._exceptions' from 'E:\\lib\\xml\\sax\\_exceptions.py'>, 'xml.sax.saxutils': <module 'xml.sax.saxutils' from 'E:\\lib\\xml\\sax\\saxutils.py'>, 'urllib.request': <module 'urllib.request' from 'E:\\lib\\urllib\\request.py'>, 'urllib.error': <module 'urllib.error' from 'E:\\lib\\urllib\\error.py'>, 'urllib.response': <module 'urllib.response' from 'E:\\lib\\urllib\\response.py'>, 'nturl2path': <module 'nturl2path' from 'E:\\lib\\nturl2path.py'>, '_pydevd_bundle.pydevd_save_locals': <module '_pydevd_bundle.pydevd_save_locals' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_save_locals.py'>, '_pydevd_bundle.pydevd_utils': <module '_pydevd_bundle.pydevd_utils' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_utils.py'>, '_pydev_bundle.pydev_console_utils': <module '_pydev_bundle.pydev_console_utils' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_console_utils.py'>, '_pydev_bundle._pydev_calltip_util': <module '_pydev_bundle._pydev_calltip_util' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\_pydev_calltip_util.py'>, '_pydev_bundle._pydev_imports_tipper': <module '_pydev_bundle._pydev_imports_tipper' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\_pydev_imports_tipper.py'>, '_pydev_bundle._pydev_tipper_common': <module '_pydev_bundle._pydev_tipper_common' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\_pydev_tipper_common.py'>, '_pydev_bundle.pydev_umd': <module '_pydev_bundle.pydev_umd' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_umd.py'>, 'pydevconsole': <module 'pydevconsole' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevconsole.py'>, '_pydev_bundle.pydev_localhost': <module '_pydev_bundle.pydev_localhost' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_localhost.py'>, 'encodings.idna': <module 'encodings.idna' from 'E:\\lib\\encodings\\idna.py'>, 'stringprep': <module 'stringprep' from 'E:\\lib\\stringprep.py'>, 'unicodedata': <module 'unicodedata' from 'E:\\DLLs\\unicodedata.pyd'>, 'pydev_ipython': <module 'pydev_ipython' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydev_ipython\\__init__.py'>, 'pydev_ipython.matplotlibtools': <module 'pydev_ipython.matplotlibtools' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydev_ipython\\matplotlibtools.py'>, 'pydev_ipython.inputhook': <module 'pydev_ipython.inputhook' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydev_ipython\\inputhook.py'>, '_pydev_bundle.pydev_import_hook': <module '_pydev_bundle.pydev_import_hook' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_import_hook.py'>, '_pydev_bundle.pydev_import_hook.import_hook': <module '_pydev_bundle.pydev_import_hook.import_hook'>, 'pydevd_plugins.extensions.types': <module 'pydevd_plugins.extensions.types' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevd_plugins\\extensions\\types\\__init__.py'>, 'pydevd_plugins.extensions.types.pydevd_plugin_numpy_types': <module 'pydevd_plugins.extensions.types.pydevd_plugin_numpy_types' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevd_plugins\\extensions\\types\\pydevd_plugin_numpy_types.py'>, 'pydevd_plugins.extensions.types.pydevd_helpers': <module 'pydevd_plugins.extensions.types.pydevd_helpers' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevd_plugins\\extensions\\types\\pydevd_helpers.py'>, 'pydevd_plugins.extensions.types.pydevd_plugins_django_form_str': <module 'pydevd_plugins.extensions.types.pydevd_plugins_django_form_str' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\pydevd_plugins\\extensions\\types\\pydevd_plugins_django_form_str.py'>, '_pydevd_bundle.pydevd_comm': <module '_pydevd_bundle.pydevd_comm' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_comm.py'>, '_pydevd_bundle.pydevd_tracing': <module '_pydevd_bundle.pydevd_tracing' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_tracing.py'>, '_pydev_bundle._pydev_completer': <module '_pydev_bundle._pydev_completer' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\_pydev_completer.py'>, '_pydevd_bundle.pydevd_console': <module '_pydevd_bundle.pydevd_console' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_console.py'>, '_pydev_bundle.pydev_override': <module '_pydev_bundle.pydev_override' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_override.py'>, '_pydevd_bundle.pydevd_io': <module '_pydevd_bundle.pydevd_io' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydevd_bundle\\pydevd_io.py'>, '_pydev_bundle.pydev_monkey': <module '_pydev_bundle.pydev_monkey' from 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev\\_pydev_bundle\\pydev_monkey.py'>, 'shelve': <module 'shelve' from 'E:\\lib\\shelve.py'>, 'dbm': <module 'dbm' from 'E:\\lib\\dbm\\__init__.py'>, 'dbm.dumb': <module 'dbm.dumb' from 'E:\\lib\\dbm\\dumb.py'>, 'hello3': <module 'hello3' from 'E:\\pycharm\\venv\\lib\\site-packages\\hello3.py'>}
>>> sys.platform
'win32'
>>> sys.stdin
<_pydev_bundle.pydev_console_utils.StdIn object at 0x00000000039DBCF8>
>>> sys.stdout
<_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>
>>> sys.stderr
<_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>
>>> sys.exit()
Process finished with exit code 0
pass
6、模块os
该模块让你能够访问多个操作系统服务。
模块os中一些重要的函数和变量
函数/变量 | 描述 |
---|---|
environ | 包含环境变量的映射 |
system(command) | 在子shell中执行操作系统命令 |
sep | 路径中使用的分隔符 |
pathsep | 分隔不同路径的分隔符 |
linesep | 行分隔符(’\n’、’\r’、’\r\n’) |
urandom(n) | 返回n个字节的强加密随机数据 |
除此之外,os及其子模块os.path还包含多个查看、创建和删除目录及文件的函数,以及一些操作路径的函数(例如,os.path.split 和 os.path.join 让你在大多数情况下都可以忽略os.pathsep)。
>>> import os
>>> os.environ
environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\4823\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'YHSC18', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'FP_NO_HOST_CHECK': 'NO', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\4823', 'IPYTHONENABLE': 'True', 'LOCALAPPDATA': 'C:\\Users\\4823\\AppData\\Local', 'LOGONSERVER': '\\\\DMSRV', 'NUMBER_OF_PROCESSORS': '4', 'OS': 'Windows_NT', 'PATH': 'E:\\Scripts\\;E:\\;E:\\python\\Scripts\\;E:\\python\\;D:\\Conductor\\System;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;E:\\Anaconda3;E:\\Anaconda3\\Library\\mingw-w64\\bin;E:\\Anaconda3\\Library\\usr\\bin;E:\\Anaconda3\\Library\\bin;E:\\Anaconda3\\Scripts;E:\\python\\Scripts\\;E:\\python\\', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 58 Stepping 9, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '3a09', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PROMPT': '(venv) $P$G', 'PSMODULEPATH': 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM_HOSTED': '1', 'PYDEVD_LOAD_VALUES_ASYNC': 'True', 'PYTHONDONTWRITEBYTECODE': '1', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONPATH': 'E:\\PyCharm Community Edition 2018.1.4\\helpers\\pydev', 'PYTHONUNBUFFERED': '1', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\Windows', 'TEMP': 'C:\\Users\\4823\\AppData\\Local\\Temp', 'TMP': 'C:\\Users\\4823\\AppData\\Local\\Temp', 'USERDNSDOMAIN': 'GALAXY.ORG', 'USERDOMAIN': 'GALAXY', 'USERDOMAIN_ROAMINGPROFILE': 'GALAXY', 'USERNAME': '4823', 'USERPROFILE': 'C:\\Users\\4823', 'VIRTUAL_ENV': 'E:\\pycharm\\venv', 'WINDIR': 'C:\\Windows', 'WINDOWS_TRACING_FLAGS': '3', 'WINDOWS_TRACING_LOGFILE': 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log', '_DFX_INSTALL_UNSIGNED_DRIVER': '1', '_OLD_VIRTUAL_PATH': 'E:\\Scripts\\;E:\\;E:\\python\\Scripts\\;E:\\python\\;D:\\Conductor\\System;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;E:\\Anaconda3;E:\\Anaconda3\\Library\\mingw-w64\\bin;E:\\Anaconda3\\Library\\usr\\bin;E:\\Anaconda3\\Library\\bin;E:\\Anaconda3\\Scripts;E:\\python\\Scripts\\;E:\\python\\', '_OLD_VIRTUAL_PROMPT': '$P$G'})
>>> os.sep
'\\'
>>> os.pathsep
';'
>>> os.linesep
'\r\n'
>>> os.urandom(2)
b'\xf4\xb6'
>>> os.urandom(4)
b"*\xca\xba'"
映射os.environ包含前面介绍的环境变量。例如,要访问环境变量PYTHONPATH,可以使用表达式os.environ[‘PYTHONPATH’]。这个映射也可用于修改环境变量,但并非所有平台都支持这么做。
函数os.system用于运行外部程序。还有其他用于执行外部程序的函数,如execv和popen。前者退出Python解释器,并将控制器交给被执行的程序,而后者创建一个到程序的连接(这个连接类似于文件)。
变量os.sep是用于路径名中的分隔符。在UNIX中,标准分隔符为/。Windows中为\。旧式macOC中为:。
可使用os.pathsep来组合多条路径,就想在PYTHONPATH中那样。pathsep用于分隔不同的路径名:在UNIX/macOC中为:,在Windows中为;。
变量os.linsep是用于文本文件中的行分隔符:在UNIX/OS X中为单个换行符(\n),在Windows中为回车和换行符(\r\n)。
函数urandom使用随系统而异的“真正”(至少是强加密)随机源。如果平台没有提供这样的随机源,将引发NotImplementedError异常。
7、模块fileinput
它能让你轻松地迭代一系列文本文件中的所有行。其中一些重要的函数如下:
函数 | 描述 |
---|---|
input([files[,inplace[,backup]]]) | 帮助迭代多个输入流中的行 |
filename() | 返回当前文件的名称 |
lineno() | 返回(累计的)当前行号 |
fileineno() | 返回在当前文件中的行号 |
isfirstline() | 检查当前行是否文件中的第一行 |
isstdin() | 检查最后一行是否来自sys.stdin |
nextfile() | 关闭当前文件并移到下一个文件 |
close() | 关闭序列 |
fileinput.input是其中最重要的函数,它返回一个可在for循环中进行迭代的对象。
pass