Opensourcetechブログ

OpensourcetechによるNGINX/Kubernetes/Zabbix/Neo4j/Linuxなどオープンソース技術に関するブログです。

Python help() について

 

こんにちは、鯨井貴博@opensourcetechです。

 

Pythonのhelp()に関するメモです。

help()は、関数名やモジュール名を指定してヘルプ(マニュアル)を表示するものです。

 

Pythonの関数やモジュール

標準で用意されている関数やモジュールは、以下。

2. 組み込み関数 — Python 3.6.5 ドキュメント

Python 標準ライブラリ — Python 3.6.5 ドキュメント

pipコマンドで追加できるもモジュールは、以下となります。

pypi.orgPyPI – the Python Package Index · PyPI

 

 

help()の開始

bash-3.2$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help()・・・help()の開始

Welcome to Python 2.7! This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/2.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>・・・ここに関数名やライブラリ名(モジュール名)、トピックなどを指定します。

 

 

help()の全体像を掴む

help()使用に際しては、以下のようにしてまず全体像を掴んでおくといいかもしれません。

bash-3.2$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help()

help> modules・・・モジュールの全体を確認

Please wait a moment while I gather a list of all available modules...


/Library/Python/2.7/site-packages/IPython/kernel/__init__.py:13: ShimWarning: The `IPython.kernel` package has been deprecated since IPython 4.0.You should import from ipykernel or jupyter_client instead.
"You should import from ipykernel or jupyter_client instead.", ShimWarning)
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pkgutil.py:110: VisibleDeprecationWarning: zmq.eventloop.minitornado is deprecated in pyzmq 14.0 and will be removed.
Install tornado itself to use zmq with the tornado IOLoop.

__import__(name)
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_bridgesupport.py:674: RuntimeWarning: Error parsing BridgeSupport data for AVFoundation: PyObjCRT_SkipTypeSpec: Unhandled type '5d' ]}
warnings.warn("Error parsing BridgeSupport data for %s: %s" % (frameworkName, e), RuntimeWarning)
2018-05-09 11:10:33.901 Python[912:29113] Cannot find executable for CFBundle 0x7f881fed42e0 </System/Library/Frameworks/Message.framework> (not loaded)
AVFoundation _codecs_cn email pyclbr
Accounts _codecs_hk encodings pydoc
AddressBook _codecs_iso2022 ensurepip pydoc_data
AppKit _codecs_jp enum pyexpat
AppleScriptKit _codecs_kr errno pygments
AppleScriptObjC _codecs_tw exceptions pylab
Audio_mac _collections fcntl pyparsing
Automator _csv filecmp pytz
BaseHTTPServer _ctypes fileinput quopri
Bastion _ctypes_test findertools random
CFNetwork _curses fnmatch re
CFOpenDirectory _curses_panel formatter readline
CGIHTTPServer _elementtree fpformat repr
Canvas _functools fractions requests
Carbon _hashlib ftplib resource
Cocoa _heapq functools rexec
CodeWarrior _hotshot future_builtins rfc822
Collaboration _io gc rlcompleter
ColorPicker _json genericpath rmagic
ConfigParser _locale gensuitemodule robotparser
Cookie _lsprof gestalt runpy
CoreData _markerlib getopt scandir
CoreFoundation _multibytecodec getpass sched
CoreGraphics _multiprocessing gettext scipy
CoreLocation _osx_support glob select
CoreText _pyio grp sets
Dialog _random gzip setuptools
DictionaryServices _scandir hashlib sgmllib
DocXMLRPCServer _scproxy heapq sha
EasyDialogs _socket hgdemandimport shelve
EventKit _sqlite3 hgext shlex
ExceptionHandling _sre hgext3rd shutil
Explorer _ssl hmac shutil_backports
FSEvents _strptime hotshot signal
FileDialog _struct htmlentitydefs simplegeneric
Finder _symtable htmllib site
FixTk _sysconfigdata httplib six
Foundation _testcapi ic smtpd
FrameWork _threading_local icglue smtplib
HTMLParser _tkinter icopen sndhdr
IN _warnings idlelib snowballstemmer
IPython _weakref idna socket
InputMethodKit _weakrefset ihooks sphinx
InstallerPlugins abc imageop sphinxcontrib
InstantMessage aepack imagesize sqlite3
JavaScriptCore aetools imaplib sre
LatentSemanticMapping aetypes imghdr sre_compile
LaunchServices aifc imp sre_constants
MacOS alabaster importlib sre_parse
Message altgraph imputil ssl
MimeWriter antigravity inspect stat
MiniAEFrame anydbm io statvfs
Nav applesingle ipython_genutils storemagic
Netscape appletrawmain itertools string
OSATerminology appletrunner jinja2 stringold
OpenDirectory appnope json stringprep
OpenSSL argparse keyword strop
PIL argvemulator lib2to3 struct
PixMapWrapper array linecache subprocess
PreferencePanes ast locale sunau
PubSub asynchat logging sunaudio
PyObjCTools asyncore macerrors symbol
QTKit atexit macholib sympyprinting
Quartz audiodev macostools symtable
Queue audioop macpath sys
ScreenSaver autoGIL macresource sysconfig
ScriptingBridge autoreload macurl2path syslog
ScrolledText babel mailbox tabnanny
SearchKit backports mailcap tarfile
ServiceManagement base64 markupbase telnetlib
SimpleDialog bdb markupsafe tempfile
SimpleHTTPServer bdist_mpkg marshal terminalcommand
SimpleXMLRPCServer bgenlocations math termios
Social binascii matplotlib test
SocketServer binhex md5 tests
StdSuites bisect mercurial textwrap
StringIO bonjour mhlib this
SyncServices bsddb mimetools thread
SystemConfiguration bsddb185 mimetypes threading
SystemEvents buildtools mimify time
Tix bundlebuilder mmap timeit
Tkconstants bz2 modulefinder tkColorChooser
Tkdnd cPickle modulegraph tkCommonDialog
Tkinter cProfile multifile tkFileDialog
UserDict cStringIO multiprocessing tkFont
UserList calendar mutex tkMessageBox
UserString certifi neo4j tkSimpleDialog
VBoxPython2_6 cfmfile netrc toaiff
VBoxPython2_7 cgi new token
WebKit cgitb nis tokenize
_AE chardet nntplib trace
_AH chunk ntpath traceback
_App cli nturl2path traitlets
_CF cmath numbers ttk
_CG cmd numpy tty
_CarbonEvt code objc turtle
_Cm codecs opcode types
_Ctl codeop operator typing
_Dlg collections optparse unicodedata
_Drag colorsys os unittest
_Evt commands os2emxpath urllib
_File compileall parser urllib2
_Fm compiler pathlib2 urllib3
_Folder contextlib pdb urlparse
_Help cookielib pexpect user
_IBCarbon copy pickle uu
_Icn copy_reg pickleshare uuid
_LWPCookieJar crypt pickletools vboxapi
_Launch csv pimp vboxshell
_List ctypes pip videoreader
_Menu curses pipes warnings
_Mlte cythonmagic pkg_resources wave
_MozillaCookieJar datetime pkgutil wcwidth
_OSA dateutil platform weakref
_Qd dbhash plistlib webbrowser
_Qdoffs dbm popen2 whichdb
_Qt decimal poplib wsgiref
_Res decorator posix xattr
_Scrap difflib posixfile xdrlib
_Snd dircache posixpath xml
_TE dis pprint xmllib
_Win distutils profile xmlrpclib
__builtin__ dl prompt_toolkit xxsubtype
__future__ doctest pstats zipfile
_abcoll docutils pty zipimport
_ast dumbdbm ptyprocess zlib
_bisect dummy_thread pwd zmq
_builtinSuites dummy_threading py2app zope
_codecs easy_install py_compile

Enter any module name to get more help. Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".

help> modules neo4j・・・neo4jモジュールを確認

Here is a list of matching modules. Enter any module name to get more help.


neo4j
neo4j.__main__
neo4j.addressing
neo4j.bolt
neo4j.bolt._io
neo4j.bolt.cert
neo4j.bolt.connection - This module contains the low-level functionality required for speaking
neo4j.bolt.io
neo4j.bolt.response
neo4j.compat - This module provides compatibility functions between different versions
neo4j.compat.collections
neo4j.compat.ssl
neo4j.config
neo4j.exceptions - This module contains the core driver exceptions.
neo4j.meta
neo4j.packstream
neo4j.packstream._packer
neo4j.packstream._unpacker
neo4j.packstream.constants
neo4j.packstream.packer
neo4j.packstream.structure
neo4j.packstream.unpacker
neo4j.util
neo4j.v1
neo4j.v1.api
neo4j.v1.direct
neo4j.v1.exceptions
neo4j.v1.result
neo4j.v1.routing
neo4j.v1.security
neo4j.v1.session
neo4j.v1.types - This module contains classes for modelling nodes, relationships and


help> neo4j.config・・・neo4j.configを確認
Help on module neo4j.config in neo4j:

NAME
neo4j.config - # -*- encoding: utf-8 -*-

FILE
/Library/Python/2.7/site-packages/neo4j/config.py

DATA
DEFAULT_CONNECTION_ACQUISITION_TIMEOUT = 60
DEFAULT_CONNECTION_TIMEOUT = 5.0
DEFAULT_LOAD_BALANCING_STRATEGY = 0
DEFAULT_MAX_CONNECTION_LIFETIME = 3600
DEFAULT_MAX_CONNECTION_POOL_SIZE = 100
DEFAULT_MAX_RETRY_TIME = 30.0
DEFAULT_USER_AGENT = 'neo4j-python/1.5.3'
INFINITE = -1
LOAD_BALANCING_STRATEGY_LEAST_CONNECTED = 0
LOAD_BALANCING_STRATEGY_ROUND_ROBIN = 1
TRUST_ALL_CERTIFICATES = 2
TRUST_CUSTOM_CA_SIGNED_CERTIFICATES = 3
TRUST_DEFAULT = 2
TRUST_ON_FIRST_USE = 0
TRUST_SIGNED_CERTIFICATES = 1
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES = 4
default_config = {'auth': None, 'connection_acquisition_timeout': 60, ...
version = '1.5.3'

help> keywords・・・キーワードの全体を確認

Here is a list of the Python keywords. Enter any keyword to get more help.

and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass


help> topics・・・トピックの全体を確認

Here is a list of available topics. Enter any topic name to get more help.

ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES METHODS SPECIALATTRIBUTES
BACKQUOTES ELLIPSIS MODULES SPECIALIDENTIFIERS
BASICMETHODS EXCEPTIONS NAMESPACES SPECIALMETHODS
BINARY EXECUTION NONE STRINGMETHODS
BITWISE EXPRESSIONS NUMBERMETHODS STRINGS
BOOLEAN FILES NUMBERS SUBSCRIPTS
CALLABLEMETHODS FLOAT OBJECTS TRACEBACKS
CALLS FORMATTING OPERATORS TRUTHVALUE
CLASSES FRAMEOBJECTS PACKAGES TUPLELITERALS
CODEOBJECTS FRAMES POWER TUPLES
COERCIONS FUNCTIONS PRECEDENCE TYPEOBJECTS
COMPARISON IDENTIFIERS PRINTING TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS1

 

 

関数名やライブラリ名の指定 方法1

help> dir・・・dir()関数の指定 ※以下、ヘルプ。

Help on built-in function dir in module __builtin__:

dir(...)
dir([object]) -> list of strings

If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.

help> range
Help on built-in function range in module __builtin__:

range(...)
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

help> list・・・list関数の指定 ※以下、ヘルプ。
Help on class list in module __builtin__:

class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
|
| Methods defined here:
|
| __add__(...)
| x.__add__(y) <==> x+y
|
| __contains__(...)
| x.__contains__(y) <==> y in x
|
| __delitem__(...)
| x.__delitem__(y) <==> del x[y]
|
| __delslice__(...)
| x.__delslice__(i, j) <==> del x[i:j]
|
| Use of negative indices is not supported.
|
| __eq__(...)
| x.__eq__(y) <==> x==y
|
| __ge__(...)
| x.__ge__(y) <==> x>=y
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __getslice__(...)
| x.__getslice__(i, j) <==> x[i:j]
|
| Use of negative indices is not supported.
|
| __gt__(...)
| x.__gt__(y) <==> x>y
|
| __iadd__(...)
| x.__iadd__(y) <==> x+=y
|
| __imul__(...)
| x.__imul__(y) <==> x*=y
|
| __init__(...)
| x.__init__(...) initializes x; see help(type(x)) for signature
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| __le__(...)
| x.__le__(y) <==> x<=y
|
| __len__(...)
| x.__len__() <==> len(x)
|
| __lt__(...)
| x.__lt__(y) <==> x<y
|
| __mul__(...)
| x.__mul__(n) <==> x*n
|
| __ne__(...)
| x.__ne__(y) <==> x!=y
|
| __repr__(...)
| x.__repr__() <==> repr(x)
|
| __reversed__(...)
| L.__reversed__() -- return a reverse iterator over the list
|
| __rmul__(...)
| x.__rmul__(n) <==> n*x
|
| __setitem__(...)
| x.__setitem__(i, y) <==> x[i]=y
|
| __setslice__(...)
| x.__setslice__(i, j, y) <==> x[i:j]=y
|
| Use of negative indices is not supported.
|
| __sizeof__(...)
| L.__sizeof__() -- size of L in memory, in bytes
|
| append(...)
| L.append(object) -- append object to end
|
| count(...)
| L.count(value) -> integer -- return number of occurrences of value
|
| extend(...)
| L.extend(iterable) -- extend list by appending elements from the iterable
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
| insert(...)
| L.insert(index, object) -- insert object before index
|
| pop(...)
| L.pop([index]) -> item -- remove and return item at index (default last).
| Raises IndexError if list is empty or index is out of range.
|
| remove(...)
| L.remove(value) -- remove first occurrence of value.
| Raises ValueError if the value is not present.
|
| reverse(...)
| L.reverse() -- reverse *IN PLACE*
|
| sort(...)
| L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
| cmp(x, y) -> -1, 0, 1
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T

help> math・・・mathモジュールの指定 ※以下、ヘルプ。
Help on module math:

NAME
math

FILE
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so

MODULE DOCS
http://docs.python.org/library/math

DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.

FUNCTIONS
acos(...)
acos(x)

Return the arc cosine (measured in radians) of x.

acosh(...)
acosh(x)

Return the inverse hyperbolic cosine of x.

asin(...)
asin(x)

Return the arc sine (measured in radians) of x.

asinh(...)
asinh(x)

Return the inverse hyperbolic sine of x.

atan(...)
atan(x)

Return the arc tangent (measured in radians) of x.

atan2(...)
atan2(y, x)

Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered.

atanh(...)
atanh(x)

Return the inverse hyperbolic tangent of x.

ceil(...)
ceil(x)

Return the ceiling of x as a float.
This is the smallest integral value >= x.

copysign(...)
copysign(x, y)

Return x with the sign of y.

cos(...)
cos(x)

Return the cosine of x (measured in radians).

cosh(...)
cosh(x)

Return the hyperbolic cosine of x.

degrees(...)
degrees(x)

Convert angle x from radians to degrees.

erf(...)
erf(x)

Error function at x.

erfc(...)
erfc(x)

Complementary error function at x.

exp(...)
exp(x)

Return e raised to the power of x.

expm1(...)
expm1(x)

Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.

fabs(...)
fabs(x)

Return the absolute value of the float x.

factorial(...)
factorial(x) -> Integral

Find x!. Raise a ValueError if x is negative or non-integral.

floor(...)
floor(x)

Return the floor of x as a float.
This is the largest integral value <= x.

fmod(...)
fmod(x, y)

Return fmod(x, y), according to platform C. x % y may differ.

frexp(...)
frexp(x)

Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.

fsum(...)
fsum(iterable)

Return an accurate floating point sum of values in the iterable.
Assumes IEEE-754 floating point arithmetic.

gamma(...)
gamma(x)

Gamma function at x.

hypot(...)
hypot(x, y)

Return the Euclidean distance, sqrt(x*x + y*y).

isinf(...)
isinf(x) -> bool

Check if float x is infinite (positive or negative).

isnan(...)
isnan(x) -> bool

Check if float x is not a number (NaN).

ldexp(...)
ldexp(x, i)

Return x * (2**i).

lgamma(...)
lgamma(x)

Natural logarithm of absolute value of Gamma function at x.

log(...)
log(x[, base])

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.

log10(...)
log10(x)

Return the base 10 logarithm of x.

log1p(...)
log1p(x)

Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero.

modf(...)
modf(x)

Return the fractional and integer parts of x. Both results carry the sign
of x and are floats.

pow(...)
pow(x, y)

Return x**y (x to the power of y).

radians(...)
radians(x)

Convert angle x from degrees to radians.

sin(...)
sin(x)

Return the sine of x (measured in radians).

sinh(...)
sinh(x)

Return the hyperbolic sine of x.

sqrt(...)
sqrt(x)

Return the square root of x.

tan(...)
tan(x)

Return the tangent of x (measured in radians).

tanh(...)
tanh(x)

Return the hyperbolic tangent of x.

trunc(...)
trunc(x:Real) -> Integral

Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
e = 2.718281828459045
pi = 3.141592653589793

help> ・・・Enterで終了
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>

 

関数名やライブラリ名の指定 方法2

bash-3.2$ python
Python 2.7.10 (default, Oct 6 2017, 22:29:07)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(math)

>>> help(list)

>>> help(range)

>>> help(dir)

>>> help(help)

 

 

www.slideshare.net

github.com

www.facebook.com

twitter.com

www.instagram.com

 

 

にほんブログ村 IT技術ブログ Linuxへ
Linux

にほんブログ村 IT技術ブログ オープンソースへ
オープンソース

 

Opensourcetech by Takahiro Kujirai