Поиск по блогу

понедельник, 21 апреля 2014 г.

Заметки при чтении главы "Modules" документации Python

Модули в Python - это файлы. Из модулей можно импортировать классы. Импорт сначала осуществляется из текущего модуля, а потом из подпапок. Если ничего не найдено, то из путей sys.path
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable name.

Первоисточники и ссылки

In []:
Начинать лучше со страницы документации
<br/>[Modules](https://docs.python.org/2/tutorial/modules.html)
<br/>[]()
<br/>[]()
<br/>[]()
<br/>[]()
<br/>[]()
<br/>[]()
<br/>[]()
The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:
In [4]:
sys.path
Out[4]:
['',
 'C:\\Users\\kiss\\Anaconda\\python27.zip',
 'C:\\Users\\kiss\\Anaconda\\DLLs',
 'C:\\Users\\kiss\\Anaconda\\lib',
 'C:\\Users\\kiss\\Anaconda\\lib\\plat-win',
 'C:\\Users\\kiss\\Anaconda\\lib\\lib-tk',
 'C:\\Users\\kiss\\Anaconda',
 'C:\\Users\\kiss\\Anaconda\\lib\\site-packages',
 'C:\\Users\\kiss\\Anaconda\\lib\\site-packages\\PIL',
 'C:\\Users\\kiss\\Anaconda\\lib\\site-packages\\win32',
 'C:\\Users\\kiss\\Anaconda\\lib\\site-packages\\win32\\lib',
 'C:\\Users\\kiss\\Anaconda\\lib\\site-packages\\Pythonwin',
 'C:\\Users\\kiss\\Anaconda\\lib\\site-packages\\setuptools-2.2-py2.7.egg',
 'C:\\Users\\kiss\\Anaconda\\lib\\site-packages\\IPython\\extensions']

6.1.2. The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
the directory containing the input script (or the current directory).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
the installation-dependent default.
After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path.
This means that scripts in that directory will be loaded instead of modules of the same name in the library directory.
This is an error unless the replacement is intended. See section Standard Modules for more information.

6.2. Standard Modules

Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter).
Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls.
The set of such modules is a configuration option which also depends on the underlying platform. For example, the winreg module is only provided on Windows systems.
One particular module deserves some attention: sys, which is built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:
In [5]:
# The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:
sys.ps1,sys.ps2
Out[5]:
('In : ', '...: ')

The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings

In [10]:
# Надо чаще просматривать, что есть в модулях
# Я совсем забыл про эту вохможность
dir(sys)
Out[10]:
['__displayhook__',
 '__doc__',
 '__excepthook__',
 '__name__',
 '__package__',
 '__stderr__',
 '__stdin__',
 '__stdout__',
 '_clear_type_cache',
 '_current_frames',
 '_getframe',
 '_mercurial',
 'api_version',
 'argv',
 'builtin_module_names',
 'byteorder',
 'call_tracing',
 'callstats',
 'copyright',
 'displayhook',
 'dllhandle',
 'dont_write_bytecode',
 'exc_clear',
 'exc_info',
 'exc_type',
 'excepthook',
 'exec_prefix',
 'executable',
 'exit',
 'exitfunc',
 'flags',
 'float_info',
 'float_repr_style',
 'getcheckinterval',
 'getdefaultencoding',
 'getfilesystemencoding',
 'getprofile',
 'getrecursionlimit',
 'getrefcount',
 'getsizeof',
 'gettrace',
 'getwindowsversion',
 'hexversion',
 'last_traceback',
 'last_type',
 'last_value',
 'long_info',
 'maxint',
 'maxsize',
 'maxunicode',
 'meta_path',
 'modules',
 'path',
 'path_hooks',
 'path_importer_cache',
 'platform',
 'prefix',
 'ps1',
 'ps2',
 'ps3',
 'py3kwarning',
 'setcheckinterval',
 'setprofile',
 'setrecursionlimit',
 'settrace',
 'stderr',
 'stdin',
 'stdout',
 'subversion',
 'version',
 'version_info',
 'warnoptions',
 'winver']
In [11]:
# Without arguments, dir() lists the names you have defined currently
# Note that it lists all types of names: variables, modules, functions, etc.
dir()
Out[11]:
['In',
 'Out',
 '_',
 '_10',
 '_2',
 '_3',
 '_4',
 '_5',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '__package__',
 '_dh',
 '_exit_code',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'get_ipython',
 'help',
 'quit',
 'sys']
dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module __builtin__:
In [12]:
import __builtin__
>>> dir(__builtin__)  
Out[12]:
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BufferError',
 'BytesWarning',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'NameError',
 'None',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'ReferenceError',
 'RuntimeError',
 'RuntimeWarning',
 'StandardError',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'WindowsError',
 'ZeroDivisionError',
 '__IPYTHON__',
 '__IPYTHON__active',
 '__debug__',
 '__doc__',
 '__import__',
 '__name__',
 '__package__',
 'abs',
 'all',
 'any',
 'apply',
 'basestring',
 'bin',
 'bool',
 'buffer',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'cmp',
 'coerce',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'divmod',
 'dreload',
 'enumerate',
 'eval',
 'execfile',
 'file',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'intern',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'long',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'raw_input',
 'reduce',
 'reload',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'unichr',
 'unicode',
 'vars',
 'xrange',
 'zip']
In [7]:
# Это совсем другая функция
!dir
 Volume in drive C has no label.
 Volume Serial Number is 6017-2A0B

 Directory of C:\Users\kiss\Documents\IPython Notebooks\web\proxy\pyProxy

20.04.2014  16:07    <DIR>          .
20.04.2014  16:07    <DIR>          ..
20.04.2014  16:18    <DIR>          .ipynb_checkpoints
20.04.2014  16:38             8В 084 modules_python.ipynb
18.04.2014  13:47            59В 450 poria_1.html
18.04.2014  13:45            23В 668 poria_1.ipynb
15.04.2014  14:50             8В 813 proxylist.txt
18.04.2014  15:07             4В 416 ProxyNova.ipynb
18.04.2014  14:09           153В 457 proxy_garden.html
18.04.2014  14:08           153В 529 proxy_garden.ipynb
13.04.2014  19:44            35В 597 pyProxy.ipynb
08.10.2010  18:21            13В 170 pyproxy.py
14.04.2014  21:27            12В 507 pyproxy.pyc
16.04.2014  17:36            34В 943 pyproxy_pdb.html
16.04.2014  15:45            22В 081 pyproxy_pdb.ipynb
07.04.2014  19:19                 0 samara.txt
20.04.2014  16:18           154В 185 scrapy_middle.ipynb
15.04.2014  14:50             7В 708 uniqueproxylist.txt
              15 File(s)        691В 608 bytes
               3 Dir(s)  402В 648В 682В 496 bytes free

6.4. Packages

Packages are a way of structuring Python’s module namespace by using “dotted module names”. When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

6.4.1. Importing * From a Package

In [13]:
__path__
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-4096c837c17a> in <module>()
----> 1 __path__

NameError: name '__path__' is not defined
In []:



Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий