_id stringlengths 5 9 | text stringlengths 5 385k | title stringclasses 1
value |
|---|---|---|
doc_0 |
Return the visibility. | |
doc_1 |
Bases: object Stack of elements with a movable cursor. Mimics home/back/forward in a web browser. back()[source]
Move the position back and return the current element.
bubble(o)[source]
Raise all references of o to the top of the stack, and return it. Raises
ValueError
If o is not in the stack.
clear()[source]
Empty the stack.
empty()[source]
Return whether the stack is empty.
forward()[source]
Move the position forward and return the current element.
home()[source]
Push the first element onto the top of the stack. The first element is returned.
push(o)[source]
Push o to the stack at current position. Discard all later elements. o is returned.
remove(o)[source]
Remove o from the stack. Raises
ValueError
If o is not in the stack. | |
doc_2 |
Base class for figure.Figure and figure.SubFigure containing the methods that add artists to the figure or subfigure, create Axes, etc. add_artist(artist, clip=False)[source]
Add an Artist to the figure. Usually artists are added to Axes objects using Axes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead. Parameters
artistArtist
The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to figure.transSubfigure.
clipbool, default: False
Whether the added artist should be clipped by the figure patch. Returns
Artist
The added artist.
add_axes(*args, **kwargs)[source]
Add an Axes to the figure. Call signatures: add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters
rectsequence of float
The dimensions [left, bottom, width, height] of the new Axes. All quantities are in fractions of figure width and height.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the Axes. str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
Axes, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual Axes class.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_subplot
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Notes In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes. Examples Some simple examples: rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
add_callback(func)[source]
Add a callback function that will be called whenever one of the Artist's properties changes. Parameters
funccallable
The callback function. It must have the signature: def func(artist: Artist) -> Any
where artist is the calling Artist. Return values may exist but are ignored. Returns
int
The observer id associated with the callback. This id can be used for removing the callback with remove_callback later. See also remove_callback
add_gridspec(nrows=1, ncols=1, **kwargs)[source]
Return a GridSpec that has this figure as a parent. This allows complex layout of Axes in the figure. Parameters
nrowsint, default: 1
Number of rows in grid.
ncolsint, default: 1
Number or columns in grid. Returns
GridSpec
Other Parameters
**kwargs
Keyword arguments are passed to GridSpec. See also matplotlib.pyplot.subplots
Examples Adding a subplot that spans two rows: fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
# spans two rows:
ax3 = fig.add_subplot(gs[:, 1])
add_subfigure(subplotspec, **kwargs)[source]
Add a SubFigure to the figure as part of a subplot arrangement. Parameters
subplotspecgridspec.SubplotSpec
Defines the region in a parent gridspec where the subfigure will be placed. Returns
figure.SubFigure
Other Parameters
**kwargs
Are passed to the SubFigure object. See also Figure.subfigures
add_subplot(*args, **kwargs)[source]
Add an Axes to the figure as part of a subplot arrangement. Call signatures: add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters
*argsint, (int, int, index), or SubplotSpec, default: (1, 1, 1)
The position of the subplot described by one of Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure. A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots. A SubplotSpec. In rare circumstances, add_subplot may be called with a single argument, a subplot Axes instance already created in the present figure but not in the figure's list of Axes.
projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional
The projection type of the subplot (Axes). str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.
polarbool, default: False
If True, equivalent to projection='polar'.
axes_classsubclass type of Axes, optional
The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
sharex, shareyAxes, optional
Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
labelstr
A label for the returned Axes. Returns
axes.SubplotBase, or another subclass of Axes
The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is used. The returned Axes is then a subplot subclass of the base class. Other Parameters
**kwargs
This method also takes the keyword arguments for the returned Axes base class; except for the figure argument. The keyword arguments for the rectilinear base class Axes can be found in the following table but there might also be other keyword arguments if another projection is used.
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float See also Figure.add_axes
pyplot.subplot
pyplot.axes
Figure.subplots
pyplot.subplots
Examples fig = plt.figure()
fig.add_subplot(231)
ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
fig.add_subplot(232, frameon=False) # subplot with no frame
fig.add_subplot(233, projection='polar') # polar subplot
fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
fig.add_subplot(235, facecolor="red") # red subplot
ax1.remove() # delete ax1 from the figure
fig.add_subplot(ax1) # add ax1 back to the figure
align_labels(axs=None)[source]
Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the labels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_ylabels
align_xlabels(axs=None)[source]
Align the xlabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row. Parameters
axslist of Axes
Optional list of (or ndarray) Axes to align the xlabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_ylabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with rotated xtick labels: fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
align_ylabels(axs=None)[source]
Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the left, it is aligned with labels on Axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on Axes with the same right-most column. Parameters
axslist of Axes
Optional list (or ndarray) of Axes to align the ylabels. Default is to align all Axes on the figure. See also matplotlib.figure.Figure.align_xlabels
matplotlib.figure.Figure.align_labels
Notes This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions. Examples Example with large yticks labels: fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
autofmt_xdate(bottom=0.2, rotation=30, ha='right', which='major')[source]
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. Parameters
bottomfloat, default: 0.2
The bottom of the subplots for subplots_adjust.
rotationfloat, default: 30 degrees
The rotation angle of the xtick labels in degrees.
ha{'left', 'center', 'right'}, default: 'right'
The horizontal alignment of the xticklabels.
which{'major', 'minor', 'both'}, default: 'major'
Selects which ticklabels to rotate.
propertyaxes
The Axes instance the artist resides in, or None.
colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)[source]
Add a colorbar to a plot. Parameters
mappable
The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image. Note that one can create a ScalarMappable "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g. fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
caxAxes, optional
Axes into which the colorbar will be drawn.
axAxes, list of Axes, optional
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
use_gridspecbool, optional
If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the gridspec module. Returns
colorbarColorbar
Notes Additional keyword arguments are of two kinds: axes properties: locationNone or {'left', 'right', 'top', 'bottom'}
The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset. orientationNone or {'vertical', 'horizontal'}
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception. fractionfloat, default: 0.15
Fraction of original axes to use for colorbar. shrinkfloat, default: 1.0
Fraction by which to multiply the size of the colorbar. aspectfloat, default: 20
Ratio of long to short dimensions. padfloat, default: 0.05 if vertical, 0.15 if horizontal
Fraction of original axes between colorbar and new image axes. anchor(float, float), optional
The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal. panchor(float, float), or False, optional
The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal. colorbar properties:
Property Description
extend {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac {None, 'auto', length, lengths} If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional'). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
spacing {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval.
ticks None or list of ticks or Locator If None, ticks are determined automatically from the input.
format None or str or Formatter If None, ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter may be given instead.
drawedges bool Whether to draw lines at color boundaries.
label str The label on the colorbar's long axis. The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property Description
boundaries None or a sequence
values None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. If mappable is a ContourSet, its extend kwarg is included automatically. The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored. For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs. It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments: cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
contains(mouseevent)[source]
Test whether the mouse event occurred on the figure. Returns
bool, {}
convert_xunits(x)[source]
Convert x using the unit type of the xaxis. If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
convert_yunits(y)[source]
Convert y using the unit type of the yaxis. If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
delaxes(ax)[source]
Remove the Axes ax from the figure; update the current Axes.
draw(renderer)[source]
Draw the Artist (and its children) using the given renderer. This has no effect if the artist is not visible (Artist.get_visible returns False). Parameters
rendererRendererBase subclass.
Notes This method is overridden in the Artist subclasses.
findobj(match=None, include_self=True)[source]
Find artist objects. Recursively find all Artist instances contained in the artist. Parameters
match
A filter criterion for the matches. This can be
None: Return all objects contained in artist. A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool
Include self in the list to be checked for a match. Returns
list of Artist
format_cursor_data(data)[source]
Return a string representation of data. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter. See also get_cursor_data
propertyframeon
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
gca(**kwargs)[source]
Get the current Axes. If there is currently no Axes on this Figure, a new one is created using Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether pyplot.get_fignums() is empty.) The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
anchor (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
animated bool
aspect {'auto', 'equal'} or float
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
box_aspect float or None
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
facecolor or fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
xticklabels unknown
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...} or ScaleBase
yticklabels unknown
yticks unknown
zorder float
get_agg_filter()[source]
Return filter function to be used for agg filter.
get_alpha()[source]
Return the alpha value used for blending - not supported on all backends.
get_animated()[source]
Return whether the artist is animated.
get_children()[source]
Get a list of artists contained in the figure.
get_clip_box()[source]
Return the clipbox.
get_clip_on()[source]
Return whether the artist uses clipping.
get_clip_path()[source]
Return the clip path.
get_cursor_data(event)[source]
Return the cursor data for a given event. Note This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself. Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None. Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation. The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse. Parameters
eventmatplotlib.backend_bases.MouseEvent
See also format_cursor_data
get_default_bbox_extra_artists()[source]
get_edgecolor()[source]
Get the edge color of the Figure rectangle.
get_facecolor()[source]
Get the face color of the Figure rectangle.
get_figure()[source]
Return the Figure instance the artist belongs to.
get_frameon()[source]
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().
get_gid()[source]
Return the group id.
get_in_layout()[source]
Return boolean flag, True if artist is included in layout calculations. E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').
get_label()[source]
Return the label used for this artist in the legend.
get_linewidth()[source]
Get the line width of the Figure rectangle.
get_path_effects()[source]
get_picker()[source]
Return the picking behavior of the artist. The possible values are described in set_picker. See also
set_picker, pickable, pick
get_rasterized()[source]
Return whether the artist is to be rasterized.
get_sketch_params()[source]
Return the sketch parameters for the artist. Returns
tuple or None
A 3-tuple with the following elements:
scale: The amplitude of the wiggle perpendicular to the source line.
length: The length of the wiggle along the line.
randomness: The scale factor by which the length is shrunken or expanded. Returns None if no sketch parameters were set.
get_snap()[source]
Return the snap setting. See set_snap for details.
get_tightbbox(renderer, bbox_extra_artists=None)[source]
Return a (tight) bounding box of the figure in inches. Note that FigureBase differs from all other artists, which return their Bbox in pixels. Artists that have artist.set_in_layout(False) are not included in the bbox. Parameters
rendererRendererBase subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())
bbox_extra_artistslist of Artist or None
List of artists to include in the tight bounding box. If None (default), then all artist children of each Axes are included in the tight bounding box. Returns
BboxBase
containing the bounding box (in figure inches).
get_transform()[source]
Return the Transform instance used by this artist.
get_transformed_clip_path_and_affine()[source]
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
get_url()[source]
Return the url.
get_visible()[source]
Return the visibility.
get_window_extent(*args, **kwargs)[source]
Get the artist's bounding box in display space. The bounding box' width and height are nonnegative. Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0. Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
get_zorder()[source]
Return the artist's zorder.
have_units()[source]
Return whether units are set on any axis.
is_transform_set()[source]
Return whether the Artist has an explicitly set transform. This is True after set_transform has been called.
legend(*args, **kwargs)[source]
Place a legend on the figure. Call signatures: legend()
legend(handles, labels)
legend(handles=handles)
legend(labels)
The call signatures correspond to the following different ways to use this method: 1. Automatic detection of elements to be shown in the legend The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments. In this case, the labels are taken from the artist. You can specify them either at artist creation or by calling the set_label() method on the artist: ax.plot([1, 2, 3], label='Inline label')
fig.legend()
or: line, = ax.plot([1, 2, 3])
line.set_label('Label via method')
fig.legend()
Specific lines can be excluded from the automatic legend element selection by defining a label starting with an underscore. This is default for all artists, so calling Figure.legend without any arguments and without setting the labels manually will result in no legend being drawn. 2. Explicitly listing the artists and labels in the legend For full control of which artists have a legend entry, it is possible to pass an iterable of legend artists followed by an iterable of legend labels respectively: fig.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
3. Explicitly listing the artists in the legend This is similar to 2, but the labels are taken from the artists' label properties. Example: line1, = ax1.plot([1, 2, 3], label='label1')
line2, = ax2.plot([1, 2, 3], label='label2')
fig.legend(handles=[line1, line2])
4. Labeling existing plot elements Discouraged This call signature is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up. To make a legend for all artists on all Axes, call this function with an iterable of strings, one for each legend item. For example: fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot([1, 3, 5], color='blue')
ax2.plot([2, 4, 6], color='red')
fig.legend(['the blues', 'the reds'])
Parameters
handleslist of Artist, optional
A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
labelslist of str, optional
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient. Returns
Legend
Other Parameters
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures)
The location of the legend. The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure. The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure. The string 'center' places the legend at the center of the axes/figure. The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location. The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored). For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value:
Location String Location Code
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend. Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called. If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure): loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used: loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncolint, default: 1
The number of columns that the legend has.
propNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.
fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
labelcolorstr or list, default: rcParams["legend.labelcolor"] (default: 'None')
The color of the text in the legend. Either a valid color string (for example, 'red'), or a list of color strings. The labelcolor can also be made to match the color of the line or marker using 'linecolor', 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec'). Labelcolor can be set globally using rcParams["legend.labelcolor"] (default: 'None'). If None, use rcParams["text.color"] (default: 'black').
numpointsint, default: rcParams["legend.numpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a Line2D (line).
scatterpointsint, default: rcParams["legend.scatterpoints"] (default: 1)
The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot).
scatteryoffsetsiterable of floats, default: [0.375, 0.5, 0.3125]
The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5].
markerscalefloat, default: rcParams["legend.markerscale"] (default: 1.0)
The relative size of legend markers compared with the originally drawn ones.
markerfirstbool, default: True
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.
frameonbool, default: rcParams["legend.frameon"] (default: True)
Whether the legend should be drawn on a patch (frame).
fancyboxbool, default: rcParams["legend.fancybox"] (default: True)
Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background.
shadowbool, default: rcParams["legend.shadow"] (default: False)
Whether to draw a shadow behind the legend.
framealphafloat, default: rcParams["legend.framealpha"] (default: 0.8)
The alpha transparency of the legend's background. If shadow is activated and framealpha is None, the default value is ignored.
facecolor"inherit" or color, default: rcParams["legend.facecolor"] (default: 'inherit')
The legend's background color. If "inherit", use rcParams["axes.facecolor"] (default: 'white').
edgecolor"inherit" or color, default: rcParams["legend.edgecolor"] (default: '0.8')
The legend's background patch edge color. If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').
mode{"expand", None}
If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).
bbox_transformNone or matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.
titlestr or None
The legend's title. Default is no title (None).
title_fontpropertiesNone or matplotlib.font_manager.FontProperties or dict
The font properties of the legend's title. If None (default), the title_fontsize argument will be used if present; if title_fontsize is also None, the current rcParams["legend.title_fontsize"] (default: None) will be used.
title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default: rcParams["legend.title_fontsize"] (default: None)
The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.
borderpadfloat, default: rcParams["legend.borderpad"] (default: 0.4)
The fractional whitespace inside the legend border, in font-size units.
labelspacingfloat, default: rcParams["legend.labelspacing"] (default: 0.5)
The vertical space between the legend entries, in font-size units.
handlelengthfloat, default: rcParams["legend.handlelength"] (default: 2.0)
The length of the legend handles, in font-size units.
handleheightfloat, default: rcParams["legend.handleheight"] (default: 0.7)
The height of the legend handles, in font-size units.
handletextpadfloat, default: rcParams["legend.handletextpad"] (default: 0.8)
The pad between the legend handle and text, in font-size units.
borderaxespadfloat, default: rcParams["legend.borderaxespad"] (default: 0.5)
The pad between the axes and legend border, in font-size units.
columnspacingfloat, default: rcParams["legend.columnspacing"] (default: 2.0)
The spacing between columns, in font-size units.
handler_mapdict or None
The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map. See also Axes.legend
Notes Some artists are not supported by this function. See Legend guide for details.
propertymouseover
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it. See also get_cursor_data(), ToolCursorPosition and NavigationToolbar2.
pchanged()[source]
Call all of the registered callbacks. This function is triggered internally when a property is changed. See also add_callback
remove_callback
pick(mouseevent)[source]
Process a pick event. Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set. See also
set_picker, get_picker, pickable
pickable()[source]
Return whether the artist is pickable. See also
set_picker, get_picker, pick
properties()[source]
Return a dictionary of all the properties of the artist.
remove()[source]
Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle. Call relim to update the axes limits if desired. Note: relim will not see collections even if the collection was added to the axes with autolim = True. Note: there is no support for removing the artist's legend entry.
remove_callback(oid)[source]
Remove a callback based on its observer id. See also add_callback
sca(a)[source]
Set the current Axes to be a and return a.
set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, frameon=<UNSET>, gid=<UNSET>, in_layout=<UNSET>, label=<UNSET>, linewidth=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)[source]
Set multiple properties at once. Supported properties are
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
edgecolor color
facecolor color
figure Figure
frameon bool
gid str
in_layout bool
label object
linewidth number
path_effects AbstractPathEffect
picker None or bool or float or callable
rasterized bool
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
transform Transform
url str
visible bool
zorder float
set_agg_filter(filter_func)[source]
Set the agg filter. Parameters
filter_funccallable
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends. Parameters
alphascalar or None
alpha must be within the 0-1 range, inclusive.
set_animated(b)[source]
Set whether the artist is intended to be used in an animation. If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist / Axes.draw_artist explicitly on the artist. This appoach is used to speed up animations using blitting. See also matplotlib.animation and Faster rendering by using blitting. Parameters
bbool
set_clip_box(clipbox)[source]
Set the artist's clip Bbox. Parameters
clipboxBbox
set_clip_on(b)[source]
Set whether the artist uses clipping. When False artists will be visible outside of the axes which can lead to unexpected results. Parameters
bbool
set_clip_path(path, transform=None)[source]
Set the artist's clip path. Parameters
pathPatch or Path or TransformedPath or None
The clip path. If given a Path, transform must be provided as well. If None, a previously set clip path is removed.
transformTransform, optional
Only used if path is a Path, in which case the given Path is converted to a TransformedPath using transform. Notes For efficiency, if path is a Rectangle this method will set the clipping box to the corresponding rectangle and set the clipping path to None. For technical reasons (support of set), a tuple (path, transform) is also accepted as a single positional parameter.
set_edgecolor(color)[source]
Set the edge color of the Figure rectangle. Parameters
colorcolor
set_facecolor(color)[source]
Set the face color of the Figure rectangle. Parameters
colorcolor
set_figure(fig)[source]
Set the Figure instance the artist belongs to. Parameters
figFigure
set_frameon(b)[source]
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible(). Parameters
bbool
set_gid(gid)[source]
Set the (group) id for the artist. Parameters
gidstr
set_in_layout(in_layout)[source]
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight'). Parameters
in_layoutbool
set_label(s)[source]
Set a label that will be displayed in the legend. Parameters
sobject
s will be converted to a string by calling str.
set_linewidth(linewidth)[source]
Set the line width of the Figure rectangle. Parameters
linewidthnumber
set_path_effects(path_effects)[source]
Set the path effects. Parameters
path_effectsAbstractPathEffect
set_picker(picker)[source]
Define the picking behavior of the artist. Parameters
pickerNone or bool or float or callable
This can be one of the following:
None: Picking is disabled for this artist (default). A boolean: If True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist. A float: If picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if its data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event: hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
set_rasterized(rasterized)[source]
Force rasterized (bitmap) drawing for vector graphics output. Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued. This setting is ignored for pixel-based output. See also Rasterization for vector graphics. Parameters
rasterizedbool
set_sketch_params(scale=None, length=None, randomness=None)[source]
Set the sketch parameters. Parameters
scalefloat, optional
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
lengthfloat, optional
The length of the wiggle along the line, in pixels (default 128.0)
randomnessfloat, optional
The scale factor by which the length is shrunken or expanded (default 16.0) The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
set_snap(snap)[source]
Set the snapping behavior. Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line. Snapping is currently only supported by the Agg and MacOSX backends. Parameters
snapbool or None
Possible values:
True: Snap vertices to the nearest pixel center.
False: Do not modify vertex positions.
None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center.
set_transform(t)[source]
Set the artist transform. Parameters
tTransform
set_url(url)[source]
Set the url for the artist. Parameters
urlstr
set_visible(b)[source]
Set the artist's visibility. Parameters
bbool
set_zorder(level)[source]
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat
propertystale
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
propertysticky_edges
x and y sticky edge lists for autoscaling. When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram. Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1. This attribute cannot be assigned to; however, the x and y lists can be modified in place as needed. Examples >>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)
subfigures(nrows=1, ncols=1, squeeze=True, wspace=None, hspace=None, width_ratios=None, height_ratios=None, **kwargs)[source]
Add a subfigure to this figure or subfigure. A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See Figure subfigures. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subfigure grid.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of subfigures.
wspace, hspacefloat, default: None
The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from a figure or rcParams when necessary.
width_ratiosarray-like of length ncols, optional
Defines the relative widths of the columns. Each column gets a relative width of width_ratios[i] / sum(width_ratios). If not given, all columns will have the same width.
height_ratiosarray-like of length nrows, optional
Defines the relative heights of the rows. Each row gets a relative height of height_ratios[i] / sum(height_ratios). If not given, all rows will have the same height.
subplot_mosaic(mosaic, *, sharex=False, sharey=False, subplot_kw=None, gridspec_kw=None, empty_sentinel='.')[source]
Build a layout of Axes based on ASCII art or nested lists. This is a helper function to build complex GridSpec layouts visually. Note This API is provisional and may be revised in the future based on early user feedback. Parameters
mosaiclist of list of {hashable or nested} or str
A visual layout of how you want your Axes to be arranged labeled as strings. For example x = [['A panel', 'A panel', 'edge'],
['C panel', '.', 'edge']]
produces 4 Axes: 'A panel' which is 1 row high and spans the first two columns 'edge' which is 2 rows high and is on the right edge 'C panel' which in 1 row and 1 column wide in the bottom left a blank space 1 row and 1 column wide in the bottom center Any of the entries in the layout can be a list of lists of the same form to create nested layouts. If input is a str, then it can either be a multi-line string of the form '''
AAE
C.E
'''
where each character is a column and each line is a row. Or it can be a single-line string where rows are separated by ;: 'AB;CC'
The string notation allows only single character Axes labels and does not support nesting but is very terse.
sharex, shareybool, default: False
If True, the x-axis (sharex) or y-axis (sharey) will be shared among all subplots. In that case, tick label visibility and axis units behave as for subplots. If False, each subplot's x- or y-axis will be independent.
subplot_kwdict, optional
Dictionary with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dictionary with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
empty_sentinelobject, optional
Entry in the layout to mean "leave this space empty". Defaults to '.'. Note, if layout is a string, it is processed via inspect.cleandoc to remove leading white space, which may interfere with using white-space as the empty sentinel. Returns
dict[label, Axes]
A dictionary mapping the labels to the Axes objects. The order of the axes is left-to-right and top-to-bottom of their position in the total layout.
subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)[source]
Add a set of subplots to this figure. This utility wrapper makes it convenient to create common layouts of subplots in a single call. Parameters
nrows, ncolsint, default: 1
Number of rows/columns of the subplot grid.
sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False
Controls sharing of x-axis (sharex) or y-axis (sharey): True or 'all': x- or y-axis will be shared among all subplots. False or 'none': each subplot x- or y-axis will be independent. 'row': each subplot row will share an x- or y-axis. 'col': each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params. When subplots have a shared axis that has units, calling Axis.set_units will update each axis with the new units.
squeezebool, default: True
If True, extra dimensions are squeezed out from the returned array of Axes: if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar. for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects. for NxM, subplots with N>1 and M>1 are returned as a 2D array. If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
subplot_kwdict, optional
Dict with keywords passed to the Figure.add_subplot call used to create each subplot.
gridspec_kwdict, optional
Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. Returns
Axes or array of Axes
Either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above. See also pyplot.subplots
Figure.add_subplot
pyplot.subplot
Examples # First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create a figure
plt.figure()
# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar Axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share a X axis with each column of subplots
fig.subplots(2, 2, sharex='col')
# Share a Y axis with each row of subplots
fig.subplots(2, 2, sharey='row')
# Share both X and Y axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)[source]
Adjust the subplot layout parameters. Unset parameters are left unmodified; initial values are given by rcParams["figure.subplot.[name]"]. Parameters
leftfloat, optional
The position of the left edge of the subplots, as a fraction of the figure width.
rightfloat, optional
The position of the right edge of the subplots, as a fraction of the figure width.
bottomfloat, optional
The position of the bottom edge of the subplots, as a fraction of the figure height.
topfloat, optional
The position of the top edge of the subplots, as a fraction of the figure height.
wspacefloat, optional
The width of the padding between subplots, as a fraction of the average Axes width.
hspacefloat, optional
The height of the padding between subplots, as a fraction of the average Axes height.
suptitle(t, **kwargs)[source]
Add a centered suptitle to the figure. Parameters
tstr
The suptitle text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.98
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: top
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the suptitle. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supxlabel(t, **kwargs)[source]
Add a centered supxlabel to the figure. Parameters
tstr
The supxlabel text.
xfloat, default: 0.5
The x location of the text in figure coordinates.
yfloat, default: 0.01
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: center
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: bottom
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supxlabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
supylabel(t, **kwargs)[source]
Add a centered supylabel to the figure. Parameters
tstr
The supylabel text.
xfloat, default: 0.02
The x location of the text in figure coordinates.
yfloat, default: 0.5
The y location of the text in figure coordinates.
horizontalalignment, ha{'center', 'left', 'right'}, default: left
The horizontal alignment of the text relative to (x, y).
verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: center
The vertical alignment of the text relative to (x, y).
fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')
The font size of the text. See Text.set_size for possible values.
fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')
The font weight of the text. See Text.set_weight for possible values. Returns
text
The Text instance of the supylabel. Other Parameters
fontpropertiesNone or dict, optional
A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case. **kwargs
Additional kwargs are matplotlib.text.Text properties.
text(x, y, s, fontdict=None, **kwargs)[source]
Add text to figure. Parameters
x, yfloat
The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.
sstr
The text string.
fontdictdict, optional
A dictionary to override the default text properties. If not given, the defaults are determined by rcParams["font.*"]. Properties passed as kwargs override the corresponding ones given in fontdict. Returns
Text
Other Parameters
**kwargsText properties
Other miscellaneous text parameters.
Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha scalar or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box unknown
clip_on unknown
clip_path unknown
color or c color
figure Figure
fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font or font_properties font_manager.FontProperties or str or pathlib.Path
fontsize or size float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style {'normal', 'italic', 'oblique'}
fontvariant or variant {'normal', 'small-caps'}
fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid str
horizontalalignment or ha {'center', 'right', 'left'}
in_layout bool
label object
linespacing float (multiple of font size)
math_fontfamily str
multialignment or ma {'left', 'right', 'center'}
parse_math bool
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool
rotation float or {'vertical', 'horizontal'}
rotation_mode {None, 'default', 'anchor'}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
transform_rotates_text bool
url str
usetex bool or None
verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible bool
wrap bool
x float
y float
zorder float See also Axes.text
pyplot.text
update(props)[source]
Update this artist's properties from the dict props. Parameters
propsdict
update_from(other)[source]
Copy properties from other to self.
zorder=0 | |
doc_3 | The object passed as the tzinfo argument to the datetime constructor, or None if none was passed. | |
doc_4 | Reads and returns at most n frames of audio, as a bytes object. | |
doc_5 |
Check if windows match. New in version 1.6.0. Parameters
otherclass instance
The other class must have the window attribute. Returns
boolboolean
True if the windows are the same, False otherwise. | |
doc_6 | The maximum number of frames to include in tracebacks output by the default log_exception() method. If None, all frames are included. | |
doc_7 | class collections.abc.MutableMapping
ABCs for read-only and mutable mappings. | |
doc_8 |
Set the result for this Future, which will mark this Future as completed and trigger all attached callbacks. Note that a Future cannot be marked completed twice. Parameters
result (object) – the result object of this Future. Example::
>>> import threading
>>> import time
>>> import torch
>>>
>>> def slow_set_future(fut, value):
>>> time.sleep(0.5)
>>> fut.set_result(value)
>>>
>>> fut = torch.futures.Future()
>>> t = threading.Thread(
>>> target=slow_set_future,
>>> args=(fut, torch.ones(2) * 3)
>>> )
>>> t.start()
>>>
>>> print(fut.wait()) # tensor([3., 3.])
>>> t.join() | |
doc_9 |
Return the names of the available scales. | |
doc_10 |
Efficiently redraw Axes data, but not axis ticks, labels, etc. This method can only be used after an initial draw which caches the renderer. | |
doc_11 | Concrete implementation of InspectLoader.is_package(). A module is determined to be a package if its file path (as provided by ExecutionLoader.get_filename()) is a file named __init__ when the file extension is removed and the module name itself does not end in __init__. | |
doc_12 |
Return cumulative distribution function (cdf) for the given image. Parameters
imagearray
Image array.
nbinsint, optional
Number of bins for image histogram. Returns
img_cdfarray
Values of cumulative distribution function.
bin_centersarray
Centers of bins. See also
histogram
References
1
https://en.wikipedia.org/wiki/Cumulative_distribution_function Examples >>> from skimage import data, exposure, img_as_float
>>> image = img_as_float(data.camera())
>>> hi = exposure.histogram(image)
>>> cdf = exposure.cumulative_distribution(image)
>>> np.alltrue(cdf[0] == np.cumsum(hi[0])/float(image.size))
True | |
doc_13 |
Bases: skimage.viewer.plugins.base.Plugin
__init__(max_radius=20, **kwargs) [source]
Initialize self. See help(type(self)) for accurate signature.
attach(image_viewer) [source]
Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: viewer += Plugin(...)
Also note that attach automatically calls the filter function so that the image matches the filtered value specified by attached widgets.
help() [source]
property label
name = 'LabelPainter'
on_enter(overlay) [source]
property radius | |
doc_14 | __delitem__(key)
discard(key)
These methods immediately delete the message. The MH convention of marking a message for deletion by prepending a comma to its name is not used. | |
doc_15 | Convert an IRI to a URI. All non-ASCII and unsafe characters are quoted. If the URL has a domain, it is encoded to Punycode. >>> iri_to_uri('http://\u2603.net/p\xe5th?q=\xe8ry%DF')
'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF'
Parameters
iri (Union[str, Tuple[str, str, str, str, str]]) – The IRI to convert.
charset (str) – The encoding of the IRI.
errors (str) – Error handler to use during bytes.encode.
safe_conversion (bool) – Return the URL unchanged if it only contains ASCII characters and no whitespace. See the explanation below. Return type
str There is a general problem with IRI conversion with some protocols that are in violation of the URI specification. Consider the following two IRIs: magnet:?xt=uri:whatever
itms-services://?action=download-manifest
After parsing, we don’t know if the scheme requires the //, which is dropped if empty, but conveys different meanings in the final URL if it’s present or not. In this case, you can use safe_conversion, which will return the URL unchanged if it only contains ASCII characters and no whitespace. This can result in a URI with unquoted characters if it was not already quoted correctly, but preserves the URL’s semantics. Werkzeug uses this for the Location header for redirects. Changelog Changed in version 0.15: All reserved characters remain unquoted. Previously, only some reserved characters were left unquoted. Changed in version 0.9.6: The safe_conversion parameter was added. New in version 0.6. | |
doc_16 | A function that checks if django.contrib.sites is installed and returns either the current Site object or a RequestSite object based on the request. It looks up the current site based on request.get_host() if the SITE_ID setting is not defined. Both a domain and a port may be returned by request.get_host() when the Host header has a port explicitly specified, e.g. example.com:80. In such cases, if the lookup fails because the host does not match a record in the database, the port is stripped and the lookup is retried with the domain part only. This does not apply to RequestSite which will always use the unmodified host. | |
doc_17 |
Find indices where elements of v should be inserted in a to maintain order. For full documentation, see numpy.searchsorted See also numpy.searchsorted
equivalent function | |
doc_18 |
Legendre series whose graph is a straight line. Parameters
off, sclscalars
The specified line is given by off + scl*x. Returns
yndarray
This module’s representation of the Legendre series for off + scl*x. See also numpy.polynomial.polynomial.polyline
numpy.polynomial.chebyshev.chebline
numpy.polynomial.laguerre.lagline
numpy.polynomial.hermite.hermline
numpy.polynomial.hermite_e.hermeline
Examples >>> import numpy.polynomial.legendre as L
>>> L.legline(3,2)
array([3, 2])
>>> L.legval(-3, L.legline(3,2)) # should be -3
-3.0 | |
doc_19 |
Applies Instance Normalization over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper Instance Normalization: The Missing Ingredient for Fast Stylization. y=x−E[x]Var[x]+ϵ∗γ+βy = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
The mean and standard-deviation are calculated per-dimension separately for each object in a mini-batch. γ\gamma and β\beta are learnable parameter vectors of size C (where C is the input size) if affine is True. The standard-deviation is calculated via the biased estimator, equivalent to torch.var(input, unbiased=False). By default, this layer uses instance statistics computed from input data in both training and evaluation modes. If track_running_stats is set to True, during training this layer keeps running estimates of its computed mean and variance, which are then used for normalization during evaluation. The running estimates are kept with a default momentum of 0.1. Note This momentum argument is different from one used in optimizer classes and the conventional notion of momentum. Mathematically, the update rule for running statistics here is x^new=(1−momentum)×x^+momentum×xt\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t , where x^\hat{x} is the estimated statistic and xtx_t is the new observed value. Note InstanceNorm3d and LayerNorm are very similar, but have some subtle differences. InstanceNorm3d is applied on each channel of channeled data like 3D models with RGB color, but LayerNorm is usually applied on entire sample and often in NLP tasks. Additionally, LayerNorm applies elementwise affine transform, while InstanceNorm3d usually don’t apply affine transform. Parameters
num_features – CC from an expected input of size (N,C,D,H,W)(N, C, D, H, W)
eps – a value added to the denominator for numerical stability. Default: 1e-5
momentum – the value used for the running_mean and running_var computation. Default: 0.1
affine – a boolean value that when set to True, this module has learnable affine parameters, initialized the same way as done for batch normalization. Default: False.
track_running_stats – a boolean value that when set to True, this module tracks the running mean and variance, and when set to False, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: False
Shape:
Input: (N,C,D,H,W)(N, C, D, H, W)
Output: (N,C,D,H,W)(N, C, D, H, W) (same shape as input) Examples: >>> # Without Learnable Parameters
>>> m = nn.InstanceNorm3d(100)
>>> # With Learnable Parameters
>>> m = nn.InstanceNorm3d(100, affine=True)
>>> input = torch.randn(20, 100, 35, 45, 10)
>>> output = m(input) | |
doc_20 |
Alias for get_linewidth. | |
doc_21 |
Conversion from the sRGB color space (IEC 61966-2-1:1999) to the CIE Lab colorspace under the given illuminant and observer. Parameters
rgb(…, 3) array_like
The image in RGB format. Final dimension denotes channels.
illuminant{“A”, “D50”, “D55”, “D65”, “D75”, “E”}, optional
The name of the illuminant (the function is NOT case sensitive).
observer{“2”, “10”}, optional
The aperture angle of the observer. Returns
out(…, 3) ndarray
The image in Lab format. Same dimensions as input. Raises
ValueError
If rgb is not at least 2-D with shape (…, 3). Notes RGB is a device-dependent color space so, if you use this function, be sure that the image you are analyzing has been mapped to the sRGB color space. This function uses rgb2xyz and xyz2lab. By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x_ref=95.047, y_ref=100., z_ref=108.883. See function get_xyz_coords for a list of supported illuminants. References
1
https://en.wikipedia.org/wiki/Standard_illuminant | |
doc_22 | See Migration guide for more details. tf.compat.v1.raw_ops.BatchFFT
tf.raw_ops.BatchFFT(
input, name=None
)
Args
input A Tensor of type complex64.
name A name for the operation (optional).
Returns A Tensor of type complex64. | |
doc_23 | Raised by any of the functions when an error is detected. | |
doc_24 |
Find indices where elements should be inserted to maintain order. Find the indices into a sorted array self (a) such that, if the corresponding elements in value were inserted before the indices, the order of self would be preserved. Assuming that self is sorted:
side returned index i satisfies
left self[i-1] < value <= self[i]
right self[i-1] <= value < self[i] Parameters
value:array-like, list or scalar
Value(s) to insert into self.
side:{‘left’, ‘right’}, optional
If ‘left’, the index of the first suitable location found is given. If ‘right’, return the last such index. If there is no suitable index, return either 0 or N (where N is the length of self).
sorter:1-D array-like, optional
Optional array of integer indices that sort array a into ascending order. They are typically the result of argsort. Returns
array of ints or int
If value is array-like, array of insertion points. If value is scalar, a single integer. See also numpy.searchsorted
Similar method from NumPy. | |
doc_25 | A subclass of ConnectionError, raised when a connection attempt is refused by the peer. Corresponds to errno ECONNREFUSED. | |
doc_26 | Path to the extension module. | |
doc_27 |
Filter an image with the Sato tubeness filter. This filter can be used to detect continuous ridges, e.g. tubes, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects. Defined only for 2-D and 3-D images. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to tubes, according to the method described in [1]. Parameters
image(N, M[, P]) ndarray
Array with input image data.
sigmasiterable of floats, optional
Sigmas used as scales of filter.
black_ridgesboolean, optional
When True (the default), the filter detects black ridges; when False, it detects white ridges.
mode{‘constant’, ‘reflect’, ‘wrap’, ‘nearest’, ‘mirror’}, optional
How to handle values outside the image borders.
cvalfloat, optional
Used in conjunction with mode ‘constant’, the value outside the image boundaries. Returns
out(N, M[, P]) ndarray
Filtered image (maximum of pixels across all scales). See also
meijering
frangi
hessian
References
1
Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S., Koller, T., …, Kikinis, R. (1998). Three-dimensional multi-scale line filter for segmentation and visualization of curvilinear structures in medical images. Medical image analysis, 2(2), 143-168. DOI:10.1016/S1361-8415(98)80009-1 | |
doc_28 | Return a tuple containing names of nonlocals in this function. | |
doc_29 | sys.stdout
sys.stderr
File objects used by the interpreter for standard input, output and errors:
stdin is used for all interactive input (including calls to input());
stdout is used for the output of print() and expression statements and for the prompts of input(); The interpreter’s own prompts and its error messages go to stderr. These streams are regular text files like those returned by the open() function. Their parameters are chosen as follows:
The character encoding is platform-dependent. Non-Windows platforms use the locale encoding (see locale.getpreferredencoding()). On Windows, UTF-8 is used for the console device. Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where isatty() returns True) use the value of the console input and output codepages at startup, respectively for stdin and stdout/stderr. This defaults to the system locale encoding if the process is not initially attached to a console. The special behaviour of the console can be overridden by setting the environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python. In that case, the console codepages are used as for any other character device. Under all platforms, you can override the character encoding by setting the PYTHONIOENCODING environment variable before starting Python or by using the new -X utf8 command line option and PYTHONUTF8 environment variable. However, for the Windows console, this only applies when PYTHONLEGACYWINDOWSSTDIO is also set. When interactive, the stdout stream is line-buffered. Otherwise, it is block-buffered like regular text files. The stderr stream is line-buffered in both cases. You can make both streams unbuffered by passing the -u command-line option or setting the PYTHONUNBUFFERED environment variable. Changed in version 3.9: Non-interactive stderr is now line-buffered instead of fully buffered. Note To write or read binary data from/to the standard streams, use the underlying binary buffer object. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc'). However, if you are writing a library (and do not control in which context its code will be executed), be aware that the standard streams may be replaced with file-like objects like io.StringIO which do not support the buffer attribute. | |
doc_30 |
Return series instance that has the specified roots. Returns a series representing the product (x - r[0])*(x - r[1])*...*(x - r[n-1]), where r is a list of roots. Parameters
rootsarray_like
List of roots.
domain{[], None, array_like}, optional
Domain for the resulting series. If None the domain is the interval from the smallest root to the largest. If [] the domain is the class domain. The default is [].
window{None, array_like}, optional
Window for the returned series. If None the class window is used. The default is None. Returns
new_seriesseries
Series with the specified roots. | |
doc_31 |
input_type: 'number'
template_name: 'django/forms/widgets/number.html'
Renders as: <input type="number" ...>
Beware that not all browsers support entering localized numbers in number input types. Django itself avoids using them for fields having their localize property set to True. | |
doc_32 | The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. | |
doc_33 | Fills self tensor with elements drawn from the exponential distribution: f(x)=λe−λxf(x) = \lambda e^{-\lambda x} | |
doc_34 | Schedule all currently open asynchronous generator objects to close with an aclose() call. After calling this method, the event loop will issue a warning if a new asynchronous generator is iterated. This should be used to reliably finalize all scheduled asynchronous generators. Note that there is no need to call this function when asyncio.run() is used. Example: try:
loop.run_forever()
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
New in version 3.6. | |
doc_35 | Return True if the event is set. | |
doc_36 | os.R_OK
os.W_OK
os.X_OK
Values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path, respectively. | |
doc_37 |
Call self as a function. | |
doc_38 | Returns the name of the field that contains the date data that this view will operate on. Returns date_field by default. | |
doc_39 |
Restore the graphics context from the stack - needed only for backends that save graphics contexts on a stack. | |
doc_40 |
Bases: object The LatexManager opens an instance of the LaTeX application for determining the metrics of text elements. The LaTeX environment can be modified by setting fonts and/or a custom preamble in rcParams. get_width_height_descent(text, prop)[source]
Get the width, total height, and descent (in TeX points) for a text typeset by the current LaTeX environment.
propertystr_cache[source] | |
doc_41 | tf.compat.v1.estimator.tpu.TPUEstimator(
model_fn=None, model_dir=None, config=None, params=None, use_tpu=True,
train_batch_size=None, eval_batch_size=None, predict_batch_size=None,
batch_axis=None, eval_on_tpu=True, export_to_tpu=True, export_to_cpu=True,
warm_start_from=None, embedding_config_spec=None,
export_saved_model_api_version=ExportSavedModelApiVersion.V1
)
TPUEstimator also supports training on CPU and GPU. You don't need to define a separate tf.estimator.Estimator. TPUEstimator handles many of the details of running on TPU devices, such as replicating inputs and models for each core, and returning to host periodically to run hooks. TPUEstimator transforms a global batch size in params to a per-shard batch size when calling the input_fn and model_fn. Users should specify global batch size in constructor, and then get the batch size for each shard in input_fn and model_fn by params['batch_size']. For training, model_fn gets per-core batch size; input_fn may get per-core or per-host batch size depending on per_host_input_for_training in TPUConfig (See docstring for TPUConfig for details). For evaluation and prediction, model_fn gets per-core batch size and input_fn get per-host batch size. Evaluation model_fn should return TPUEstimatorSpec, which expects the eval_metrics for TPU evaluation. If eval_on_tpu is False, the evaluation will execute on CPU or GPU; in this case the following discussion on TPU evaluation does not apply. TPUEstimatorSpec.eval_metrics is a tuple of metric_fn and tensors, where tensors could be a list of any nested structure of Tensors (See TPUEstimatorSpec for details). metric_fn takes the tensors and returns a dict from metric string name to the result of calling a metric function, namely a (metric_tensor, update_op) tuple. One can set use_tpu to False for testing. All training, evaluation, and predict will be executed on CPU. input_fn and model_fn will receive train_batch_size or eval_batch_size unmodified as params['batch_size']. Current limitations: TPU evaluation only works on a single host (one TPU worker) except BROADCAST mode. input_fn for evaluation should NOT raise an end-of-input exception (OutOfRangeError or StopIteration). And all evaluation steps and all batches should have the same size. Example (MNIST): # The metric Fn which runs on CPU.
def metric_fn(labels, logits):
predictions = tf.argmax(logits, 1)
return {
'accuracy': tf.compat.v1.metrics.precision(
labels=labels, predictions=predictions),
}
# Your model Fn which runs on TPU (eval_metrics is list in this example)
def model_fn(features, labels, mode, config, params):
...
logits = ...
if mode = tf.estimator.ModeKeys.EVAL:
return tpu_estimator.TPUEstimatorSpec(
mode=mode,
loss=loss,
eval_metrics=(metric_fn, [labels, logits]))
# or specify the eval_metrics tensors as dict.
def model_fn(features, labels, mode, config, params):
...
final_layer_output = ...
if mode = tf.estimator.ModeKeys.EVAL:
return tpu_estimator.TPUEstimatorSpec(
mode=mode,
loss=loss,
eval_metrics=(metric_fn, {
'labels': labels,
'logits': final_layer_output,
}))
Prediction Prediction on TPU is an experimental feature to support large batch inference. It is not designed for latency-critical system. In addition, due to some usability issues, for prediction with small dataset, CPU .predict, i.e., creating a new TPUEstimator instance with use_tpu=False, might be more convenient.
Note: In contrast to TPU training/evaluation, the input_fn for prediction should raise an end-of-input exception (OutOfRangeError or StopIteration), which serves as the stopping signal to TPUEstimator. To be precise, the ops created by input_fn produce one batch of the data. The predict() API processes one batch at a time. When reaching the end of the data source, an end-of-input exception should be raised by one of these operations. The user usually does not need to do this manually. As long as the dataset is not repeated forever, the tf.data API will raise an end-of-input exception automatically after the last batch has been produced.
Note: Estimator.predict returns a Python generator. Please consume all the data from the generator so that TPUEstimator can shutdown the TPU system properly for user.
Current limitations: TPU prediction only works on a single host (one TPU worker). input_fn must return a Dataset instance rather than features. In fact, .train() and .evaluate() also support Dataset as return value. Example (MNIST): height = 32
width = 32
total_examples = 100
def predict_input_fn(params):
batch_size = params['batch_size']
images = tf.random.uniform(
[total_examples, height, width, 3], minval=-1, maxval=1)
dataset = tf.data.Dataset.from_tensor_slices(images)
dataset = dataset.map(lambda images: {'image': images})
dataset = dataset.batch(batch_size)
return dataset
def model_fn(features, labels, params, mode):
# Generate predictions, called 'output', from features['image']
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions={
'predictions': output,
'is_padding': features['is_padding']
})
tpu_est = TPUEstimator(
model_fn=model_fn,
...,
predict_batch_size=16)
# Fully consume the generator so that TPUEstimator can shutdown the TPU
# system.
for item in tpu_est.predict(input_fn=input_fn):
# Filter out item if the `is_padding` is 1.
# Process the 'predictions'
Exporting export_saved_model exports 2 metagraphs, one with saved_model.SERVING, and another with saved_model.SERVING and saved_model.TPU tags. At serving time, these tags are used to select the appropriate metagraph to load. Before running the graph on TPU, the TPU system needs to be initialized. If TensorFlow Serving model-server is used, this is done automatically. If not, please use session.run(tpu.initialize_system()). There are two versions of the API: 1 or 2. In V1, the exported CPU graph is model_fn as it is. The exported TPU graph wraps tpu.rewrite() and TPUPartitionedCallOp around model_fn so model_fn is on TPU by default. To place ops on CPU, tpu.outside_compilation(host_call, logits) can be used. Example: def model_fn(features, labels, mode, config, params):
...
logits = ...
export_outputs = {
'logits': export_output_lib.PredictOutput(
{'logits': logits})
}
def host_call(logits):
class_ids = math_ops.argmax(logits)
classes = string_ops.as_string(class_ids)
export_outputs['classes'] =
export_output_lib.ClassificationOutput(classes=classes)
tpu.outside_compilation(host_call, logits)
...
In V2, export_saved_model() sets up params['use_tpu'] flag to let the user know if the code is exporting to TPU (or not). When params['use_tpu'] is True, users need to call tpu.rewrite(), TPUPartitionedCallOp and/or batch_function(). Alternatively use inference_on_tpu() which is a convenience wrapper of the three. def model_fn(features, labels, mode, config, params):
...
# This could be some pre-processing on CPU like calls to input layer with
# embedding columns.
x2 = features['x'] * 2
def computation(input_tensor):
return layers.dense(
input_tensor, 1, kernel_initializer=init_ops.zeros_initializer())
inputs = [x2]
if params['use_tpu']:
predictions = array_ops.identity(
tpu_estimator.inference_on_tpu(computation, inputs,
num_batch_threads=1, max_batch_size=2, batch_timeout_micros=100),
name='predictions')
else:
predictions = array_ops.identity(
computation(*inputs), name='predictions')
key = signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY
export_outputs = {
key: export_lib.PredictOutput({'prediction': predictions})
}
...
TIP: V2 is recommended as it is more flexible (eg: batching, etc).
Args
model_fn Model function as required by Estimator which returns EstimatorSpec or TPUEstimatorSpec. training_hooks, 'evaluation_hooks', and prediction_hooks must not capure any TPU Tensor inside the model_fn.
model_dir Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. If None, the model_dir in config will be used if set. If both are set, they must be same. If both are None, a temporary directory will be used.
config An tpu_config.RunConfig configuration object. Cannot be None.
params An optional dict of hyper parameters that will be passed into input_fn and model_fn. Keys are names of parameters, values are basic python types. There are reserved keys for TPUEstimator, including 'batch_size'.
use_tpu A bool indicating whether TPU support is enabled. Currently, - TPU training and evaluation respect this bit, but eval_on_tpu can override execution of eval. See below.
train_batch_size An int representing the global training batch size. TPUEstimator transforms this global batch size to a per-shard batch size, as params['batch_size'], when calling input_fn and model_fn. Cannot be None if use_tpu is True. Must be divisible by total number of replicas.
eval_batch_size An int representing evaluation batch size. Must be divisible by total number of replicas.
predict_batch_size An int representing the prediction batch size. Must be divisible by total number of replicas.
batch_axis A python tuple of int values describing how each tensor produced by the Estimator input_fn should be split across the TPU compute shards. For example, if your input_fn produced (images, labels) where the images tensor is in HWCN format, your shard dimensions would be [3, 0], where 3 corresponds to the N dimension of your images Tensor, and 0 corresponds to the dimension along which to split the labels to match up with the corresponding images. If None is supplied, and per_host_input_for_training is True, batches will be sharded based on the major dimension. If tpu_config.per_host_input_for_training is False or PER_HOST_V2, batch_axis is ignored.
eval_on_tpu If False, evaluation runs on CPU or GPU. In this case, the model_fn must return EstimatorSpec when called with mode as EVAL.
export_to_tpu If True, export_saved_model() exports a metagraph for serving on TPU. Note that unsupported export modes such as EVAL will be ignored. For those modes, only a CPU model will be exported. Currently, export_to_tpu only supports PREDICT.
export_to_cpu If True, export_saved_model() exports a metagraph for serving on CPU.
warm_start_from Optional string filepath to a checkpoint or SavedModel to warm-start from, or a tf.estimator.WarmStartSettings object to fully configure warm-starting. If the string filepath is provided instead of a WarmStartSettings, then all variables are warm-started, and it is assumed that vocabularies and Tensor names are unchanged.
embedding_config_spec Optional EmbeddingConfigSpec instance to support using TPU embedding.
export_saved_model_api_version an integer: 1 or 2. 1 corresponds to V1, 2 corresponds to V2. (Defaults to V1). With V1, export_saved_model() adds rewrite() and TPUPartitionedCallOp() for user; while in v2, user is expected to add rewrite(), TPUPartitionedCallOp() etc in their model_fn. A helper function inference_on_tpu is provided for V2. brn_tpu_estimator.py includes examples for both versions i.e. TPUEstimatorExportTest and TPUEstimatorExportV2Test.
Raises
ValueError params has reserved keys already.
Attributes
config
model_dir
model_fn Returns the model_fn which is bound to self.params.
params
Methods eval_dir View source
eval_dir(
name=None
)
Shows the directory name where evaluation metrics are dumped.
Args
name Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.
Returns A string which is the path of directory contains evaluation metrics.
evaluate View source
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
Evaluates the model given evaluation data input_fn. For each step, calls input_fn, which returns one batch of data. Evaluates until:
steps batches are processed, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).
Args
input_fn A function that constructs the input data for evaluation. See Premade Estimators for more information. The function should construct and return one of the following: A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.
steps Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
hooks List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the evaluation call.
checkpoint_path Path of a specific checkpoint to evaluate. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, evaluation is run with newly initialized Variables instead of ones restored from checkpoint.
name Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.
Returns A dict containing the evaluation metrics specified in model_fn keyed by name, as well as an entry global_step which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the loss (mean loss per mini-batch) and the average_loss (mean loss per sample). Canned classifiers also return the accuracy. Canned regressors also return the label/mean and the prediction/mean.
Raises
ValueError If steps <= 0. experimental_export_all_saved_models View source
experimental_export_all_saved_models(
export_dir_base, input_receiver_fn_map, assets_extra=None, as_text=False,
checkpoint_path=None
)
Exports a SavedModel with tf.MetaGraphDefs for each requested mode. For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory. For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures. For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
Args
export_dir_base A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
input_receiver_fn_map dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
assets_extra A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
as_text whether to write the SavedModel proto in text format.
checkpoint_path The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
Returns The path to the exported directory as a bytes object.
Raises
ValueError if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found. export_saved_model View source
export_saved_model(
export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
Exports inference graph as a SavedModel into the given dir. For a detailed guide, see SavedModel from Estimators. This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session. The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}. The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
Args
export_dir_base A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
serving_input_receiver_fn A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
assets_extra A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
as_text whether to write the SavedModel proto in text format.
checkpoint_path The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
experimental_mode tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.
Returns The path to the exported directory as a bytes object.
Raises
ValueError if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found. export_savedmodel View source
export_savedmodel(
export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
checkpoint_path=None, strip_default_attrs=False
)
Exports inference graph as a SavedModel into the given dir. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This function has been renamed, use export_saved_model instead. For a detailed guide, see SavedModel from Estimators. This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session. The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn. Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
Args
export_dir_base A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
serving_input_receiver_fn A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
assets_extra A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
as_text whether to write the SavedModel proto in text format.
checkpoint_path The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
strip_default_attrs Boolean. If True, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see Stripping Default-Valued Attributes.
Returns The path to the exported directory as a bytes object.
Raises
ValueError if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found. get_variable_names View source
get_variable_names()
Returns list of all variable names in this model.
Returns List of names.
Raises
ValueError If the Estimator has not produced a checkpoint yet. get_variable_value View source
get_variable_value(
name
)
Returns value of the variable given by name.
Args
name string or a list of string, name of the tensor.
Returns Numpy array - value of the tensor.
Raises
ValueError If the Estimator has not produced a checkpoint yet. latest_checkpoint View source
latest_checkpoint()
Finds the filename of the latest saved checkpoint file in model_dir.
Returns The full path to the latest checkpoint or None if no checkpoint was found.
predict View source
predict(
input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
yield_single_examples=True
)
Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506
Args
input_fn A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.
predict_keys list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
hooks List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
checkpoint_path Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
yield_single_examples If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.
Yields Evaluated values of predictions tensors.
Raises
ValueError If batch length of predictions is not the same and yield_single_examples is True.
ValueError If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict. train View source
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
Trains a model given training data input_fn.
Args
input_fn A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following: A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.
hooks List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
steps Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
max_steps Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
saving_listeners list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.
Returns self, for chaining.
Raises
ValueError If both steps and max_steps are not None.
ValueError If either steps or max_steps <= 0. | |
doc_42 | Prompt the user for a password without echoing. The user is prompted using the string prompt, which defaults to 'Password: '. On Unix, the prompt is written to the file-like object stream using the replace error handler if needed. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows). If echo free input is unavailable getpass() falls back to printing a warning message to stream and reading from sys.stdin and issuing a GetPassWarning. Note If you call getpass from within IDLE, the input may be done in the terminal you launched IDLE from rather than the idle window itself. | |
doc_43 | exception os.error
An alias for the built-in OSError exception.
os.name
The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'. See also sys.platform has a finer granularity. os.uname() gives system-dependent version information. The platform module provides detailed checks for the system’s identity.
File Names, Command Line Arguments, and Environment Variables In Python, file names, command line arguments, and environment variables are represented using the string type. On some systems, decoding these strings to and from bytes is necessary before passing them to the operating system. Python uses the file system encoding to perform this conversion (see sys.getfilesystemencoding()). Changed in version 3.1: On some systems, conversion using the file system encoding may fail. In this case, Python uses the surrogateescape encoding error handler, which means that undecodable bytes are replaced by a Unicode character U+DCxx on decoding, and these are again translated to the original byte on encoding. The file system encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions may raise UnicodeErrors. Process Parameters These functions and data items provide information and operate on the current process and user.
os.ctermid()
Return the filename corresponding to the controlling terminal of the process. Availability: Unix.
os.environ
A mapping object representing the string environment. For example, environ['HOME'] is the pathname of your home directory (on some platforms), and is equivalent to getenv("HOME") in C. This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly. This mapping may be used to modify the environment as well as query the environment. putenv() will be called automatically when the mapping is modified. On Unix, keys and values use sys.getfilesystemencoding() and 'surrogateescape' error handler. Use environb if you would like to use a different encoding. Note Calling putenv() directly does not change os.environ, so it’s better to modify os.environ. Note On some platforms, including FreeBSD and Mac OS X, setting environ may cause memory leaks. Refer to the system documentation for putenv(). You can delete items in this mapping to unset environment variables. unsetenv() will be called automatically when an item is deleted from os.environ, and when one of the pop() or clear() methods is called. Changed in version 3.9: Updated to support PEP 584’s merge (|) and update (|=) operators.
os.environb
Bytes version of environ: a mapping object representing the environment as byte strings. environ and environb are synchronized (modify environb updates environ, and vice versa). environb is only available if supports_bytes_environ is True. New in version 3.2. Changed in version 3.9: Updated to support PEP 584’s merge (|) and update (|=) operators.
os.chdir(path)
os.fchdir(fd)
os.getcwd()
These functions are described in Files and Directories.
os.fsencode(filename)
Encode path-like filename to the filesystem encoding with 'surrogateescape' error handler, or 'strict' on Windows; return bytes unchanged. fsdecode() is the reverse function. New in version 3.2. Changed in version 3.6: Support added to accept objects implementing the os.PathLike interface.
os.fsdecode(filename)
Decode the path-like filename from the filesystem encoding with 'surrogateescape' error handler, or 'strict' on Windows; return str unchanged. fsencode() is the reverse function. New in version 3.2. Changed in version 3.6: Support added to accept objects implementing the os.PathLike interface.
os.fspath(path)
Return the file system representation of the path. If str or bytes is passed in, it is returned unchanged. Otherwise __fspath__() is called and its value is returned as long as it is a str or bytes object. In all other cases, TypeError is raised. New in version 3.6.
class os.PathLike
An abstract base class for objects representing a file system path, e.g. pathlib.PurePath. New in version 3.6.
abstractmethod __fspath__()
Return the file system path representation of the object. The method should only return a str or bytes object, with the preference being for str.
os.getenv(key, default=None)
Return the value of the environment variable key if it exists, or default if it doesn’t. key, default and the result are str. On Unix, keys and values are decoded with sys.getfilesystemencoding() and 'surrogateescape' error handler. Use os.getenvb() if you would like to use a different encoding. Availability: most flavors of Unix, Windows.
os.getenvb(key, default=None)
Return the value of the environment variable key if it exists, or default if it doesn’t. key, default and the result are bytes. getenvb() is only available if supports_bytes_environ is True. Availability: most flavors of Unix. New in version 3.2.
os.get_exec_path(env=None)
Returns the list of directories that will be searched for a named executable, similar to a shell, when launching a process. env, when specified, should be an environment variable dictionary to lookup the PATH in. By default, when env is None, environ is used. New in version 3.2.
os.getegid()
Return the effective group id of the current process. This corresponds to the “set id” bit on the file being executed in the current process. Availability: Unix.
os.geteuid()
Return the current process’s effective user id. Availability: Unix.
os.getgid()
Return the real group id of the current process. Availability: Unix.
os.getgrouplist(user, group)
Return list of group ids that user belongs to. If group is not in the list, it is included; typically, group is specified as the group ID field from the password record for user. Availability: Unix. New in version 3.3.
os.getgroups()
Return list of supplemental group ids associated with the current process. Availability: Unix. Note On Mac OS X, getgroups() behavior differs somewhat from other Unix platforms. If the Python interpreter was built with a deployment target of 10.5 or earlier, getgroups() returns the list of effective group ids associated with the current user process; this list is limited to a system-defined number of entries, typically 16, and may be modified by calls to setgroups() if suitably privileged. If built with a deployment target greater than 10.5, getgroups() returns the current group access list for the user associated with the effective user id of the process; the group access list may change over the lifetime of the process, it is not affected by calls to setgroups(), and its length is not limited to 16. The deployment target value, MACOSX_DEPLOYMENT_TARGET, can be obtained with sysconfig.get_config_var().
os.getlogin()
Return the name of the user logged in on the controlling terminal of the process. For most purposes, it is more useful to use getpass.getuser() since the latter checks the environment variables LOGNAME or USERNAME to find out who the user is, and falls back to pwd.getpwuid(os.getuid())[0] to get the login name of the current real user id. Availability: Unix, Windows.
os.getpgid(pid)
Return the process group id of the process with process id pid. If pid is 0, the process group id of the current process is returned. Availability: Unix.
os.getpgrp()
Return the id of the current process group. Availability: Unix.
os.getpid()
Return the current process id.
os.getppid()
Return the parent’s process id. When the parent process has exited, on Unix the id returned is the one of the init process (1), on Windows it is still the same id, which may be already reused by another process. Availability: Unix, Windows. Changed in version 3.2: Added support for Windows.
os.getpriority(which, who)
Get program scheduling priority. The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. Availability: Unix. New in version 3.3.
os.PRIO_PROCESS
os.PRIO_PGRP
os.PRIO_USER
Parameters for the getpriority() and setpriority() functions. Availability: Unix. New in version 3.3.
os.getresuid()
Return a tuple (ruid, euid, suid) denoting the current process’s real, effective, and saved user ids. Availability: Unix. New in version 3.2.
os.getresgid()
Return a tuple (rgid, egid, sgid) denoting the current process’s real, effective, and saved group ids. Availability: Unix. New in version 3.2.
os.getuid()
Return the current process’s real user id. Availability: Unix.
os.initgroups(username, gid)
Call the system initgroups() to initialize the group access list with all of the groups of which the specified username is a member, plus the specified group id. Availability: Unix. New in version 3.2.
os.putenv(key, value)
Set the environment variable named key to the string value. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv(). Assignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to putenv() don’t update os.environ, so it is actually preferable to assign to items of os.environ. Note On some platforms, including FreeBSD and Mac OS X, setting environ may cause memory leaks. Refer to the system documentation for putenv(). Raises an auditing event os.putenv with arguments key, value. Changed in version 3.9: The function is now always available.
os.setegid(egid)
Set the current process’s effective group id. Availability: Unix.
os.seteuid(euid)
Set the current process’s effective user id. Availability: Unix.
os.setgid(gid)
Set the current process’ group id. Availability: Unix.
os.setgroups(groups)
Set the list of supplemental group ids associated with the current process to groups. groups must be a sequence, and each element must be an integer identifying a group. This operation is typically available only to the superuser. Availability: Unix. Note On Mac OS X, the length of groups may not exceed the system-defined maximum number of effective group ids, typically 16. See the documentation for getgroups() for cases where it may not return the same group list set by calling setgroups().
os.setpgrp()
Call the system call setpgrp() or setpgrp(0, 0) depending on which version is implemented (if any). See the Unix manual for the semantics. Availability: Unix.
os.setpgid(pid, pgrp)
Call the system call setpgid() to set the process group id of the process with id pid to the process group with id pgrp. See the Unix manual for the semantics. Availability: Unix.
os.setpriority(which, who, priority)
Set program scheduling priority. The value which is one of PRIO_PROCESS, PRIO_PGRP, or PRIO_USER, and who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER). A zero value for who denotes (respectively) the calling process, the process group of the calling process, or the real user ID of the calling process. priority is a value in the range -20 to 19. The default priority is 0; lower priorities cause more favorable scheduling. Availability: Unix. New in version 3.3.
os.setregid(rgid, egid)
Set the current process’s real and effective group ids. Availability: Unix.
os.setresgid(rgid, egid, sgid)
Set the current process’s real, effective, and saved group ids. Availability: Unix. New in version 3.2.
os.setresuid(ruid, euid, suid)
Set the current process’s real, effective, and saved user ids. Availability: Unix. New in version 3.2.
os.setreuid(ruid, euid)
Set the current process’s real and effective user ids. Availability: Unix.
os.getsid(pid)
Call the system call getsid(). See the Unix manual for the semantics. Availability: Unix.
os.setsid()
Call the system call setsid(). See the Unix manual for the semantics. Availability: Unix.
os.setuid(uid)
Set the current process’s user id. Availability: Unix.
os.strerror(code)
Return the error message corresponding to the error code in code. On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.
os.supports_bytes_environ
True if the native OS type of the environment is bytes (eg. False on Windows). New in version 3.2.
os.umask(mask)
Set the current numeric umask and return the previous umask.
os.uname()
Returns information identifying the current operating system. The return value is an object with five attributes:
sysname - operating system name
nodename - name of machine on network (implementation-defined)
release - operating system release
version - operating system version
machine - hardware identifier For backwards compatibility, this object is also iterable, behaving like a five-tuple containing sysname, nodename, release, version, and machine in that order. Some systems truncate nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()). Availability: recent flavors of Unix. Changed in version 3.3: Return type changed from a tuple to a tuple-like object with named attributes.
os.unsetenv(key)
Unset (delete) the environment variable named key. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv(). Deletion of items in os.environ is automatically translated into a corresponding call to unsetenv(); however, calls to unsetenv() don’t update os.environ, so it is actually preferable to delete items of os.environ. Raises an auditing event os.unsetenv with argument key. Changed in version 3.9: The function is now always available and is also available on Windows.
File Object Creation These functions create new file objects. (See also open() for opening file descriptors.)
os.fdopen(fd, *args, **kwargs)
Return an open file object connected to the file descriptor fd. This is an alias of the open() built-in function and accepts the same arguments. The only difference is that the first argument of fdopen() must always be an integer.
File Descriptor Operations These functions operate on I/O streams referenced using file descriptors. File descriptors are small integers corresponding to a file that has been opened by the current process. For example, standard input is usually file descriptor 0, standard output is 1, and standard error is 2. Further files opened by a process will then be assigned 3, 4, 5, and so forth. The name “file descriptor” is slightly deceptive; on Unix platforms, sockets and pipes are also referenced by file descriptors. The fileno() method can be used to obtain the file descriptor associated with a file object when required. Note that using the file descriptor directly will bypass the file object methods, ignoring aspects such as internal buffering of data.
os.close(fd)
Close file descriptor fd. Note This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To close a “file object” returned by the built-in function open() or by popen() or fdopen(), use its close() method.
os.closerange(fd_low, fd_high)
Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors. Equivalent to (but much faster than): for fd in range(fd_low, fd_high):
try:
os.close(fd)
except OSError:
pass
os.copy_file_range(src, dst, count, offset_src=None, offset_dst=None)
Copy count bytes from file descriptor src, starting from offset offset_src, to file descriptor dst, starting from offset offset_dst. If offset_src is None, then src is read from the current position; respectively for offset_dst. The files pointed by src and dst must reside in the same filesystem, otherwise an OSError is raised with errno set to errno.EXDEV. This copy is done without the additional cost of transferring data from the kernel to user space and then back into the kernel. Additionally, some filesystems could implement extra optimizations. The copy is done as if both files are opened as binary. The return value is the amount of bytes copied. This could be less than the amount requested. Availability: Linux kernel >= 4.5 or glibc >= 2.27. New in version 3.8.
os.device_encoding(fd)
Return a string describing the encoding of the device associated with fd if it is connected to a terminal; else return None.
os.dup(fd)
Return a duplicate of file descriptor fd. The new file descriptor is non-inheritable. On Windows, when duplicating a standard stream (0: stdin, 1: stdout, 2: stderr), the new file descriptor is inheritable. Changed in version 3.4: The new file descriptor is now non-inheritable.
os.dup2(fd, fd2, inheritable=True)
Duplicate file descriptor fd to fd2, closing the latter first if necessary. Return fd2. The new file descriptor is inheritable by default or non-inheritable if inheritable is False. Changed in version 3.4: Add the optional inheritable parameter. Changed in version 3.7: Return fd2 on success. Previously, None was always returned.
os.fchmod(fd, mode)
Change the mode of the file given by fd to the numeric mode. See the docs for chmod() for possible values of mode. As of Python 3.3, this is equivalent to os.chmod(fd, mode). Raises an auditing event os.chmod with arguments path, mode, dir_fd. Availability: Unix.
os.fchown(fd, uid, gid)
Change the owner and group id of the file given by fd to the numeric uid and gid. To leave one of the ids unchanged, set it to -1. See chown(). As of Python 3.3, this is equivalent to os.chown(fd, uid,
gid). Raises an auditing event os.chown with arguments path, uid, gid, dir_fd. Availability: Unix.
os.fdatasync(fd)
Force write of file with filedescriptor fd to disk. Does not force update of metadata. Availability: Unix. Note This function is not available on MacOS.
os.fpathconf(fd, name)
Return system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted. If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in pathconf_names, an OSError is raised with errno.EINVAL for the error number. As of Python 3.3, this is equivalent to os.pathconf(fd, name). Availability: Unix.
os.fstat(fd)
Get the status of the file descriptor fd. Return a stat_result object. As of Python 3.3, this is equivalent to os.stat(fd). See also The stat() function.
os.fstatvfs(fd)
Return information about the filesystem containing the file associated with file descriptor fd, like statvfs(). As of Python 3.3, this is equivalent to os.statvfs(fd). Availability: Unix.
os.fsync(fd)
Force write of file with filedescriptor fd to disk. On Unix, this calls the native fsync() function; on Windows, the MS _commit() function. If you’re starting with a buffered Python file object f, first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk. Availability: Unix, Windows.
os.ftruncate(fd, length)
Truncate the file corresponding to file descriptor fd, so that it is at most length bytes in size. As of Python 3.3, this is equivalent to os.truncate(fd, length). Raises an auditing event os.truncate with arguments fd, length. Availability: Unix, Windows. Changed in version 3.5: Added support for Windows
os.get_blocking(fd)
Get the blocking mode of the file descriptor: False if the O_NONBLOCK flag is set, True if the flag is cleared. See also set_blocking() and socket.socket.setblocking(). Availability: Unix. New in version 3.5.
os.isatty(fd)
Return True if the file descriptor fd is open and connected to a tty(-like) device, else False.
os.lockf(fd, cmd, len)
Apply, test or remove a POSIX lock on an open file descriptor. fd is an open file descriptor. cmd specifies the command to use - one of F_LOCK, F_TLOCK, F_ULOCK or F_TEST. len specifies the section of the file to lock. Raises an auditing event os.lockf with arguments fd, cmd, len. Availability: Unix. New in version 3.3.
os.F_LOCK
os.F_TLOCK
os.F_ULOCK
os.F_TEST
Flags that specify what action lockf() will take. Availability: Unix. New in version 3.3.
os.lseek(fd, pos, how)
Set the current position of file descriptor fd to position pos, modified by how: SEEK_SET or 0 to set the position relative to the beginning of the file; SEEK_CUR or 1 to set it relative to the current position; SEEK_END or 2 to set it relative to the end of the file. Return the new cursor position in bytes, starting from the beginning.
os.SEEK_SET
os.SEEK_CUR
os.SEEK_END
Parameters to the lseek() function. Their values are 0, 1, and 2, respectively. New in version 3.3: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA.
os.open(path, flags, mode=0o777, *, dir_fd=None)
Open the file path and set various flags according to flags and possibly its mode according to mode. When computing mode, the current umask value is first masked out. Return the file descriptor for the newly opened file. The new file descriptor is non-inheritable. For a description of the flag and mode values, see the C run-time documentation; flag constants (like O_RDONLY and O_WRONLY) are defined in the os module. In particular, on Windows adding O_BINARY is needed to open files in binary mode. This function can support paths relative to directory descriptors with the dir_fd parameter. Raises an auditing event open with arguments path, mode, flags. Changed in version 3.4: The new file descriptor is now non-inheritable. Note This function is intended for low-level I/O. For normal usage, use the built-in function open(), which returns a file object with read() and write() methods (and many more). To wrap a file descriptor in a file object, use fdopen(). New in version 3.3: The dir_fd argument. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). Changed in version 3.6: Accepts a path-like object.
The following constants are options for the flags parameter to the open() function. They can be combined using the bitwise OR operator |. Some of them are not available on all platforms. For descriptions of their availability and use, consult the open(2) manual page on Unix or the MSDN on Windows.
os.O_RDONLY
os.O_WRONLY
os.O_RDWR
os.O_APPEND
os.O_CREAT
os.O_EXCL
os.O_TRUNC
The above constants are available on Unix and Windows.
os.O_DSYNC
os.O_RSYNC
os.O_SYNC
os.O_NDELAY
os.O_NONBLOCK
os.O_NOCTTY
os.O_CLOEXEC
The above constants are only available on Unix. Changed in version 3.3: Add O_CLOEXEC constant.
os.O_BINARY
os.O_NOINHERIT
os.O_SHORT_LIVED
os.O_TEMPORARY
os.O_RANDOM
os.O_SEQUENTIAL
os.O_TEXT
The above constants are only available on Windows.
os.O_ASYNC
os.O_DIRECT
os.O_DIRECTORY
os.O_NOFOLLOW
os.O_NOATIME
os.O_PATH
os.O_TMPFILE
os.O_SHLOCK
os.O_EXLOCK
The above constants are extensions and not present if they are not defined by the C library. Changed in version 3.4: Add O_PATH on systems that support it. Add O_TMPFILE, only available on Linux Kernel 3.11 or newer.
os.openpty()
Open a new pseudo-terminal pair. Return a pair of file descriptors (master, slave) for the pty and the tty, respectively. The new file descriptors are non-inheritable. For a (slightly) more portable approach, use the pty module. Availability: some flavors of Unix. Changed in version 3.4: The new file descriptors are now non-inheritable.
os.pipe()
Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. The new file descriptor is non-inheritable. Availability: Unix, Windows. Changed in version 3.4: The new file descriptors are now non-inheritable.
os.pipe2(flags)
Create a pipe with flags set atomically. flags can be constructed by ORing together one or more of these values: O_NONBLOCK, O_CLOEXEC. Return a pair of file descriptors (r, w) usable for reading and writing, respectively. Availability: some flavors of Unix. New in version 3.3.
os.posix_fallocate(fd, offset, len)
Ensures that enough disk space is allocated for the file specified by fd starting from offset and continuing for len bytes. Availability: Unix. New in version 3.3.
os.posix_fadvise(fd, offset, len, advice)
Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations. The advice applies to the region of the file specified by fd starting at offset and continuing for len bytes. advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED or POSIX_FADV_DONTNEED. Availability: Unix. New in version 3.3.
os.POSIX_FADV_NORMAL
os.POSIX_FADV_SEQUENTIAL
os.POSIX_FADV_RANDOM
os.POSIX_FADV_NOREUSE
os.POSIX_FADV_WILLNEED
os.POSIX_FADV_DONTNEED
Flags that can be used in advice in posix_fadvise() that specify the access pattern that is likely to be used. Availability: Unix. New in version 3.3.
os.pread(fd, n, offset)
Read at most n bytes from file descriptor fd at a position of offset, leaving the file offset unchanged. Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned. Availability: Unix. New in version 3.3.
os.preadv(fd, buffers, offset, flags=0)
Read from a file descriptor fd at a position of offset into mutable bytes-like objects buffers, leaving the file offset unchanged. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data. The flags argument contains a bitwise OR of zero or more of the following flags: RWF_HIPRI RWF_NOWAIT Return the total number of bytes actually read which can be less than the total capacity of all the objects. The operating system may set a limit (sysconf() value 'SC_IOV_MAX') on the number of buffers that can be used. Combine the functionality of os.readv() and os.pread(). Availability: Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires Linux 4.6 or newer. New in version 3.7.
os.RWF_NOWAIT
Do not wait for data which is not immediately available. If this flag is specified, the system call will return instantly if it would have to read data from the backing storage or wait for a lock. If some data was successfully read, it will return the number of bytes read. If no bytes were read, it will return -1 and set errno to errno.EAGAIN. Availability: Linux 4.14 and newer. New in version 3.7.
os.RWF_HIPRI
High priority read/write. Allows block-based filesystems to use polling of the device, which provides lower latency, but may use additional resources. Currently, on Linux, this feature is usable only on a file descriptor opened using the O_DIRECT flag. Availability: Linux 4.6 and newer. New in version 3.7.
os.pwrite(fd, str, offset)
Write the bytestring in str to file descriptor fd at position of offset, leaving the file offset unchanged. Return the number of bytes actually written. Availability: Unix. New in version 3.3.
os.pwritev(fd, buffers, offset, flags=0)
Write the buffers contents to file descriptor fd at a offset offset, leaving the file offset unchanged. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on. The flags argument contains a bitwise OR of zero or more of the following flags: RWF_DSYNC RWF_SYNC Return the total number of bytes actually written. The operating system may set a limit (sysconf() value 'SC_IOV_MAX') on the number of buffers that can be used. Combine the functionality of os.writev() and os.pwrite(). Availability: Linux 2.6.30 and newer, FreeBSD 6.0 and newer, OpenBSD 2.7 and newer, AIX 7.1 and newer. Using flags requires Linux 4.7 or newer. New in version 3.7.
os.RWF_DSYNC
Provide a per-write equivalent of the O_DSYNC open(2) flag. This flag effect applies only to the data range written by the system call. Availability: Linux 4.7 and newer. New in version 3.7.
os.RWF_SYNC
Provide a per-write equivalent of the O_SYNC open(2) flag. This flag effect applies only to the data range written by the system call. Availability: Linux 4.7 and newer. New in version 3.7.
os.read(fd, n)
Read at most n bytes from file descriptor fd. Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned. Note This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To read a “file object” returned by the built-in function open() or by popen() or fdopen(), or sys.stdin, use its read() or readline() methods. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
os.sendfile(out_fd, in_fd, offset, count)
os.sendfile(out_fd, in_fd, offset, count, headers=(), trailers=(), flags=0)
Copy count bytes from file descriptor in_fd to file descriptor out_fd starting at offset. Return the number of bytes sent. When EOF is reached return 0. The first function notation is supported by all platforms that define sendfile(). On Linux, if offset is given as None, the bytes are read from the current position of in_fd and the position of in_fd is updated. The second case may be used on Mac OS X and FreeBSD where headers and trailers are arbitrary sequences of buffers that are written before and after the data from in_fd is written. It returns the same as the first case. On Mac OS X and FreeBSD, a value of 0 for count specifies to send until the end of in_fd is reached. All platforms support sockets as out_fd file descriptor, and some platforms allow other types (e.g. regular file, pipe) as well. Cross-platform applications should not use headers, trailers and flags arguments. Availability: Unix. Note For a higher-level wrapper of sendfile(), see socket.socket.sendfile(). New in version 3.3. Changed in version 3.9: Parameters out and in was renamed to out_fd and in_fd.
os.set_blocking(fd, blocking)
Set the blocking mode of the specified file descriptor. Set the O_NONBLOCK flag if blocking is False, clear the flag otherwise. See also get_blocking() and socket.socket.setblocking(). Availability: Unix. New in version 3.5.
os.SF_NODISKIO
os.SF_MNOWAIT
os.SF_SYNC
Parameters to the sendfile() function, if the implementation supports them. Availability: Unix. New in version 3.3.
os.readv(fd, buffers)
Read from a file descriptor fd into a number of mutable bytes-like objects buffers. Transfer data into each buffer until it is full and then move on to the next buffer in the sequence to hold the rest of the data. Return the total number of bytes actually read which can be less than the total capacity of all the objects. The operating system may set a limit (sysconf() value 'SC_IOV_MAX') on the number of buffers that can be used. Availability: Unix. New in version 3.3.
os.tcgetpgrp(fd)
Return the process group associated with the terminal given by fd (an open file descriptor as returned by os.open()). Availability: Unix.
os.tcsetpgrp(fd, pg)
Set the process group associated with the terminal given by fd (an open file descriptor as returned by os.open()) to pg. Availability: Unix.
os.ttyname(fd)
Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised. Availability: Unix.
os.write(fd, str)
Write the bytestring in str to file descriptor fd. Return the number of bytes actually written. Note This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To write a “file object” returned by the built-in function open() or by popen() or fdopen(), or sys.stdout or sys.stderr, use its write() method. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
os.writev(fd, buffers)
Write the contents of buffers to file descriptor fd. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on. Returns the total number of bytes actually written. The operating system may set a limit (sysconf() value 'SC_IOV_MAX') on the number of buffers that can be used. Availability: Unix. New in version 3.3.
Querying the size of a terminal New in version 3.3.
os.get_terminal_size(fd=STDOUT_FILENO)
Return the size of the terminal window as (columns, lines), tuple of type terminal_size. The optional argument fd (default STDOUT_FILENO, or standard output) specifies which file descriptor should be queried. If the file descriptor is not connected to a terminal, an OSError is raised. shutil.get_terminal_size() is the high-level function which should normally be used, os.get_terminal_size is the low-level implementation. Availability: Unix, Windows.
class os.terminal_size
A subclass of tuple, holding (columns, lines) of the terminal window size.
columns
Width of the terminal window in characters.
lines
Height of the terminal window in characters.
Inheritance of File Descriptors New in version 3.4. A file descriptor has an “inheritable” flag which indicates if the file descriptor can be inherited by child processes. Since Python 3.4, file descriptors created by Python are non-inheritable by default. On UNIX, non-inheritable file descriptors are closed in child processes at the execution of a new program, other file descriptors are inherited. On Windows, non-inheritable handles and file descriptors are closed in child processes, except for standard streams (file descriptors 0, 1 and 2: stdin, stdout and stderr), which are always inherited. Using spawn* functions, all inheritable handles and all inheritable file descriptors are inherited. Using the subprocess module, all file descriptors except standard streams are closed, and inheritable handles are only inherited if the close_fds parameter is False.
os.get_inheritable(fd)
Get the “inheritable” flag of the specified file descriptor (a boolean).
os.set_inheritable(fd, inheritable)
Set the “inheritable” flag of the specified file descriptor.
os.get_handle_inheritable(handle)
Get the “inheritable” flag of the specified handle (a boolean). Availability: Windows.
os.set_handle_inheritable(handle, inheritable)
Set the “inheritable” flag of the specified handle. Availability: Windows.
Files and Directories On some Unix platforms, many of these functions support one or more of these features:
specifying a file descriptor: Normally the path argument provided to functions in the os module must be a string specifying a file path. However, some functions now alternatively accept an open file descriptor for their path argument. The function will then operate on the file referred to by the descriptor. (For POSIX systems, Python will call the variant of the function prefixed with f (e.g. call fchdir instead of chdir).) You can check whether or not path can be specified as a file descriptor for a particular function on your platform using os.supports_fd. If this functionality is unavailable, using it will raise a NotImplementedError. If the function also supports dir_fd or follow_symlinks arguments, it’s an error to specify one of those when supplying path as a file descriptor.
paths relative to directory descriptors: If dir_fd is not None, it should be a file descriptor referring to a directory, and the path to operate on should be relative; path will then be relative to that directory. If the path is absolute, dir_fd is ignored. (For POSIX systems, Python will call the variant of the function with an at suffix and possibly prefixed with f (e.g. call faccessat instead of access). You can check whether or not dir_fd is supported for a particular function on your platform using os.supports_dir_fd. If it’s unavailable, using it will raise a NotImplementedError.
not following symlinks: If follow_symlinks is False, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call the l... variant of the function.) You can check whether or not follow_symlinks is supported for a particular function on your platform using os.supports_follow_symlinks. If it’s unavailable, using it will raise a NotImplementedError.
os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)
Use the real uid/gid to test for access to path. Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path. mode should be F_OK to test the existence of path, or it can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions. Return True if access is allowed, False if not. See the Unix man page access(2) for more information. This function can support specifying paths relative to directory descriptors and not following symlinks. If effective_ids is True, access() will perform its access checks using the effective uid/gid instead of the real uid/gid. effective_ids may not be supported on your platform; you can check whether or not it is available using os.supports_effective_ids. If it is unavailable, using it will raise a NotImplementedError. Note Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example: if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
return "some default data"
is better written as: try:
fp = open("myfile")
except PermissionError:
return "some default data"
else:
with fp:
return fp.read()
Note I/O operations may fail even when access() indicates that they would succeed, particularly for operations on network filesystems which may have permissions semantics beyond the usual POSIX permission-bit model. Changed in version 3.3: Added the dir_fd, effective_ids, and follow_symlinks parameters. Changed in version 3.6: Accepts a path-like object.
os.F_OK
os.R_OK
os.W_OK
os.X_OK
Values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path, respectively.
os.chdir(path)
Change the current working directory to path. This function can support specifying a file descriptor. The descriptor must refer to an opened directory, not an open file. This function can raise OSError and subclasses such as FileNotFoundError, PermissionError, and NotADirectoryError. Raises an auditing event os.chdir with argument path. New in version 3.3: Added support for specifying path as a file descriptor on some platforms. Changed in version 3.6: Accepts a path-like object.
os.chflags(path, flags, *, follow_symlinks=True)
Set the flags of path to the numeric flags. flags may take a combination (bitwise OR) of the following values (as defined in the stat module): stat.UF_NODUMP stat.UF_IMMUTABLE stat.UF_APPEND stat.UF_OPAQUE stat.UF_NOUNLINK stat.UF_COMPRESSED stat.UF_HIDDEN stat.SF_ARCHIVED stat.SF_IMMUTABLE stat.SF_APPEND stat.SF_NOUNLINK stat.SF_SNAPSHOT This function can support not following symlinks. Raises an auditing event os.chflags with arguments path, flags. Availability: Unix. New in version 3.3: The follow_symlinks argument. Changed in version 3.6: Accepts a path-like object.
os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
Change the mode of path to the numeric mode. mode may take one of the following values (as defined in the stat module) or bitwise ORed combinations of them: stat.S_ISUID stat.S_ISGID stat.S_ENFMT stat.S_ISVTX stat.S_IREAD stat.S_IWRITE stat.S_IEXEC stat.S_IRWXU stat.S_IRUSR stat.S_IWUSR stat.S_IXUSR stat.S_IRWXG stat.S_IRGRP stat.S_IWGRP stat.S_IXGRP stat.S_IRWXO stat.S_IROTH stat.S_IWOTH stat.S_IXOTH This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks. Note Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored. Raises an auditing event os.chmod with arguments path, mode, dir_fd. New in version 3.3: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments. Changed in version 3.6: Accepts a path-like object.
os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)
Change the owner and group id of path to the numeric uid and gid. To leave one of the ids unchanged, set it to -1. This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks. See shutil.chown() for a higher-level function that accepts names in addition to numeric ids. Raises an auditing event os.chown with arguments path, uid, gid, dir_fd. Availability: Unix. New in version 3.3: Added support for specifying path as an open file descriptor, and the dir_fd and follow_symlinks arguments. Changed in version 3.6: Supports a path-like object.
os.chroot(path)
Change the root directory of the current process to path. Availability: Unix. Changed in version 3.6: Accepts a path-like object.
os.fchdir(fd)
Change the current working directory to the directory represented by the file descriptor fd. The descriptor must refer to an opened directory, not an open file. As of Python 3.3, this is equivalent to os.chdir(fd). Raises an auditing event os.chdir with argument path. Availability: Unix.
os.getcwd()
Return a string representing the current working directory.
os.getcwdb()
Return a bytestring representing the current working directory. Changed in version 3.8: The function now uses the UTF-8 encoding on Windows, rather than the ANSI code page: see PEP 529 for the rationale. The function is no longer deprecated on Windows.
os.lchflags(path, flags)
Set the flags of path to the numeric flags, like chflags(), but do not follow symbolic links. As of Python 3.3, this is equivalent to os.chflags(path, flags, follow_symlinks=False). Raises an auditing event os.chflags with arguments path, flags. Availability: Unix. Changed in version 3.6: Accepts a path-like object.
os.lchmod(path, mode)
Change the mode of path to the numeric mode. If path is a symlink, this affects the symlink rather than the target. See the docs for chmod() for possible values of mode. As of Python 3.3, this is equivalent to os.chmod(path, mode, follow_symlinks=False). Raises an auditing event os.chmod with arguments path, mode, dir_fd. Availability: Unix. Changed in version 3.6: Accepts a path-like object.
os.lchown(path, uid, gid)
Change the owner and group id of path to the numeric uid and gid. This function will not follow symbolic links. As of Python 3.3, this is equivalent to os.chown(path, uid, gid, follow_symlinks=False). Raises an auditing event os.chown with arguments path, uid, gid, dir_fd. Availability: Unix. Changed in version 3.6: Accepts a path-like object.
os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)
Create a hard link pointing to src named dst. This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors, and not following symlinks. Raises an auditing event os.link with arguments src, dst, src_dir_fd, dst_dir_fd. Availability: Unix, Windows. Changed in version 3.2: Added Windows support. New in version 3.3: Added the src_dir_fd, dst_dir_fd, and follow_symlinks arguments. Changed in version 3.6: Accepts a path-like object for src and dst.
os.listdir(path='.')
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified. path may be a path-like object. If path is of type bytes (directly or indirectly through the PathLike interface), the filenames returned will also be of type bytes; in all other circumstances, they will be of type str. This function can also support specifying a file descriptor; the file descriptor must refer to a directory. Raises an auditing event os.listdir with argument path. Note To encode str filenames to bytes, use fsencode(). See also The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases. Changed in version 3.2: The path parameter became optional. New in version 3.3: Added support for specifying path as an open file descriptor. Changed in version 3.6: Accepts a path-like object.
os.lstat(path, *, dir_fd=None)
Perform the equivalent of an lstat() system call on the given path. Similar to stat(), but does not follow symbolic links. Return a stat_result object. On platforms that do not support symbolic links, this is an alias for stat(). As of Python 3.3, this is equivalent to os.stat(path, dir_fd=dir_fd,
follow_symlinks=False). This function can also support paths relative to directory descriptors. See also The stat() function. Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links. Changed in version 3.3: Added the dir_fd parameter. Changed in version 3.6: Accepts a path-like object. Changed in version 3.8: On Windows, now opens reparse points that represent another path (name surrogates), including symbolic links and directory junctions. Other kinds of reparse points are resolved by the operating system as for stat().
os.mkdir(path, mode=0o777, *, dir_fd=None)
Create a directory named path with numeric mode mode. If the directory already exists, FileExistsError is raised. On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If bits other than the last 9 (i.e. the last 3 digits of the octal representation of the mode) are set, their meaning is platform-dependent. On some platforms, they are ignored and you should call chmod() explicitly to set them. This function can also support paths relative to directory descriptors. It is also possible to create temporary directories; see the tempfile module’s tempfile.mkdtemp() function. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.3: The dir_fd argument. Changed in version 3.6: Accepts a path-like object.
os.makedirs(name, mode=0o777, exist_ok=False)
Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. Note makedirs() will become confused if the path elements to create include pardir (eg. “..” on UNIX systems). This function handles UNC paths correctly. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.2: The exist_ok parameter. Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.
os.mkfifo(path, mode=0o666, *, dir_fd=None)
Create a FIFO (a named pipe) named path with numeric mode mode. The current umask value is first masked out from the mode. This function can also support paths relative to directory descriptors. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted (for example with os.unlink()). Generally, FIFOs are used as rendezvous between “client” and “server” type processes: the server opens the FIFO for reading, and the client opens it for writing. Note that mkfifo() doesn’t open the FIFO — it just creates the rendezvous point. Availability: Unix. New in version 3.3: The dir_fd argument. Changed in version 3.6: Accepts a path-like object.
os.mknod(path, mode=0o600, device=0, *, dir_fd=None)
Create a filesystem node (file, device special file or named pipe) named path. mode specifies both the permissions to use and the type of node to be created, being combined (bitwise OR) with one of stat.S_IFREG, stat.S_IFCHR, stat.S_IFBLK, and stat.S_IFIFO (those constants are available in stat). For stat.S_IFCHR and stat.S_IFBLK, device defines the newly created device special file (probably using os.makedev()), otherwise it is ignored. This function can also support paths relative to directory descriptors. Availability: Unix. New in version 3.3: The dir_fd argument. Changed in version 3.6: Accepts a path-like object.
os.major(device)
Extract the device major number from a raw device number (usually the st_dev or st_rdev field from stat).
os.minor(device)
Extract the device minor number from a raw device number (usually the st_dev or st_rdev field from stat).
os.makedev(major, minor)
Compose a raw device number from the major and minor device numbers.
os.pathconf(path, name)
Return system configuration information relevant to a named file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given in the pathconf_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted. If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in pathconf_names, an OSError is raised with errno.EINVAL for the error number. This function can support specifying a file descriptor. Availability: Unix. Changed in version 3.6: Accepts a path-like object.
os.pathconf_names
Dictionary mapping names accepted by pathconf() and fpathconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system. Availability: Unix.
os.readlink(path, *, dir_fd=None)
Return a string representing the path to which the symbolic link points. The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using os.path.join(os.path.dirname(path), result). If the path is a string object (directly or indirectly through a PathLike interface), the result will also be a string object, and the call may raise a UnicodeDecodeError. If the path is a bytes object (direct or indirectly), the result will be a bytes object. This function can also support paths relative to directory descriptors. When trying to resolve a path that may contain links, use realpath() to properly handle recursion and platform differences. Availability: Unix, Windows. Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links. New in version 3.3: The dir_fd argument. Changed in version 3.6: Accepts a path-like object on Unix. Changed in version 3.8: Accepts a path-like object and a bytes object on Windows. Changed in version 3.8: Added support for directory junctions, and changed to return the substitution path (which typically includes \\?\ prefix) rather than the optional “print name” field that was previously returned.
os.remove(path, *, dir_fd=None)
Remove (delete) the file path. If path is a directory, an IsADirectoryError is raised. Use rmdir() to remove directories. If the file does not exist, a FileNotFoundError is raised. This function can support paths relative to directory descriptors. On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use. This function is semantically identical to unlink(). Raises an auditing event os.remove with arguments path, dir_fd. New in version 3.3: The dir_fd argument. Changed in version 3.6: Accepts a path-like object.
os.removedirs(name)
Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed. Raises an auditing event os.remove with arguments path, dir_fd. Changed in version 3.6: Accepts a path-like object.
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases: On Windows, if dst exists a FileExistsError is always raised. On Unix, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors. If you want cross-platform overwriting of the destination, use replace(). Raises an auditing event os.rename with arguments src, dst, src_dir_fd, dst_dir_fd. New in version 3.3: The src_dir_fd and dst_dir_fd arguments. Changed in version 3.6: Accepts a path-like object for src and dst.
os.renames(old, new)
Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using removedirs(). Note This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file. Raises an auditing event os.rename with arguments src, dst, src_dir_fd, dst_dir_fd. Changed in version 3.6: Accepts a path-like object for old and new.
os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
Rename the file or directory src to dst. If dst is a directory, OSError will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors. Raises an auditing event os.rename with arguments src, dst, src_dir_fd, dst_dir_fd. New in version 3.3. Changed in version 3.6: Accepts a path-like object for src and dst.
os.rmdir(path, *, dir_fd=None)
Remove (delete) the directory path. If the directory does not exist or is not empty, an FileNotFoundError or an OSError is raised respectively. In order to remove whole directory trees, shutil.rmtree() can be used. This function can support paths relative to directory descriptors. Raises an auditing event os.rmdir with arguments path, dir_fd. New in version 3.3: The dir_fd parameter. Changed in version 3.6: Accepts a path-like object.
os.scandir(path='.')
Return an iterator of os.DirEntry objects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries '.' and '..' are not included. If a file is removed from or added to the directory after creating the iterator, whether an entry for that file be included is unspecified. Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows. path may be a path-like object. If path is of type bytes (directly or indirectly through the PathLike interface), the type of the name and path attributes of each os.DirEntry will be bytes; in all other circumstances, they will be of type str. This function can also support specifying a file descriptor; the file descriptor must refer to a directory. Raises an auditing event os.scandir with argument path. The scandir() iterator supports the context manager protocol and has the following method:
scandir.close()
Close the iterator and free acquired resources. This is called automatically when the iterator is exhausted or garbage collected, or when an error happens during iterating. However it is advisable to call it explicitly or use the with statement. New in version 3.6.
The following example shows a simple use of scandir() to display all the files (excluding directories) in the given path that don’t start with '.'. The entry.is_file() call will generally not make an additional system call: with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)
Note On Unix-based systems, scandir() uses the system’s opendir() and readdir() functions. On Windows, it uses the Win32 FindFirstFileW and FindNextFileW functions. New in version 3.5. New in version 3.6: Added support for the context manager protocol and the close() method. If a scandir() iterator is neither exhausted nor explicitly closed a ResourceWarning will be emitted in its destructor. The function accepts a path-like object. Changed in version 3.7: Added support for file descriptors on Unix.
class os.DirEntry
Object yielded by scandir() to expose the file path and other file attributes of a directory entry. scandir() will provide as much of this information as possible without making additional system calls. When a stat() or lstat() system call is made, the os.DirEntry object will cache the result. os.DirEntry instances are not intended to be stored in long-lived data structures; if you know the file metadata has changed or if a long time has elapsed since calling scandir(), call os.stat(entry.path) to fetch up-to-date information. Because the os.DirEntry methods can make operating system calls, they may also raise OSError. If you need very fine-grained control over errors, you can catch OSError when calling one of the os.DirEntry methods and handle as appropriate. To be directly usable as a path-like object, os.DirEntry implements the PathLike interface. Attributes and methods on a os.DirEntry instance are as follows:
name
The entry’s base filename, relative to the scandir() path argument. The name attribute will be bytes if the scandir() path argument is of type bytes and str otherwise. Use fsdecode() to decode byte filenames.
path
The entry’s full path name: equivalent to os.path.join(scandir_path,
entry.name) where scandir_path is the scandir() path argument. The path is only absolute if the scandir() path argument was absolute. If the scandir() path argument was a file descriptor, the path attribute is the same as the name attribute. The path attribute will be bytes if the scandir() path argument is of type bytes and str otherwise. Use fsdecode() to decode byte filenames.
inode()
Return the inode number of the entry. The result is cached on the os.DirEntry object. Use os.stat(entry.path, follow_symlinks=False).st_ino to fetch up-to-date information. On the first, uncached call, a system call is required on Windows but not on Unix.
is_dir(*, follow_symlinks=True)
Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore. If follow_symlinks is False, return True only if this entry is a directory (without following symlinks); return False if the entry is any other kind of file or if it doesn’t exist anymore. The result is cached on the os.DirEntry object, with a separate cache for follow_symlinks True and False. Call os.stat() along with stat.S_ISDIR() to fetch up-to-date information. On the first, uncached call, no system call is required in most cases. Specifically, for non-symlinks, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return dirent.d_type == DT_UNKNOWN. If the entry is a symlink, a system call will be required to follow the symlink unless follow_symlinks is False. This method can raise OSError, such as PermissionError, but FileNotFoundError is caught and not raised.
is_file(*, follow_symlinks=True)
Return True if this entry is a file or a symbolic link pointing to a file; return False if the entry is or points to a directory or other non-file entry, or if it doesn’t exist anymore. If follow_symlinks is False, return True only if this entry is a file (without following symlinks); return False if the entry is a directory or other non-file entry, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. Caching, system calls made, and exceptions raised are as per is_dir().
is_symlink()
Return True if this entry is a symbolic link (even if broken); return False if the entry points to a directory or any kind of file, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. Call os.path.islink() to fetch up-to-date information. On the first, uncached call, no system call is required in most cases. Specifically, neither Windows or Unix require a system call, except on certain Unix file systems, such as network file systems, that return dirent.d_type == DT_UNKNOWN. This method can raise OSError, such as PermissionError, but FileNotFoundError is caught and not raised.
stat(*, follow_symlinks=True)
Return a stat_result object for this entry. This method follows symbolic links by default; to stat a symbolic link add the follow_symlinks=False argument. On Unix, this method always requires a system call. On Windows, it only requires a system call if follow_symlinks is True and the entry is a reparse point (for example, a symbolic link or directory junction). On Windows, the st_ino, st_dev and st_nlink attributes of the stat_result are always set to zero. Call os.stat() to get these attributes. The result is cached on the os.DirEntry object, with a separate cache for follow_symlinks True and False. Call os.stat() to fetch up-to-date information.
Note that there is a nice correspondence between several attributes and methods of os.DirEntry and of pathlib.Path. In particular, the name attribute has the same meaning, as do the is_dir(), is_file(), is_symlink() and stat() methods. New in version 3.5. Changed in version 3.6: Added support for the PathLike interface. Added support for bytes paths on Windows.
os.stat(path, *, dir_fd=None, follow_symlinks=True)
Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the PathLike interface – or as an open file descriptor. Return a stat_result object. This function normally follows symlinks; to stat a symlink add the argument follow_symlinks=False, or use lstat(). This function can support specifying a file descriptor and not following symlinks. On Windows, passing follow_symlinks=False will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use the os.path.realpath() function to resolve the path name as far as possible and call lstat() on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions. Example: >>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264
See also fstat() and lstat() functions. New in version 3.3: Added the dir_fd and follow_symlinks arguments, specifying a file descriptor instead of a path. Changed in version 3.6: Accepts a path-like object. Changed in version 3.8: On Windows, all reparse points that can be resolved by the operating system are now followed, and passing follow_symlinks=False disables following all name surrogate reparse points. If the operating system reaches a reparse point that it is not able to follow, stat now returns the information for the original path as if follow_symlinks=False had been specified instead of raising an error.
class os.stat_result
Object whose attributes correspond roughly to the members of the stat structure. It is used for the result of os.stat(), os.fstat() and os.lstat(). Attributes:
st_mode
File mode: file type and file mode bits (permissions).
st_ino
Platform dependent, but if non-zero, uniquely identifies the file for a given value of st_dev. Typically: the inode number on Unix, the file index on Windows
st_dev
Identifier of the device on which this file resides.
st_nlink
Number of hard links.
st_uid
User identifier of the file owner.
st_gid
Group identifier of the file owner.
st_size
Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.
Timestamps:
st_atime
Time of most recent access expressed in seconds.
st_mtime
Time of most recent content modification expressed in seconds.
st_ctime
Platform dependent: the time of most recent metadata change on Unix, the time of creation on Windows, expressed in seconds.
st_atime_ns
Time of most recent access expressed in nanoseconds as an integer.
st_mtime_ns
Time of most recent content modification expressed in nanoseconds as an integer.
st_ctime_ns
Platform dependent: the time of most recent metadata change on Unix, the time of creation on Windows, expressed in nanoseconds as an integer.
Note The exact meaning and resolution of the st_atime, st_mtime, and st_ctime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details. Similarly, although st_atime_ns, st_mtime_ns, and st_ctime_ns are always expressed in nanoseconds, many systems do not provide nanosecond precision. On systems that do provide nanosecond precision, the floating-point object used to store st_atime, st_mtime, and st_ctime cannot preserve all of it, and as such will be slightly inexact. If you need the exact timestamps you should always use st_atime_ns, st_mtime_ns, and st_ctime_ns. On some Unix systems (such as Linux), the following attributes may also be available:
st_blocks
Number of 512-byte blocks allocated for file. This may be smaller than st_size/512 when the file has holes.
st_blksize
“Preferred” blocksize for efficient file system I/O. Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.
st_rdev
Type of device if an inode device.
st_flags
User defined flags for file.
On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them):
st_gen
File generation number.
st_birthtime
Time of file creation.
On Solaris and derivatives, the following attributes may also be available:
st_fstype
String that uniquely identifies the type of the filesystem that contains the file.
On Mac OS systems, the following attributes may also be available:
st_rsize
Real size of the file.
st_creator
Creator of the file.
st_type
File type.
On Windows systems, the following attributes are also available:
st_file_attributes
Windows file attributes: dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle(). See the FILE_ATTRIBUTE_* constants in the stat module.
st_reparse_tag
When st_file_attributes has the FILE_ATTRIBUTE_REPARSE_POINT set, this field contains the tag identifying the type of reparse point. See the IO_REPARSE_TAG_* constants in the stat module.
The standard module stat defines functions and constants that are useful for extracting information from a stat structure. (On Windows, some items are filled with dummy values.) For backward compatibility, a stat_result instance is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. More items may be added at the end by some implementations. For compatibility with older Python versions, accessing stat_result as a tuple always returns integers. New in version 3.3: Added the st_atime_ns, st_mtime_ns, and st_ctime_ns members. New in version 3.5: Added the st_file_attributes member on Windows. Changed in version 3.5: Windows now returns the file index as st_ino when available. New in version 3.7: Added the st_fstype member to Solaris/derivatives. New in version 3.8: Added the st_reparse_tag member on Windows. Changed in version 3.8: On Windows, the st_mode member now identifies special files as S_IFCHR, S_IFIFO or S_IFBLK as appropriate.
os.statvfs(path)
Perform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax, f_fsid. Two module-level constants are defined for the f_flag attribute’s bit-flags: if ST_RDONLY is set, the filesystem is mounted read-only, and if ST_NOSUID is set, the semantics of setuid/setgid bits are disabled or not supported. Additional module-level constants are defined for GNU/glibc based systems. These are ST_NODEV (disallow access to device special files), ST_NOEXEC (disallow program execution), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file/directory/symlink), ST_APPEND (append-only file), ST_IMMUTABLE (immutable file), ST_NOATIME (do not update access times), ST_NODIRATIME (do not update directory access times), ST_RELATIME (update atime relative to mtime/ctime). This function can support specifying a file descriptor. Availability: Unix. Changed in version 3.2: The ST_RDONLY and ST_NOSUID constants were added. New in version 3.3: Added support for specifying path as an open file descriptor. Changed in version 3.4: The ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS, ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIME, and ST_RELATIME constants were added. Changed in version 3.6: Accepts a path-like object. New in version 3.7: Added f_fsid.
os.supports_dir_fd
A set object indicating which functions in the os module accept an open file descriptor for their dir_fd parameter. Different platforms provide different features, and the underlying functionality Python uses to implement the dir_fd parameter is not available on all platforms Python supports. For consistency’s sake, functions that may support dir_fd always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying None for dir_fd is always supported on all platforms.) To check whether a particular function accepts an open file descriptor for its dir_fd parameter, use the in operator on supports_dir_fd. As an example, this expression evaluates to True if os.stat() accepts open file descriptors for dir_fd on the local platform: os.stat in os.supports_dir_fd
Currently dir_fd parameters only work on Unix platforms; none of them work on Windows. New in version 3.3.
os.supports_effective_ids
A set object indicating whether os.access() permits specifying True for its effective_ids parameter on the local platform. (Specifying False for effective_ids is always supported on all platforms.) If the local platform supports it, the collection will contain os.access(); otherwise it will be empty. This expression evaluates to True if os.access() supports effective_ids=True on the local platform: os.access in os.supports_effective_ids
Currently effective_ids is only supported on Unix platforms; it does not work on Windows. New in version 3.3.
os.supports_fd
A set object indicating which functions in the os module permit specifying their path parameter as an open file descriptor on the local platform. Different platforms provide different features, and the underlying functionality Python uses to accept open file descriptors as path arguments is not available on all platforms Python supports. To determine whether a particular function permits specifying an open file descriptor for its path parameter, use the in operator on supports_fd. As an example, this expression evaluates to True if os.chdir() accepts open file descriptors for path on your local platform: os.chdir in os.supports_fd
New in version 3.3.
os.supports_follow_symlinks
A set object indicating which functions in the os module accept False for their follow_symlinks parameter on the local platform. Different platforms provide different features, and the underlying functionality Python uses to implement follow_symlinks is not available on all platforms Python supports. For consistency’s sake, functions that may support follow_symlinks always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying True for follow_symlinks is always supported on all platforms.) To check whether a particular function accepts False for its follow_symlinks parameter, use the in operator on supports_follow_symlinks. As an example, this expression evaluates to True if you may specify follow_symlinks=False when calling os.stat() on the local platform: os.stat in os.supports_follow_symlinks
New in version 3.3.
os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)
Create a symbolic link pointing to src named dst. On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is True or a file symlink (the default) otherwise. On non-Windows platforms, target_is_directory is ignored. This function can support paths relative to directory descriptors. Note On newer versions of Windows 10, unprivileged accounts can create symlinks if Developer Mode is enabled. When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator. OSError is raised when the function is called by an unprivileged user. Raises an auditing event os.symlink with arguments src, dst, dir_fd. Availability: Unix, Windows. Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links. New in version 3.3: Added the dir_fd argument, and now allow target_is_directory on non-Windows platforms. Changed in version 3.6: Accepts a path-like object for src and dst. Changed in version 3.8: Added support for unelevated symlinks on Windows with Developer Mode.
os.sync()
Force write of everything to disk. Availability: Unix. New in version 3.3.
os.truncate(path, length)
Truncate the file corresponding to path, so that it is at most length bytes in size. This function can support specifying a file descriptor. Raises an auditing event os.truncate with arguments path, length. Availability: Unix, Windows. New in version 3.3. Changed in version 3.5: Added support for Windows Changed in version 3.6: Accepts a path-like object.
os.unlink(path, *, dir_fd=None)
Remove (delete) the file path. This function is semantically identical to remove(); the unlink name is its traditional Unix name. Please see the documentation for remove() for further information. Raises an auditing event os.remove with arguments path, dir_fd. New in version 3.3: The dir_fd parameter. Changed in version 3.6: Accepts a path-like object.
os.utime(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True)
Set the access and modified times of the file specified by path. utime() takes two optional parameters, times and ns. These specify the times set on path and are used as follows: If ns is specified, it must be a 2-tuple of the form (atime_ns, mtime_ns) where each member is an int expressing nanoseconds. If times is not None, it must be a 2-tuple of the form (atime, mtime) where each member is an int or float expressing seconds. If times is None and ns is unspecified, this is equivalent to specifying ns=(atime_ns, mtime_ns) where both times are the current time. It is an error to specify tuples for both times and ns. Note that the exact times you set here may not be returned by a subsequent stat() call, depending on the resolution with which your operating system records access and modification times; see stat(). The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from the os.stat() result object with the ns parameter to utime. This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks. Raises an auditing event os.utime with arguments path, times, ns, dir_fd. New in version 3.3: Added support for specifying path as an open file descriptor, and the dir_fd, follow_symlinks, and ns parameters. Changed in version 3.6: Accepts a path-like object.
os.walk(top, topdown=True, onerror=None, followlinks=False)
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames,
filenames). dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified. If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated. By default, errors from the scandir() call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them. Note Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already. Note If you pass a relative pathname, don’t change the current working directory between resumptions of walk(). walk() never changes the current directory, and assumes that its caller doesn’t either. This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory: import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end=" ")
print(sum(getsize(join(root, name)) for name in files), end=" ")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
In the next example (simple implementation of shutil.rmtree()), walking the tree bottom-up is essential, rmdir() doesn’t allow deleting a directory before the directory is empty: # Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
Raises an auditing event os.walk with arguments top, topdown, onerror, followlinks. Changed in version 3.5: This function now calls os.scandir() instead of os.listdir(), making it faster by reducing the number of calls to os.stat(). Changed in version 3.6: Accepts a path-like object.
os.fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)
This behaves exactly like walk(), except that it yields a 4-tuple (dirpath, dirnames, filenames, dirfd), and it supports dir_fd. dirpath, dirnames and filenames are identical to walk() output, and dirfd is a file descriptor referring to the directory dirpath. This function always supports paths relative to directory descriptors and not following symlinks. Note however that, unlike other functions, the fwalk() default value for follow_symlinks is False. Note Since fwalk() yields file descriptors, those are only valid until the next iteration step, so you should duplicate them (e.g. with dup()) if you want to keep them longer. This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory: import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
print(root, "consumes", end="")
print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
end="")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
In the next example, walking the tree bottom-up is essential: rmdir() doesn’t allow deleting a directory before the directory is empty: # Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
for name in files:
os.unlink(name, dir_fd=rootfd)
for name in dirs:
os.rmdir(name, dir_fd=rootfd)
Raises an auditing event os.fwalk with arguments top, topdown, onerror, follow_symlinks, dir_fd. Availability: Unix. New in version 3.3. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: Added support for bytes paths.
os.memfd_create(name[, flags=os.MFD_CLOEXEC])
Create an anonymous file and return a file descriptor that refers to it. flags must be one of the os.MFD_* constants available on the system (or a bitwise ORed combination of them). By default, the new file descriptor is non-inheritable. The name supplied in name is used as a filename and will be displayed as the target of the corresponding symbolic link in the directory /proc/self/fd/. The displayed name is always prefixed with memfd: and serves only for debugging purposes. Names do not affect the behavior of the file descriptor, and as such multiple files can have the same name without any side effects. Availability: Linux 3.17 or newer with glibc 2.27 or newer. New in version 3.8.
os.MFD_CLOEXEC
os.MFD_ALLOW_SEALING
os.MFD_HUGETLB
os.MFD_HUGE_SHIFT
os.MFD_HUGE_MASK
os.MFD_HUGE_64KB
os.MFD_HUGE_512KB
os.MFD_HUGE_1MB
os.MFD_HUGE_2MB
os.MFD_HUGE_8MB
os.MFD_HUGE_16MB
os.MFD_HUGE_32MB
os.MFD_HUGE_256MB
os.MFD_HUGE_512MB
os.MFD_HUGE_1GB
os.MFD_HUGE_2GB
os.MFD_HUGE_16GB
These flags can be passed to memfd_create(). Availability: Linux 3.17 or newer with glibc 2.27 or newer. The MFD_HUGE* flags are only available since Linux 4.14. New in version 3.8.
Linux extended attributes New in version 3.3. These functions are all available on Linux only.
os.getxattr(path, attribute, *, follow_symlinks=True)
Return the value of the extended filesystem attribute attribute for path. attribute can be bytes or str (directly or indirectly through the PathLike interface). If it is str, it is encoded with the filesystem encoding. This function can support specifying a file descriptor and not following symlinks. Raises an auditing event os.getxattr with arguments path, attribute. Changed in version 3.6: Accepts a path-like object for path and attribute.
os.listxattr(path=None, *, follow_symlinks=True)
Return a list of the extended filesystem attributes on path. The attributes in the list are represented as strings decoded with the filesystem encoding. If path is None, listxattr() will examine the current directory. This function can support specifying a file descriptor and not following symlinks. Raises an auditing event os.listxattr with argument path. Changed in version 3.6: Accepts a path-like object.
os.removexattr(path, attribute, *, follow_symlinks=True)
Removes the extended filesystem attribute attribute from path. attribute should be bytes or str (directly or indirectly through the PathLike interface). If it is a string, it is encoded with the filesystem encoding. This function can support specifying a file descriptor and not following symlinks. Raises an auditing event os.removexattr with arguments path, attribute. Changed in version 3.6: Accepts a path-like object for path and attribute.
os.setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)
Set the extended filesystem attribute attribute on path to value. attribute must be a bytes or str with no embedded NULs (directly or indirectly through the PathLike interface). If it is a str, it is encoded with the filesystem encoding. flags may be XATTR_REPLACE or XATTR_CREATE. If XATTR_REPLACE is given and the attribute does not exist, EEXISTS will be raised. If XATTR_CREATE is given and the attribute already exists, the attribute will not be created and ENODATA will be raised. This function can support specifying a file descriptor and not following symlinks. Note A bug in Linux kernel versions less than 2.6.39 caused the flags argument to be ignored on some filesystems. Raises an auditing event os.setxattr with arguments path, attribute, value, flags. Changed in version 3.6: Accepts a path-like object for path and attribute.
os.XATTR_SIZE_MAX
The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.
os.XATTR_CREATE
This is a possible value for the flags argument in setxattr(). It indicates the operation must create an attribute.
os.XATTR_REPLACE
This is a possible value for the flags argument in setxattr(). It indicates the operation must replace an existing attribute.
Process Management These functions may be used to create and manage processes. The various exec* functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this is the argv[0] passed to a program’s main(). For example, os.execv('/bin/echo',
['foo', 'bar']) will only print bar on standard output; foo will seem to be ignored.
os.abort()
Generate a SIGABRT signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of 3. Be aware that calling this function will not call the Python signal handler registered for SIGABRT with signal.signal().
os.add_dll_directory(path)
Add a path to the DLL search path. This search path is used when resolving dependencies for imported extension modules (the module itself is resolved through sys.path), and also by ctypes. Remove the directory by calling close() on the returned object or using it in a with statement. See the Microsoft documentation for more information about how DLLs are loaded. Raises an auditing event os.add_dll_directory with argument path. Availability: Windows. New in version 3.8: Previous versions of CPython would resolve DLLs using the default behavior for the current process. This led to inconsistencies, such as only sometimes searching PATH or the current working directory, and OS functions such as AddDllDirectory having no effect. In 3.8, the two primary ways DLLs are loaded now explicitly override the process-wide behavior to ensure consistency. See the porting notes for information on updating libraries.
os.execl(path, arg0, arg1, ...)
os.execle(path, arg0, arg1, ..., env)
os.execlp(file, arg0, arg1, ...)
os.execlpe(file, arg0, arg1, ..., env)
os.execv(path, args)
os.execve(path, args, env)
os.execvp(file, args)
os.execvpe(file, args, env)
These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions. The current process is replaced immediately. Open file objects and descriptors are not flushed, so if there may be data buffered on these open files, you should flush them using sys.stdout.flush() or os.fsync() before calling an exec* function. The “l” and “v” variants of the exec* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the execl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process should start with the name of the command being run, but this is not enforced. The variants which include a “p” near the end (execlp(), execlpe(), execvp(), and execvpe()) will use the PATH environment variable to locate the program file. When the environment is being replaced (using one of the exec*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, execl(), execle(), execv(), and execve(), will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path. For execle(), execlpe(), execve(), and execvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (these are used instead of the current process’ environment); the functions execl(), execlp(), execv(), and execvp() all cause the new process to inherit the environment of the current process. For execve() on some platforms, path may also be specified as an open file descriptor. This functionality may not be supported on your platform; you can check whether or not it is available using os.supports_fd. If it is unavailable, using it will raise a NotImplementedError. Raises an auditing event os.exec with arguments path, args, env. Availability: Unix, Windows. New in version 3.3: Added support for specifying path as an open file descriptor for execve(). Changed in version 3.6: Accepts a path-like object.
os._exit(n)
Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc. Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork().
The following exit codes are defined and can be used with _exit(), although they are not required. These are typically used for system programs written in Python, such as a mail server’s external command delivery program. Note Some of these may not be available on all Unix platforms, since there is some variation. These constants are defined where they are defined by the underlying platform.
os.EX_OK
Exit code that means no error occurred. Availability: Unix.
os.EX_USAGE
Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given. Availability: Unix.
os.EX_DATAERR
Exit code that means the input data was incorrect. Availability: Unix.
os.EX_NOINPUT
Exit code that means an input file did not exist or was not readable. Availability: Unix.
os.EX_NOUSER
Exit code that means a specified user did not exist. Availability: Unix.
os.EX_NOHOST
Exit code that means a specified host did not exist. Availability: Unix.
os.EX_UNAVAILABLE
Exit code that means that a required service is unavailable. Availability: Unix.
os.EX_SOFTWARE
Exit code that means an internal software error was detected. Availability: Unix.
os.EX_OSERR
Exit code that means an operating system error was detected, such as the inability to fork or create a pipe. Availability: Unix.
os.EX_OSFILE
Exit code that means some system file did not exist, could not be opened, or had some other kind of error. Availability: Unix.
os.EX_CANTCREAT
Exit code that means a user specified output file could not be created. Availability: Unix.
os.EX_IOERR
Exit code that means that an error occurred while doing I/O on some file. Availability: Unix.
os.EX_TEMPFAIL
Exit code that means a temporary failure occurred. This indicates something that may not really be an error, such as a network connection that couldn’t be made during a retryable operation. Availability: Unix.
os.EX_PROTOCOL
Exit code that means that a protocol exchange was illegal, invalid, or not understood. Availability: Unix.
os.EX_NOPERM
Exit code that means that there were insufficient permissions to perform the operation (but not intended for file system problems). Availability: Unix.
os.EX_CONFIG
Exit code that means that some kind of configuration error occurred. Availability: Unix.
os.EX_NOTFOUND
Exit code that means something like “an entry was not found”. Availability: Unix.
os.fork()
Fork a child process. Return 0 in the child and the child’s process id in the parent. If an error occurs OSError is raised. Note that some platforms including FreeBSD <= 6.3 and Cygwin have known issues when using fork() from a thread. Raises an auditing event os.fork with no arguments. Changed in version 3.8: Calling fork() in a subinterpreter is no longer supported (RuntimeError is raised). Warning See ssl for applications that use the SSL module with fork(). Availability: Unix.
os.forkpty()
Fork a child process, using a new pseudo-terminal as the child’s controlling terminal. Return a pair of (pid, fd), where pid is 0 in the child, the new child’s process id in the parent, and fd is the file descriptor of the master end of the pseudo-terminal. For a more portable approach, use the pty module. If an error occurs OSError is raised. Raises an auditing event os.forkpty with no arguments. Changed in version 3.8: Calling forkpty() in a subinterpreter is no longer supported (RuntimeError is raised). Availability: some flavors of Unix.
os.kill(pid, sig)
Send signal sig to the process pid. Constants for the specific signals available on the host platform are defined in the signal module. Windows: The signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT signals are special signals which can only be sent to console processes which share a common console window, e.g., some subprocesses. Any other value for sig will cause the process to be unconditionally killed by the TerminateProcess API, and the exit code will be set to sig. The Windows version of kill() additionally takes process handles to be killed. See also signal.pthread_kill(). Raises an auditing event os.kill with arguments pid, sig. New in version 3.2: Windows support.
os.killpg(pgid, sig)
Send the signal sig to the process group pgid. Raises an auditing event os.killpg with arguments pgid, sig. Availability: Unix.
os.nice(increment)
Add increment to the process’s “niceness”. Return the new niceness. Availability: Unix.
os.pidfd_open(pid, flags=0)
Return a file descriptor referring to the process pid. This descriptor can be used to perform process management without races and signals. The flags argument is provided for future extensions; no flag values are currently defined. See the pidfd_open(2) man page for more details. Availability: Linux 5.3+ New in version 3.9.
os.plock(op)
Lock program segments into memory. The value of op (defined in <sys/lock.h>) determines which segments are locked. Availability: Unix.
os.popen(cmd, mode='r', buffering=-1)
Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The buffering argument has the same meaning as the corresponding argument to the built-in open() function. The returned file object reads or writes text strings rather than bytes. The close method returns None if the subprocess exited successfully, or the subprocess’s return code if there was an error. On POSIX systems, if the return code is positive it represents the return value of the process left-shifted by one byte. If the return code is negative, the process was terminated by the signal given by the negated value of the return code. (For example, the return value might be - signal.SIGKILL if the subprocess was killed.) On Windows systems, the return value contains the signed integer return code from the child process. On Unix, waitstatus_to_exitcode() can be used to convert the close method result (exit status) into an exit code if it is not None. On Windows, the close method result is directly the exit code (or None). This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses.
os.posix_spawn(path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)
Wraps the posix_spawn() C library API for use from Python. Most users should use subprocess.run() instead of posix_spawn(). The positional-only arguments path, args, and env are similar to execve(). The path parameter is the path to the executable file. The path should contain a directory. Use posix_spawnp() to pass an executable file without directory. The file_actions argument may be a sequence of tuples describing actions to take on specific file descriptors in the child process between the C library implementation’s fork() and exec() steps. The first item in each tuple must be one of the three type indicator listed below describing the remaining tuple elements:
os.POSIX_SPAWN_OPEN
(os.POSIX_SPAWN_OPEN, fd, path, flags, mode) Performs os.dup2(os.open(path, flags, mode), fd).
os.POSIX_SPAWN_CLOSE
(os.POSIX_SPAWN_CLOSE, fd) Performs os.close(fd).
os.POSIX_SPAWN_DUP2
(os.POSIX_SPAWN_DUP2, fd, new_fd) Performs os.dup2(fd, new_fd).
These tuples correspond to the C library posix_spawn_file_actions_addopen(), posix_spawn_file_actions_addclose(), and posix_spawn_file_actions_adddup2() API calls used to prepare for the posix_spawn() call itself. The setpgroup argument will set the process group of the child to the value specified. If the value specified is 0, the child’s process group ID will be made the same as its process ID. If the value of setpgroup is not set, the child will inherit the parent’s process group ID. This argument corresponds to the C library POSIX_SPAWN_SETPGROUP flag. If the resetids argument is True it will reset the effective UID and GID of the child to the real UID and GID of the parent process. If the argument is False, then the child retains the effective UID and GID of the parent. In either case, if the set-user-ID and set-group-ID permission bits are enabled on the executable file, their effect will override the setting of the effective UID and GID. This argument corresponds to the C library POSIX_SPAWN_RESETIDS flag. If the setsid argument is True, it will create a new session ID for posix_spawn. setsid requires POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP flag. Otherwise, NotImplementedError is raised. The setsigmask argument will set the signal mask to the signal set specified. If the parameter is not used, then the child inherits the parent’s signal mask. This argument corresponds to the C library POSIX_SPAWN_SETSIGMASK flag. The sigdef argument will reset the disposition of all signals in the set specified. This argument corresponds to the C library POSIX_SPAWN_SETSIGDEF flag. The scheduler argument must be a tuple containing the (optional) scheduler policy and an instance of sched_param with the scheduler parameters. A value of None in the place of the scheduler policy indicates that is not being provided. This argument is a combination of the C library POSIX_SPAWN_SETSCHEDPARAM and POSIX_SPAWN_SETSCHEDULER flags. Raises an auditing event os.posix_spawn with arguments path, argv, env. New in version 3.8. Availability: Unix.
os.posix_spawnp(path, argv, env, *, file_actions=None, setpgroup=None, resetids=False, setsid=False, setsigmask=(), setsigdef=(), scheduler=None)
Wraps the posix_spawnp() C library API for use from Python. Similar to posix_spawn() except that the system searches for the executable file in the list of directories specified by the PATH environment variable (in the same way as for execvp(3)). Raises an auditing event os.posix_spawn with arguments path, argv, env. New in version 3.8. Availability: See posix_spawn() documentation.
os.register_at_fork(*, before=None, after_in_parent=None, after_in_child=None)
Register callables to be executed when a new child process is forked using os.fork() or similar process cloning APIs. The parameters are optional and keyword-only. Each specifies a different call point.
before is a function called before forking a child process.
after_in_parent is a function called from the parent process after forking a child process.
after_in_child is a function called from the child process. These calls are only made if control is expected to return to the Python interpreter. A typical subprocess launch will not trigger them as the child is not going to re-enter the interpreter. Functions registered for execution before forking are called in reverse registration order. Functions registered for execution after forking (either in the parent or in the child) are called in registration order. Note that fork() calls made by third-party C code may not call those functions, unless it explicitly calls PyOS_BeforeFork(), PyOS_AfterFork_Parent() and PyOS_AfterFork_Child(). There is no way to unregister a function. Availability: Unix. New in version 3.7.
os.spawnl(mode, path, ...)
os.spawnle(mode, path, ..., env)
os.spawnlp(mode, file, ...)
os.spawnlpe(mode, file, ..., env)
os.spawnv(mode, path, args)
os.spawnve(mode, path, args, env)
os.spawnvp(mode, file, args)
os.spawnvpe(mode, file, args, env)
Execute the program path in a new process. (Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.) If mode is P_NOWAIT, this function returns the process id of the new process; if mode is P_WAIT, returns the process’s exit code if it exits normally, or -signal, where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the waitpid() function. Note on VxWorks, this function doesn’t return -signal when the new process is killed. Instead it raises OSError exception. The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run. The variants which include a second “p” near the end (spawnlp(), spawnlpe(), spawnvp(), and spawnvpe()) will use the PATH environment variable to locate the program file. When the environment is being replaced (using one of the spawn*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, spawnl(), spawnle(), spawnv(), and spawnve(), will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path. For spawnle(), spawnlpe(), spawnve(), and spawnvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions spawnl(), spawnlp(), spawnv(), and spawnvp() all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of 127. As an example, the following calls to spawnlp() and spawnvpe() are equivalent: import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
Raises an auditing event os.spawn with arguments mode, path, args, env. Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and spawnvpe() are not available on Windows. spawnle() and spawnve() are not thread-safe on Windows; we advise you to use the subprocess module instead. Changed in version 3.6: Accepts a path-like object.
os.P_NOWAIT
os.P_NOWAITO
Possible values for the mode parameter to the spawn* family of functions. If either of these values is given, the spawn*() functions will return as soon as the new process has been created, with the process id as the return value. Availability: Unix, Windows.
os.P_WAIT
Possible value for the mode parameter to the spawn* family of functions. If this is given as mode, the spawn*() functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or -signal if a signal kills the process. Availability: Unix, Windows.
os.P_DETACH
os.P_OVERLAY
Possible values for the mode parameter to the spawn* family of functions. These are less portable than those listed above. P_DETACH is similar to P_NOWAIT, but the new process is detached from the console of the calling process. If P_OVERLAY is used, the current process will be replaced; the spawn* function will not return. Availability: Windows.
os.startfile(path[, operation])
Start a file with its associated application. When operation is not specified or 'open', this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated. When another operation is given, it must be a “command verb” that specifies what should be done with the file. Common verbs documented by Microsoft are 'print' and 'edit' (to be used on files) as well as 'explore' and 'find' (to be used on directories). startfile() returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status. The path parameter is relative to the current directory. If you want to use an absolute path, make sure the first character is not a slash ('/'); the underlying Win32 ShellExecute() function doesn’t work if it is. Use the os.path.normpath() function to ensure that the path is properly encoded for Win32. To reduce interpreter startup overhead, the Win32 ShellExecute() function is not resolved until this function is first called. If the function cannot be resolved, NotImplementedError will be raised. Raises an auditing event os.startfile with arguments path, operation. Availability: Windows.
os.system(command)
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream. On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent. On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable COMSPEC: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation. The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes. On Unix, waitstatus_to_exitcode() can be used to convert the result (exit status) into an exit code. On Windows, the result is directly the exit code. Raises an auditing event os.system with argument command. Availability: Unix, Windows.
os.times()
Returns the current global process times. The return value is an object with five attributes:
user - user time
system - system time
children_user - user time of all child processes
children_system - system time of all child processes
elapsed - elapsed real time since a fixed point in the past For backwards compatibility, this object also behaves like a five-tuple containing user, system, children_user, children_system, and elapsed in that order. See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN on Windows. On Windows, only user and system are known; the other attributes are zero. Availability: Unix, Windows. Changed in version 3.3: Return type changed from a tuple to a tuple-like object with named attributes.
os.wait()
Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. waitstatus_to_exitcode() can be used to convert the exit status into an exit code. Availability: Unix. See also waitpid() can be used to wait for the completion of a specific child process and has more options.
os.waitid(idtype, id, options)
Wait for the completion of one or more child processes. idtype can be P_PID, P_PGID, P_ALL, or P_PIDFD on Linux. id specifies the pid to wait on. options is constructed from the ORing of one or more of WEXITED, WSTOPPED or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT. The return value is an object representing the data contained in the siginfo_t structure, namely: si_pid, si_uid, si_signo, si_status, si_code or None if WNOHANG is specified and there are no children in a waitable state. Availability: Unix. New in version 3.3.
os.P_PID
os.P_PGID
os.P_ALL
These are the possible values for idtype in waitid(). They affect how id is interpreted. Availability: Unix. New in version 3.3.
os.P_PIDFD
This is a Linux-specific idtype that indicates that id is a file descriptor that refers to a process. Availability: Linux 5.4+ New in version 3.9.
os.WEXITED
os.WSTOPPED
os.WNOWAIT
Flags that can be used in options in waitid() that specify what child signal to wait for. Availability: Unix. New in version 3.3.
os.CLD_EXITED
os.CLD_KILLED
os.CLD_DUMPED
os.CLD_TRAPPED
os.CLD_STOPPED
os.CLD_CONTINUED
These are the possible values for si_code in the result returned by waitid(). Availability: Unix. New in version 3.3. Changed in version 3.9: Added CLD_KILLED and CLD_STOPPED values.
os.waitpid(pid, options)
The details of this function differ on Unix and Windows. On Unix: Wait for completion of a child process given by process id pid, and return a tuple containing its process id and exit status indication (encoded as for wait()). The semantics of the call are affected by the value of the integer options, which should be 0 for normal operation. If pid is greater than 0, waitpid() requests status information for that specific process. If pid is 0, the request is for the status of any child in the process group of the current process. If pid is -1, the request pertains to any child of the current process. If pid is less than -1, status is requested for any process in the process group -pid (the absolute value of pid). An OSError is raised with the value of errno when the syscall returns -1. On Windows: Wait for completion of a process given by process handle pid, and return a tuple containing pid, and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A pid less than or equal to 0 has no special meaning on Windows, and raises an exception. The value of integer options has no effect. pid can refer to any process whose id is known, not necessarily a child process. The spawn* functions called with P_NOWAIT return suitable process handles. waitstatus_to_exitcode() can be used to convert the exit status into an exit code. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
os.wait3(options)
Similar to waitpid(), except no process id argument is given and a 3-element tuple containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource.getrusage() for details on resource usage information. The option argument is the same as that provided to waitpid() and wait4(). waitstatus_to_exitcode() can be used to convert the exit status into an exitcode. Availability: Unix.
os.wait4(pid, options)
Similar to waitpid(), except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource.getrusage() for details on resource usage information. The arguments to wait4() are the same as those provided to waitpid(). waitstatus_to_exitcode() can be used to convert the exit status into an exitcode. Availability: Unix.
os.waitstatus_to_exitcode(status)
Convert a wait status to an exit code. On Unix: If the process exited normally (if WIFEXITED(status) is true), return the process exit status (return WEXITSTATUS(status)): result greater than or equal to 0. If the process was terminated by a signal (if WIFSIGNALED(status) is true), return -signum where signum is the number of the signal that caused the process to terminate (return -WTERMSIG(status)): result less than 0. Otherwise, raise a ValueError. On Windows, return status shifted right by 8 bits. On Unix, if the process is being traced or if waitpid() was called with WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true. This function must not be called if WIFSTOPPED(status) is true. See also WIFEXITED(), WEXITSTATUS(), WIFSIGNALED(), WTERMSIG(), WIFSTOPPED(), WSTOPSIG() functions. New in version 3.9.
os.WNOHANG
The option for waitpid() to return immediately if no child process status is available immediately. The function returns (0, 0) in this case. Availability: Unix.
os.WCONTINUED
This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported. Availability: some Unix systems.
os.WUNTRACED
This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped. Availability: Unix.
The following functions take a process status code as returned by system(), wait(), or waitpid() as a parameter. They may be used to determine the disposition of a process.
os.WCOREDUMP(status)
Return True if a core dump was generated for the process, otherwise return False. This function should be employed only if WIFSIGNALED() is true. Availability: Unix.
os.WIFCONTINUED(status)
Return True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False. See WCONTINUED option. Availability: Unix.
os.WIFSTOPPED(status)
Return True if the process was stopped by delivery of a signal, otherwise return False. WIFSTOPPED() only returns True if the waitpid() call was done using WUNTRACED option or when the process is being traced (see ptrace(2)). Availability: Unix.
os.WIFSIGNALED(status)
Return True if the process was terminated by a signal, otherwise return False. Availability: Unix.
os.WIFEXITED(status)
Return True if the process exited terminated normally, that is, by calling exit() or _exit(), or by returning from main(); otherwise return False. Availability: Unix.
os.WEXITSTATUS(status)
Return the process exit status. This function should be employed only if WIFEXITED() is true. Availability: Unix.
os.WSTOPSIG(status)
Return the signal which caused the process to stop. This function should be employed only if WIFSTOPPED() is true. Availability: Unix.
os.WTERMSIG(status)
Return the number of the signal that caused the process to terminate. This function should be employed only if WIFSIGNALED() is true. Availability: Unix.
Interface to the scheduler These functions control how a process is allocated CPU time by the operating system. They are only available on some Unix platforms. For more detailed information, consult your Unix manpages. New in version 3.3. The following scheduling policies are exposed if they are supported by the operating system.
os.SCHED_OTHER
The default scheduling policy.
os.SCHED_BATCH
Scheduling policy for CPU-intensive processes that tries to preserve interactivity on the rest of the computer.
os.SCHED_IDLE
Scheduling policy for extremely low priority background tasks.
os.SCHED_SPORADIC
Scheduling policy for sporadic server programs.
os.SCHED_FIFO
A First In First Out scheduling policy.
os.SCHED_RR
A round-robin scheduling policy.
os.SCHED_RESET_ON_FORK
This flag can be OR’ed with any other scheduling policy. When a process with this flag set forks, its child’s scheduling policy and priority are reset to the default.
class os.sched_param(sched_priority)
This class represents tunable scheduling parameters used in sched_setparam(), sched_setscheduler(), and sched_getparam(). It is immutable. At the moment, there is only one possible parameter:
sched_priority
The scheduling priority for a scheduling policy.
os.sched_get_priority_min(policy)
Get the minimum priority value for policy. policy is one of the scheduling policy constants above.
os.sched_get_priority_max(policy)
Get the maximum priority value for policy. policy is one of the scheduling policy constants above.
os.sched_setscheduler(pid, policy, param)
Set the scheduling policy for the process with PID pid. A pid of 0 means the calling process. policy is one of the scheduling policy constants above. param is a sched_param instance.
os.sched_getscheduler(pid)
Return the scheduling policy for the process with PID pid. A pid of 0 means the calling process. The result is one of the scheduling policy constants above.
os.sched_setparam(pid, param)
Set a scheduling parameters for the process with PID pid. A pid of 0 means the calling process. param is a sched_param instance.
os.sched_getparam(pid)
Return the scheduling parameters as a sched_param instance for the process with PID pid. A pid of 0 means the calling process.
os.sched_rr_get_interval(pid)
Return the round-robin quantum in seconds for the process with PID pid. A pid of 0 means the calling process.
os.sched_yield()
Voluntarily relinquish the CPU.
os.sched_setaffinity(pid, mask)
Restrict the process with PID pid (or the current process if zero) to a set of CPUs. mask is an iterable of integers representing the set of CPUs to which the process should be restricted.
os.sched_getaffinity(pid)
Return the set of CPUs the process with PID pid (or the current process if zero) is restricted to.
Miscellaneous System Information
os.confstr(name)
Return string-valued system configuration values. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards (POSIX, Unix 95, Unix 98, and others). Some platforms define additional names as well. The names known to the host operating system are given as the keys of the confstr_names dictionary. For configuration variables not included in that mapping, passing an integer for name is also accepted. If the configuration value specified by name isn’t defined, None is returned. If name is a string and is not known, ValueError is raised. If a specific value for name is not supported by the host system, even if it is included in confstr_names, an OSError is raised with errno.EINVAL for the error number. Availability: Unix.
os.confstr_names
Dictionary mapping names accepted by confstr() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system. Availability: Unix.
os.cpu_count()
Return the number of CPUs in the system. Returns None if undetermined. This number is not equivalent to the number of CPUs the current process can use. The number of usable CPUs can be obtained with len(os.sched_getaffinity(0)) New in version 3.4.
os.getloadavg()
Return the number of processes in the system run queue averaged over the last 1, 5, and 15 minutes or raises OSError if the load average was unobtainable. Availability: Unix.
os.sysconf(name)
Return integer-valued system configuration values. If the configuration value specified by name isn’t defined, -1 is returned. The comments regarding the name parameter for confstr() apply here as well; the dictionary that provides information on the known names is given by sysconf_names. Availability: Unix.
os.sysconf_names
Dictionary mapping names accepted by sysconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system. Availability: Unix.
The following data values are used to support path manipulation operations. These are defined for all platforms. Higher-level operations on pathnames are defined in the os.path module.
os.curdir
The constant string used by the operating system to refer to the current directory. This is '.' for Windows and POSIX. Also available via os.path.
os.pardir
The constant string used by the operating system to refer to the parent directory. This is '..' for Windows and POSIX. Also available via os.path.
os.sep
The character used by the operating system to separate pathname components. This is '/' for POSIX and '\\' for Windows. Note that knowing this is not sufficient to be able to parse or concatenate pathnames — use os.path.split() and os.path.join() — but it is occasionally useful. Also available via os.path.
os.altsep
An alternative character used by the operating system to separate pathname components, or None if only one separator character exists. This is set to '/' on Windows systems where sep is a backslash. Also available via os.path.
os.extsep
The character which separates the base filename from the extension; for example, the '.' in os.py. Also available via os.path.
os.pathsep
The character conventionally used by the operating system to separate search path components (as in PATH), such as ':' for POSIX or ';' for Windows. Also available via os.path.
os.defpath
The default search path used by exec*p* and spawn*p* if the environment doesn’t have a 'PATH' key. Also available via os.path.
os.linesep
The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.
os.devnull
The file path of the null device. For example: '/dev/null' for POSIX, 'nul' for Windows. Also available via os.path.
os.RTLD_LAZY
os.RTLD_NOW
os.RTLD_GLOBAL
os.RTLD_LOCAL
os.RTLD_NODELETE
os.RTLD_NOLOAD
os.RTLD_DEEPBIND
Flags for use with the setdlopenflags() and getdlopenflags() functions. See the Unix manual page dlopen(3) for what the different flags mean. New in version 3.3.
Random numbers
os.getrandom(size, flags=0)
Get up to size random bytes. The function can return less bytes than requested. These bytes can be used to seed user-space random number generators or for cryptographic purposes. getrandom() relies on entropy gathered from device drivers and other sources of environmental noise. Unnecessarily reading large quantities of data will have a negative impact on other users of the /dev/random and /dev/urandom devices. The flags argument is a bit mask that can contain zero or more of the following values ORed together: os.GRND_RANDOM and GRND_NONBLOCK. See also the Linux getrandom() manual page. Availability: Linux 3.17 and newer. New in version 3.6.
os.urandom(size)
Return a string of size random bytes suitable for cryptographic use. This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On Linux, if the getrandom() syscall is available, it is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits of entropy are collected by the kernel). See the PEP 524 for the rationale. On Linux, the getrandom() function can be used to get random bytes in non-blocking mode (using the GRND_NONBLOCK flag) or to poll until the system urandom entropy pool is initialized. On a Unix-like system, random bytes are read from the /dev/urandom device. If the /dev/urandom device is not available or not readable, the NotImplementedError exception is raised. On Windows, it will use CryptGenRandom(). See also The secrets module provides higher level functions. For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom. Changed in version 3.6.0: On Linux, getrandom() is now used in blocking mode to increase the security. Changed in version 3.5.2: On Linux, if the getrandom() syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading /dev/urandom. Changed in version 3.5: On Linux 3.17 and newer, the getrandom() syscall is now used when available. On OpenBSD 5.6 and newer, the C getentropy() function is now used. These functions avoid the usage of an internal file descriptor.
os.GRND_NONBLOCK
By default, when reading from /dev/random, getrandom() blocks if no random bytes are available, and when reading from /dev/urandom, it blocks if the entropy pool has not yet been initialized. If the GRND_NONBLOCK flag is set, then getrandom() does not block in these cases, but instead immediately raises BlockingIOError. New in version 3.6.
os.GRND_RANDOM
If this bit is set, then random bytes are drawn from the /dev/random pool instead of the /dev/urandom pool. New in version 3.6. | |
doc_44 | Time of file creation. | |
doc_45 | Resets the counter used to generate unique savepoint IDs. | |
doc_46 | If rawdata is a string, parse it as an HTTP_COOKIE and add the values found there as Morsels. If it is a dictionary, it is equivalent to: for k, v in rawdata.items():
cookie[k] = v | |
doc_47 | Called to allocate a new receive buffer. sizehint is the recommended minimum size for the returned buffer. It is acceptable to return smaller or larger buffers than what sizehint suggests. When set to -1, the buffer size can be arbitrary. It is an error to return a buffer with a zero size. get_buffer() must return an object implementing the buffer protocol. | |
doc_48 | Encode bytes-like object s using the standard Base64 alphabet and return the encoded bytes. | |
doc_49 | Same as st2tuple(st, line_info, col_info). | |
doc_50 | create a new copy of a Surface copy() -> Surface Makes a duplicate copy of a Surface. The new surface will have the same pixel formats, color palettes, transparency settings, and class as the original. If a Surface subclass also needs to copy any instance specific attributes then it should override copy(). | |
doc_51 | Register the browser type name. Once a browser type is registered, the get() function can return a controller for that browser type. If instance is not provided, or is None, constructor will be called without parameters to create an instance when needed. If instance is provided, constructor will never be called, and may be None. Setting preferred to True makes this browser a preferred result for a get() call with no argument. Otherwise, this entry point is only useful if you plan to either set the BROWSER variable or call get() with a nonempty argument matching the name of a handler you declare. Changed in version 3.7: preferred keyword-only parameter was added. | |
doc_52 | Send an OVER command, or an XOVER command on legacy servers. message_spec can be either a string representing a message id, or a (first, last) tuple of numbers indicating a range of articles in the current group, or a (first, None) tuple indicating a range of articles starting from first to the last article in the current group, or None to select the current article in the current group. Return a pair (response, overviews). overviews is a list of (article_number, overview) tuples, one for each article selected by message_spec. Each overview is a dictionary with the same number of items, but this number depends on the server. These items are either message headers (the key is then the lower-cased header name) or metadata items (the key is then the metadata name prepended with ":"). The following items are guaranteed to be present by the NNTP specification: the subject, from, date, message-id and references headers the :bytes metadata: the number of bytes in the entire raw article (including headers and body) the :lines metadata: the number of lines in the article body The value of each item is either a string, or None if not present. It is advisable to use the decode_header() function on header values when they may contain non-ASCII characters: >>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
>>> resp, overviews = s.over((last, last))
>>> art_num, over = overviews[0]
>>> art_num
117216
>>> list(over.keys())
['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']
>>> over['from']
'=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= <martin@v.loewis.de>'
>>> nntplib.decode_header(over['from'])
'"Martin v. Löwis" <martin@v.loewis.de>'
New in version 3.2. | |
doc_53 |
Check if the Index holds Interval objects. Returns
bool
Whether or not the Index holds Interval objects. See also IntervalIndex
Index for Interval objects. is_boolean
Check if the Index only consists of booleans. is_integer
Check if the Index only consists of integers. is_floating
Check if the Index is a floating type. is_numeric
Check if the Index only consists of numeric data. is_object
Check if the Index is of the object dtype. is_categorical
Check if the Index holds categorical data. is_mixed
Check if the Index holds data with mixed data types. Examples
>>> idx = pd.Index([pd.Interval(left=0, right=5),
... pd.Interval(left=5, right=10)])
>>> idx.is_interval()
True
>>> idx = pd.Index([1, 3, 5, 7])
>>> idx.is_interval()
False | |
doc_54 |
Return a list of the child Artists of this Artist. | |
doc_55 |
Apply only the non-affine part of this transformation. transform(values) is always equivalent to transform_affine(transform_non_affine(values)). In non-affine transformations, this is generally equivalent to transform(values). In affine transformations, this is always a no-op. Parameters
valuesarray
The input values as NumPy array of length input_dims or shape (N x input_dims). Returns
array
The output values as NumPy array of length input_dims or shape (N x output_dims), depending on the input. | |
doc_56 | returns the topmost sprite get_top_sprite() -> Sprite | |
doc_57 |
nd_grid instance which returns a dense multi-dimensional “meshgrid”. An instance of numpy.lib.index_tricks.nd_grid which returns an dense (or fleshed out) mesh-grid when indexed, so that each returned argument has the same shape. The dimensions and number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop is not inclusive. However, if the step length is a complex number (e.g. 5j), then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value is inclusive. Returns
mesh-grid ndarrays all of the same dimensions
See also numpy.lib.index_tricks.nd_grid
class of ogrid and mgrid objects ogrid
like mgrid but returns open (not fleshed out) mesh grids r_
array concatenator Examples >>> np.mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
>>> np.mgrid[-1:1:5j]
array([-1. , -0.5, 0. , 0.5, 1. ]) | |
doc_58 |
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat | |
doc_59 |
Set the parameters of this estimator. Valid parameter keys can be listed with get_params(). Note that you can directly set the parameters of the estimators contained in transformers of ColumnTransformer. Returns
self | |
doc_60 |
Return the user-specified font directory for Win32. This is looked up from the registry key \\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
If the key is not found, %WINDIR%\Fonts will be returned. | |
doc_61 | Compares the values numerically with their sign ignored. | |
doc_62 |
Return the path of this patch. | |
doc_63 | >>> serializer = AccountSerializer()
>>> print(repr(serializer))
AccountSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(allow_blank=True, max_length=100, required=False)
owner = PrimaryKeyRelatedField(queryset=User.objects.all())
API Reference In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. class Album(models.Model):
album_name = models.CharField(max_length=100)
artist = models.CharField(max_length=100)
class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
order = models.IntegerField()
title = models.CharField(max_length=100)
duration = models.IntegerField()
class Meta:
unique_together = ['album', 'order']
ordering = ['order']
def __str__(self):
return '%d: %s' % (self.order, self.title)
StringRelatedField StringRelatedField may be used to represent the target of the relationship using its __str__ method. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
Would serialize to the following representation: {
'album_name': 'Things We Lost In The Fire',
'artist': 'Low',
'tracks': [
'1: Sunflower',
'2: Whitetail',
'3: Dinosaur Act',
...
]
}
This field is read only. Arguments:
many - If applied to a to-many relationship, you should set this argument to True. PrimaryKeyRelatedField PrimaryKeyRelatedField may be used to represent the target of the relationship using its primary key. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
Would serialize to a representation like this: {
'album_name': 'Undun',
'artist': 'The Roots',
'tracks': [
89,
90,
91,
...
]
}
By default this field is read-write, although you can change this behavior using the read_only flag. Arguments:
queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
many - If applied to a to-many relationship, you should set this argument to True.
allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
pk_field - Set to a field to control serialization/deserialization of the primary key's value. For example, pk_field=UUIDField(format='hex') would serialize a UUID primary key into its compact hex representation. HyperlinkedRelatedField HyperlinkedRelatedField may be used to represent the target of the relationship using a hyperlink. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.HyperlinkedRelatedField(
many=True,
read_only=True,
view_name='track-detail'
)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
Would serialize to a representation like this: {
'album_name': 'Graceland',
'artist': 'Paul Simon',
'tracks': [
'http://www.example.com/api/tracks/45/',
'http://www.example.com/api/tracks/46/',
'http://www.example.com/api/tracks/47/',
...
]
}
By default this field is read-write, although you can change this behavior using the read_only flag. Note: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the lookup_field and lookup_url_kwarg arguments. This is suitable for URLs that contain a single primary key or slug argument as part of the URL. If you require more complex hyperlinked representation you'll need to customize the field, as described in the custom hyperlinked fields section, below. Arguments:
view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <modelname>-detail. required.
queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
many - If applied to a to-many relationship, you should set this argument to True.
allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk'.
lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument. SlugRelatedField SlugRelatedField may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.SlugRelatedField(
many=True,
read_only=True,
slug_field='title'
)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
Would serialize to a representation like this: {
'album_name': 'Dear John',
'artist': 'Loney Dear',
'tracks': [
'Airport Surroundings',
'Everything Turns to You',
'I Was Only Going Out',
...
]
}
By default this field is read-write, although you can change this behavior using the read_only flag. When using SlugRelatedField as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with unique=True. Arguments:
slug_field - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, username. required
queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
many - If applied to a to-many relationship, you should set this argument to True.
allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False. HyperlinkedIdentityField This field can be applied as an identity relationship, such as the 'url' field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
class Meta:
model = Album
fields = ['album_name', 'artist', 'track_listing']
Would serialize to a representation like this: {
'album_name': 'The Eraser',
'artist': 'Thom Yorke',
'track_listing': 'http://www.example.com/api/track_list/12/',
}
This field is always read-only. Arguments:
view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <model_name>-detail. required.
lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk'.
lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument. Nested relationships As opposed to previously discussed references to another entity, the referred entity can instead also be embedded or nested in the representation of the object that refers to it. Such nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the many=True flag to the serializer field. Example For example, the following serializer: class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
Would serialize to a nested representation like this: >>> album = Album.objects.create(album_name="The Grey Album", artist='Danger Mouse')
>>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245)
<Track: Track object>
>>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264)
<Track: Track object>
>>> Track.objects.create(album=album, order=3, title='Encore', duration=159)
<Track: Track object>
>>> serializer = AlbumSerializer(instance=album)
>>> serializer.data
{
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
...
],
}
Writable nested serializers By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create create() and/or update() methods in order to explicitly specify how the child relationships should be saved: class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ['order', 'title', 'duration']
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
def create(self, validated_data):
tracks_data = validated_data.pop('tracks')
album = Album.objects.create(**validated_data)
for track_data in tracks_data:
Track.objects.create(album=album, **track_data)
return album
>>> data = {
'album_name': 'The Grey Album',
'artist': 'Danger Mouse',
'tracks': [
{'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
{'order': 2, 'title': 'What More Can I Say', 'duration': 264},
{'order': 3, 'title': 'Encore', 'duration': 159},
],
}
>>> serializer = AlbumSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<Album: Album object>
Custom relational fields In rare cases where none of the existing relational styles fit the representation you need, you can implement a completely custom relational field, that describes exactly how the output representation should be generated from the model instance. To implement a custom relational field, you should override RelatedField, and implement the .to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance. If you want to implement a read-write relational field, you must also implement the .to_internal_value(self, data) method. To provide a dynamic queryset based on the context, you can also override .get_queryset(self) instead of specifying .queryset on the class or when initializing the field. Example For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration: import time
class TrackListingField(serializers.RelatedField):
def to_representation(self, value):
duration = time.strftime('%M:%S', time.gmtime(value.duration))
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackListingField(many=True)
class Meta:
model = Album
fields = ['album_name', 'artist', 'tracks']
This custom field would then serialize to the following representation: {
'album_name': 'Sometimes I Wish We Were an Eagle',
'artist': 'Bill Callahan',
'tracks': [
'Track 1: Jim Cain (04:39)',
'Track 2: Eid Ma Clack Shaw (04:19)',
'Track 3: The Wind and the Dove (04:34)',
...
]
}
Custom hyperlinked fields In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field. You can achieve this by overriding HyperlinkedRelatedField. There are two methods that may be overridden: get_url(self, obj, view_name, request, format) The get_url method is used to map the object instance to its URL representation. May raise a NoReverseMatch if the view_name and lookup_field attributes are not configured to correctly match the URL conf. get_object(self, view_name, view_args, view_kwargs) If you want to support a writable hyperlinked field then you'll also want to override get_object, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method. The return value of this method should the object that corresponds to the matched URL conf arguments. May raise an ObjectDoesNotExist exception. Example Say we have a URL for a customer object that takes two keyword arguments, like so: /api/<organization_slug>/customers/<customer_pk>/
This cannot be represented with the default implementation, which accepts only a single lookup field. In this case we'd need to override HyperlinkedRelatedField to get the behavior we want: from rest_framework import serializers
from rest_framework.reverse import reverse
class CustomerHyperlink(serializers.HyperlinkedRelatedField):
# We define these as class attributes, so we don't need to pass them as arguments.
view_name = 'customer-detail'
queryset = Customer.objects.all()
def get_url(self, obj, view_name, request, format):
url_kwargs = {
'organization_slug': obj.organization.slug,
'customer_pk': obj.pk
}
return reverse(view_name, kwargs=url_kwargs, request=request, format=format)
def get_object(self, view_name, view_args, view_kwargs):
lookup_kwargs = {
'organization__slug': view_kwargs['organization_slug'],
'pk': view_kwargs['customer_pk']
}
return self.get_queryset().get(**lookup_kwargs)
Note that if you wanted to use this style together with the generic views then you'd also need to override .get_object on the view in order to get the correct lookup behavior. Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation. Further notes The queryset argument The queryset argument is only ever required for writable relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance. In version 2.x a serializer class could sometimes automatically determine the queryset argument if a ModelSerializer class was being used. This behavior is now replaced with always using an explicit queryset argument for writable relational fields. Doing so reduces the amount of hidden 'magic' that ModelSerializer provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the ModelSerializer shortcut, or using fully explicit Serializer classes. Customizing the HTML display The built-in __str__ method of the model will be used to generate string representations of the objects used to populate the choices property. These choices are used to populate select HTML inputs in the browsable API. To provide customized representations for such inputs, override display_value() of a RelatedField subclass. This method will receive a model object, and should return a string suitable for representing it. For example: class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField):
def display_value(self, instance):
return 'Track: %s' % (instance.title)
Select field cutoffs When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed. This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed. There are two keyword arguments you can use to control this behavior:
html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to None to disable any limiting. Defaults to 1000.
html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"
You can also control these globally using the settings HTML_SELECT_CUTOFF and HTML_SELECT_CUTOFF_TEXT. In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the style keyword argument. For example: assigned_to = serializers.SlugRelatedField(
queryset=User.objects.all(),
slug_field='username',
style={'base_template': 'input.html'}
)
Reverse relations Note that reverse relationships are not automatically included by the ModelSerializer and HyperlinkedModelSerializer classes. To include a reverse relationship, you must explicitly add it to the fields list. For example: class AlbumSerializer(serializers.ModelSerializer):
class Meta:
fields = ['tracks', ...]
You'll normally want to ensure that you've set an appropriate related_name argument on the relationship, that you can use as the field name. For example: class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE)
...
If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the fields argument. For example: class AlbumSerializer(serializers.ModelSerializer):
class Meta:
fields = ['track_set', ...]
See the Django documentation on reverse relationships for more details. Generic relationships If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship. For example, given the following model for a tag, which has a generic relationship with other arbitrary models: class TaggedItem(models.Model):
"""
Tags arbitrary model instances using a generic relation.
See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/
"""
tag_name = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
tagged_object = GenericForeignKey('content_type', 'object_id')
def __str__(self):
return self.tag_name
And the following two models, which may have associated tags: class Bookmark(models.Model):
"""
A bookmark consists of a URL, and 0 or more descriptive tags.
"""
url = models.URLField()
tags = GenericRelation(TaggedItem)
class Note(models.Model):
"""
A note consists of some text, and 0 or more descriptive tags.
"""
text = models.CharField(max_length=1000)
tags = GenericRelation(TaggedItem)
We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized: class TaggedObjectRelatedField(serializers.RelatedField):
"""
A custom field to use for the `tagged_object` generic relationship.
"""
def to_representation(self, value):
"""
Serialize tagged objects to a simple textual representation.
"""
if isinstance(value, Bookmark):
return 'Bookmark: ' + value.url
elif isinstance(value, Note):
return 'Note: ' + value.text
raise Exception('Unexpected type of tagged object')
If you need the target of the relationship to have a nested representation, you can use the required serializers inside the .to_representation() method: def to_representation(self, value):
"""
Serialize bookmark instances using a bookmark serializer,
and note instances using a note serializer.
"""
if isinstance(value, Bookmark):
serializer = BookmarkSerializer(value)
elif isinstance(value, Note):
serializer = NoteSerializer(value)
else:
raise Exception('Unexpected type of tagged object')
return serializer.data
Note that reverse generic keys, expressed using the GenericRelation field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. For more information see the Django documentation on generic relations. ManyToManyFields with a Through Model By default, relational fields that target a ManyToManyField with a through model specified are set to read-only. If you explicitly specify a relational field pointing to a ManyToManyField with a through model, be sure to set read_only to True. If you wish to represent extra fields on a through model then you may serialize the through model as a nested object. Third Party Packages The following third party packages are also available. DRF Nested Routers The drf-nested-routers package provides routers and relationship fields for working with nested resources. Rest Framework Generic Relations The rest-framework-generic-relations library provides read/write serialization for generic foreign keys. relations.py | |
doc_64 |
Return the minimum of an array or minimum along an axis. Parameters
aarray_like
Input data.
axisNone or int or tuple of ints, optional
Axis or axes along which to operate. By default, flattened input is used. New in version 1.7.0. If this is a tuple of ints, the minimum is selected over multiple axes, instead of a single axis or all the axes as before.
outndarray, optional
Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See Output type determination for more details.
keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the amin method of sub-classes of ndarray, however any non-default value will be. If the sub-class’ method does not implement keepdims any exceptions will be raised.
initialscalar, optional
The maximum value of an output element. Must be present to allow computation on empty slice. See reduce for details. New in version 1.15.0.
wherearray_like of bool, optional
Elements to compare for the minimum. See reduce for details. New in version 1.17.0. Returns
aminndarray or scalar
Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1. See also amax
The maximum value of an array along a given axis, propagating any NaNs. nanmin
The minimum value of an array along a given axis, ignoring any NaNs. minimum
Element-wise minimum of two arrays, propagating any NaNs. fmin
Element-wise minimum of two arrays, ignoring any NaNs. argmin
Return the indices of the minimum values.
nanmax, maximum, fmax
Notes NaN values are propagated, that is if at least one item is NaN, the corresponding min value will be NaN as well. To ignore NaN values (MATLAB behavior), please use nanmin. Don’t use amin for element-wise comparison of 2 arrays; when a.shape[0] is 2, minimum(a[0], a[1]) is faster than amin(a, axis=0). Examples >>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.amin(a) # Minimum of the flattened array
0
>>> np.amin(a, axis=0) # Minima along the first axis
array([0, 1])
>>> np.amin(a, axis=1) # Minima along the second axis
array([0, 2])
>>> np.amin(a, where=[False, True], initial=10, axis=0)
array([10, 1])
>>> b = np.arange(5, dtype=float)
>>> b[2] = np.NaN
>>> np.amin(b)
nan
>>> np.amin(b, where=~np.isnan(b), initial=10)
0.0
>>> np.nanmin(b)
0.0
>>> np.amin([[-50], [10]], axis=-1, initial=0)
array([-50, 0])
Notice that the initial value is used as one of the elements for which the minimum is determined, unlike for the default argument Python’s max function, which is only used for empty iterables. Notice that this isn’t the same as Python’s default argument. >>> np.amin([6], initial=5)
5
>>> min([6], default=5)
6 | |
doc_65 | numpy.int16
numpy.int32
numpy.int64
Aliases for the signed integer types (one of numpy.byte, numpy.short, numpy.intc, numpy.int_ and numpy.longlong) with the specified number of bits. Compatible with the C99 int8_t, int16_t, int32_t, and int64_t, respectively. | |
doc_66 | See Migration guide for more details. tf.compat.v1.encode_base64, tf.compat.v1.io.encode_base64
tf.io.encode_base64(
input, pad=False, name=None
)
Refer to the following article for more information on base64 format: en.wikipedia.org/wiki/Base64. Base64 strings may have padding with '=' at the end so that the encoded has length multiple of 4. See Padding section of the link above. Web-safe means that the encoder uses - and _ instead of + and /.
Args
input A Tensor of type string. Strings to be encoded.
pad An optional bool. Defaults to False. Bool whether padding is applied at the ends.
name A name for the operation (optional).
Returns A Tensor of type string. | |
doc_67 | ABC for classes that provide __aiter__ method. See also the definition of asynchronous iterable. New in version 3.5. | |
doc_68 | tf.metrics.Precision Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.metrics.Precision
tf.keras.metrics.Precision(
thresholds=None, top_k=None, class_id=None, name=None, dtype=None
)
The metric creates two local variables, true_positives and false_positives that are used to compute the precision. This value is ultimately returned as precision, an idempotent operation that simply divides true_positives by the sum of true_positives and false_positives. If sample_weight is None, weights default to 1. Use sample_weight of 0 to mask values. If top_k is set, we'll calculate precision as how often on average a class among the top-k classes with the highest predicted values of a batch entry is correct and can be found in the label for that entry. If class_id is specified, we calculate precision by considering only the entries in the batch for which class_id is above the threshold and/or in the top-k highest predictions, and computing the fraction of them for which class_id is indeed a correct label.
Args
thresholds (Optional) A float value or a python list/tuple of float threshold values in [0, 1]. A threshold is compared with prediction values to determine the truth value of predictions (i.e., above the threshold is true, below is false). One metric value is generated for each threshold value. If neither thresholds nor top_k are set, the default is to calculate precision with thresholds=0.5.
top_k (Optional) Unset by default. An int value specifying the top-k predictions to consider when calculating precision.
class_id (Optional) Integer class ID for which we want binary metrics. This must be in the half-open interval [0, num_classes), where num_classes is the last dimension of predictions.
name (Optional) string name of the metric instance.
dtype (Optional) data type of the metric result. Standalone usage:
m = tf.keras.metrics.Precision()
m.update_state([0, 1, 1, 1], [1, 0, 1, 1])
m.result().numpy()
0.6666667
m.reset_states()
m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0])
m.result().numpy()
1.0
# With top_k=2, it will calculate precision over y_true[:2] and y_pred[:2]
m = tf.keras.metrics.Precision(top_k=2)
m.update_state([0, 0, 1, 1], [1, 1, 1, 1])
m.result().numpy()
0.0
# With top_k=4, it will calculate precision over y_true[:4] and y_pred[:4]
m = tf.keras.metrics.Precision(top_k=4)
m.update_state([0, 0, 1, 1], [1, 1, 1, 1])
m.result().numpy()
0.5
Usage with compile() API: model.compile(optimizer='sgd',
loss='mse',
metrics=[tf.keras.metrics.Precision()])
Methods reset_states View source
reset_states()
Resets all of the metric state variables. This function is called between epochs/steps, when a metric is evaluated during training. result View source
result()
Computes and returns the metric value tensor. Result computation is an idempotent operation that simply calculates the metric value using the state variables. update_state View source
update_state(
y_true, y_pred, sample_weight=None
)
Accumulates true positive and false positive statistics.
Args
y_true The ground truth values, with the same dimensions as y_pred. Will be cast to bool.
y_pred The predicted values. Each element must be in the range [0, 1].
sample_weight Optional weighting of each example. Defaults to 1. Can be a Tensor whose rank is either 0, or the same rank as y_true, and must be broadcastable to y_true.
Returns Update op. | |
doc_69 | tf.compat.v1.ReaderBase(
reader_ref, supports_serialize=False
)
Conceptually, Readers convert string 'work units' into records (key, value pairs). Typically the 'work units' are filenames and the records are extracted from the contents of those files. We want a single record produced per step, but a work unit can correspond to many records. Therefore we introduce some decoupling using a queue. The queue contains the work units and the Reader dequeues from the queue when it is asked to produce a record (via Read()) but it has finished the last work unit.
Args
reader_ref The operation that implements the reader.
supports_serialize True if the reader implementation can serialize its state.
Raises
RuntimeError If eager execution is enabled. Eager Compatibility Readers are not compatible with eager execution. Instead, please use tf.data to get data into your model.
Attributes
reader_ref Op that implements the reader.
supports_serialize Whether the Reader implementation can serialize its state. Methods num_records_produced View source
num_records_produced(
name=None
)
Returns the number of records this reader has produced. This is the same as the number of Read executions that have succeeded.
Args
name A name for the operation (optional).
Returns An int64 Tensor.
num_work_units_completed View source
num_work_units_completed(
name=None
)
Returns the number of work units this reader has finished processing.
Args
name A name for the operation (optional).
Returns An int64 Tensor.
read View source
read(
queue, name=None
)
Returns the next record (key, value) pair produced by a reader. Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
Args
queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items.
name A name for the operation (optional).
Returns A tuple of Tensors (key, value). key A string scalar Tensor.
value A string scalar Tensor. read_up_to View source
read_up_to(
queue, num_records, name=None
)
Returns up to num_records (key, value) pairs produced by a reader. Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num_records even before the last batch.
Args
queue A Queue or a mutable string Tensor representing a handle to a Queue, with string work items.
num_records Number of records to read.
name A name for the operation (optional).
Returns A tuple of Tensors (keys, values). keys A 1-D string Tensor.
values A 1-D string Tensor. reset View source
reset(
name=None
)
Restore a reader to its initial clean state.
Args
name A name for the operation (optional).
Returns The created Operation.
restore_state View source
restore_state(
state, name=None
)
Restore a reader to a previously saved state. Not all Readers support being restored, so this can produce an Unimplemented error.
Args
state A string Tensor. Result of a SerializeState of a Reader with matching type.
name A name for the operation (optional).
Returns The created Operation.
serialize_state View source
serialize_state(
name=None
)
Produce a string tensor that encodes the state of a reader. Not all Readers support being serialized, so this can produce an Unimplemented error.
Args
name A name for the operation (optional).
Returns A string Tensor. | |
doc_70 | See Migration guide for more details. tf.compat.v1.raw_ops.DecodeCSV
tf.raw_ops.DecodeCSV(
records, record_defaults, field_delim=',', use_quote_delim=True,
na_value='', select_cols=[], name=None
)
RFC 4180 format is expected for the CSV records. (https://tools.ietf.org/html/rfc4180) Note that we allow leading and trailing spaces with int or float field.
Args
records A Tensor of type string. Each string is a record/row in the csv and all records should have the same format.
record_defaults A list of Tensor objects with types from: float32, float64, int32, int64, string. One tensor per column of the input record, with either a scalar default value for that column or an empty vector if the column is required.
field_delim An optional string. Defaults to ",". char delimiter to separate fields in a record.
use_quote_delim An optional bool. Defaults to True. If false, treats double quotation marks as regular characters inside of the string fields (ignoring RFC 4180, Section 2, Bullet 5).
na_value An optional string. Defaults to "". Additional string to recognize as NA/NaN.
select_cols An optional list of ints. Defaults to [].
name A name for the operation (optional).
Returns A list of Tensor objects. Has the same type as record_defaults. | |
doc_71 |
Convert continuous line to post-steps. Given a set of N points convert to 2N + 1 points, which when connected linearly give a step function which changes values at the end of the intervals. Parameters
xarray
The x location of the steps. May be empty.
y1, ..., yparray
y arrays to be turned into steps; all must be the same length as x. Returns
array
The x and y values converted to steps in the same order as the input; can be unpacked as x_out, y1_out, ..., yp_out. If the input is length N, each of these arrays will be length 2N + 1. For N=0, the length will be 0. Examples >>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2) | |
doc_72 |
Set padding for constrained_layout. Tip: The parameters can be passed from a dictionary by using fig.set_constrained_layout(**pad_dict). See Constrained Layout Guide. Parameters
w_padfloat, default: rcParams["figure.constrained_layout.w_pad"] (default: 0.04167)
Width padding in inches. This is the pad around Axes and is meant to make sure there is enough room for fonts to look good. Defaults to 3 pts = 0.04167 inches
h_padfloat, default: rcParams["figure.constrained_layout.h_pad"] (default: 0.04167)
Height padding in inches. Defaults to 3 pts.
wspacefloat, default: rcParams["figure.constrained_layout.wspace"] (default: 0.02)
Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace.
hspacefloat, default: rcParams["figure.constrained_layout.hspace"] (default: 0.02)
Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace. | |
doc_73 | Return non-zero if the mode is from a directory. | |
doc_74 |
Return cumulative maximum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative maximum. Parameters
axis:{0 or ‘index’, 1 or ‘columns’}, default 0
The index or the name of the axis. 0 is equivalent to None or ‘index’.
skipna:bool, default True
Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs
Additional keywords have no effect but might be accepted for compatibility with NumPy. Returns
Series or DataFrame
Return cumulative maximum of Series or DataFrame. See also core.window.Expanding.max
Similar functionality but ignores NaN values. DataFrame.max
Return the maximum over DataFrame axis. DataFrame.cummax
Return cumulative maximum over DataFrame axis. DataFrame.cummin
Return cumulative minimum over DataFrame axis. DataFrame.cumsum
Return cumulative sum over DataFrame axis. DataFrame.cumprod
Return cumulative product over DataFrame axis. Examples Series
>>> s = pd.Series([2, np.nan, 5, -1, 0])
>>> s
0 2.0
1 NaN
2 5.0
3 -1.0
4 0.0
dtype: float64
By default, NA values are ignored.
>>> s.cummax()
0 2.0
1 NaN
2 5.0
3 5.0
4 5.0
dtype: float64
To include NA values in the operation, use skipna=False
>>> s.cummax(skipna=False)
0 2.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
DataFrame
>>> df = pd.DataFrame([[2.0, 1.0],
... [3.0, np.nan],
... [1.0, 0.0]],
... columns=list('AB'))
>>> df
A B
0 2.0 1.0
1 3.0 NaN
2 1.0 0.0
By default, iterates over rows and finds the maximum in each column. This is equivalent to axis=None or axis='index'.
>>> df.cummax()
A B
0 2.0 1.0
1 3.0 NaN
2 3.0 1.0
To iterate over columns and find the maximum in each row, use axis=1
>>> df.cummax(axis=1)
A B
0 2.0 2.0
1 3.0 NaN
2 1.0 1.0 | |
doc_75 | class sklearn.linear_model.MultiTaskElasticNetCV(*, l1_ratio=0.5, eps=0.001, n_alphas=100, alphas=None, fit_intercept=True, normalize=False, max_iter=1000, tol=0.0001, cv=None, copy_X=True, verbose=0, n_jobs=None, random_state=None, selection='cyclic') [source]
Multi-task L1/L2 ElasticNet with built-in cross-validation. See glossary entry for cross-validation estimator. The optimization objective for MultiTaskElasticNet is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
i.e. the sum of norm of each row. Read more in the User Guide. New in version 0.15. Parameters
l1_ratiofloat or list of float, default=0.5
The ElasticNet mixing parameter, with 0 < l1_ratio <= 1. For l1_ratio = 1 the penalty is an L1/L2 penalty. For l1_ratio = 0 it is an L2 penalty. For 0 < l1_ratio < 1, the penalty is a combination of L1/L2 and L2. This parameter can be a list, in which case the different values are tested by cross-validation and the one giving the best prediction score is used. Note that a good choice of list of values for l1_ratio is often to put more values close to 1 (i.e. Lasso) and less close to 0 (i.e. Ridge), as in [.1, .5, .7,
.9, .95, .99, 1]
epsfloat, default=1e-3
Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100
Number of alphas along the regularization path.
alphasarray-like, default=None
List of alphas where to compute the models. If not provided, set automatically.
fit_interceptbool, default=True
Whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (i.e. data is expected to be centered).
normalizebool, default=False
This parameter is ignored when fit_intercept is set to False. If True, the regressors X will be normalized before regression by subtracting the mean and dividing by the l2-norm. If you wish to standardize, please use StandardScaler before calling fit on an estimator with normalize=False.
max_iterint, default=1000
The maximum number of iterations.
tolfloat, default=1e-4
The tolerance for the optimization: if the updates are smaller than tol, the optimization code checks the dual gap for optimality and continues until it is smaller than tol.
cvint, cross-validation generator or iterable, default=None
Determines the cross-validation splitting strategy. Possible inputs for cv are: None, to use the default 5-fold cross-validation, int, to specify the number of folds.
CV splitter, An iterable yielding (train, test) splits as arrays of indices. For int/None inputs, KFold is used. Refer User Guide for the various cross-validation strategies that can be used here. Changed in version 0.22: cv default value if None changed from 3-fold to 5-fold.
copy_Xbool, default=True
If True, X will be copied; else, it may be overwritten.
verbosebool or int, default=0
Amount of verbosity.
n_jobsint, default=None
Number of CPUs to use during the cross validation. Note that this is used only if multiple values for l1_ratio are given. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. See Glossary for more details.
random_stateint, RandomState instance, default=None
The seed of the pseudo random number generator that selects a random feature to update. Used when selection == ‘random’. Pass an int for reproducible output across multiple function calls. See Glossary.
selection{‘cyclic’, ‘random’}, default=’cyclic’
If set to ‘random’, a random coefficient is updated every iteration rather than looping over features sequentially by default. This (setting to ‘random’) often leads to significantly faster convergence especially when tol is higher than 1e-4. Attributes
intercept_ndarray of shape (n_tasks,)
Independent term in decision function.
coef_ndarray of shape (n_tasks, n_features)
Parameter vector (W in the cost function formula). Note that coef_ stores the transpose of W, W.T.
alpha_float
The amount of penalization chosen by cross validation.
mse_path_ndarray of shape (n_alphas, n_folds) or (n_l1_ratio, n_alphas, n_folds)
Mean square error for the test set on each fold, varying alpha.
alphas_ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas)
The grid of alphas used for fitting, for each l1_ratio.
l1_ratio_float
Best l1_ratio obtained by cross-validation.
n_iter_int
Number of iterations run by the coordinate descent solver to reach the specified tolerance for the optimal alpha.
dual_gap_float
The dual gap at the end of the optimization for the optimal alpha. See also
MultiTaskElasticNet
ElasticNetCV
MultiTaskLassoCV
Notes The algorithm used to fit the model is coordinate descent. To avoid unnecessary memory duplication the X and y arguments of the fit method should be directly passed as Fortran-contiguous numpy arrays. Examples >>> from sklearn import linear_model
>>> clf = linear_model.MultiTaskElasticNetCV(cv=3)
>>> clf.fit([[0,0], [1, 1], [2, 2]],
... [[0, 0], [1, 1], [2, 2]])
MultiTaskElasticNetCV(cv=3)
>>> print(clf.coef_)
[[0.52875032 0.46958558]
[0.52875032 0.46958558]]
>>> print(clf.intercept_)
[0.00166409 0.00166409]
Methods
fit(X, y) Fit linear model with coordinate descent.
get_params([deep]) Get parameters for this estimator.
path(*args, **kwargs) Compute elastic net path with coordinate descent.
predict(X) Predict using the linear model.
score(X, y[, sample_weight]) Return the coefficient of determination \(R^2\) of the prediction.
set_params(**params) Set the parameters of this estimator.
fit(X, y) [source]
Fit linear model with coordinate descent. Fit is on grid of alphas and best alpha estimated by cross-validation. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output, X can be sparse.
yarray-like of shape (n_samples,) or (n_samples, n_targets)
Target values.
get_params(deep=True) [source]
Get parameters for this estimator. Parameters
deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns
paramsdict
Parameter names mapped to their values.
static path(*args, **kwargs) [source]
Compute elastic net path with coordinate descent. The elastic net optimization function varies for mono and multi-outputs. For mono-output tasks it is: 1 / (2 * n_samples) * ||y - Xw||^2_2
+ alpha * l1_ratio * ||w||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2
For multi-output tasks it is: (1 / (2 * n_samples)) * ||Y - XW||^Fro_2
+ alpha * l1_ratio * ||W||_21
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
Where: ||W||_21 = \sum_i \sqrt{\sum_j w_{ij}^2}
i.e. the sum of norm of each row. Read more in the User Guide. Parameters
X{array-like, sparse matrix} of shape (n_samples, n_features)
Training data. Pass directly as Fortran-contiguous data to avoid unnecessary memory duplication. If y is mono-output then X can be sparse.
y{array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs)
Target values.
l1_ratiofloat, default=0.5
Number between 0 and 1 passed to elastic net (scaling between l1 and l2 penalties). l1_ratio=1 corresponds to the Lasso.
epsfloat, default=1e-3
Length of the path. eps=1e-3 means that alpha_min / alpha_max = 1e-3.
n_alphasint, default=100
Number of alphas along the regularization path.
alphasndarray, default=None
List of alphas where to compute the models. If None alphas are set automatically.
precompute‘auto’, bool or array-like of shape (n_features, n_features), default=’auto’
Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument.
Xyarray-like of shape (n_features,) or (n_features, n_outputs), default=None
Xy = np.dot(X.T, y) that can be precomputed. It is useful only when the Gram matrix is precomputed.
copy_Xbool, default=True
If True, X will be copied; else, it may be overwritten.
coef_initndarray of shape (n_features, ), default=None
The initial values of the coefficients.
verbosebool or int, default=False
Amount of verbosity.
return_n_iterbool, default=False
Whether to return the number of iterations or not.
positivebool, default=False
If set to True, forces coefficients to be positive. (Only allowed when y.ndim == 1).
check_inputbool, default=True
If set to False, the input validation checks are skipped (including the Gram matrix when provided). It is assumed that they are handled by the caller.
**paramskwargs
Keyword arguments passed to the coordinate descent solver. Returns
alphasndarray of shape (n_alphas,)
The alphas along the path where models are computed.
coefsndarray of shape (n_features, n_alphas) or (n_outputs, n_features, n_alphas)
Coefficients along the path.
dual_gapsndarray of shape (n_alphas,)
The dual gaps at the end of the optimization for each alpha.
n_iterslist of int
The number of iterations taken by the coordinate descent optimizer to reach the specified tolerance for each alpha. (Is returned when return_n_iter is set to True). See also
MultiTaskElasticNet
MultiTaskElasticNetCV
ElasticNet
ElasticNetCV
Notes For an example, see examples/linear_model/plot_lasso_coordinate_descent_path.py.
predict(X) [source]
Predict using the linear model. Parameters
Xarray-like or sparse matrix, shape (n_samples, n_features)
Samples. Returns
Carray, shape (n_samples,)
Returns predicted values.
score(X, y, sample_weight=None) [source]
Return the coefficient of determination \(R^2\) of the prediction. The coefficient \(R^2\) is defined as \((1 - \frac{u}{v})\), where \(u\) is the residual sum of squares ((y_true - y_pred)
** 2).sum() and \(v\) is the total sum of squares ((y_true -
y_true.mean()) ** 2).sum(). The best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of y, disregarding the input features, would get a \(R^2\) score of 0.0. Parameters
Xarray-like of shape (n_samples, n_features)
Test samples. For some estimators this may be a precomputed kernel matrix or a list of generic objects instead with shape (n_samples, n_samples_fitted), where n_samples_fitted is the number of samples used in the fitting for the estimator.
yarray-like of shape (n_samples,) or (n_samples, n_outputs)
True values for X.
sample_weightarray-like of shape (n_samples,), default=None
Sample weights. Returns
scorefloat
\(R^2\) of self.predict(X) wrt. y. Notes The \(R^2\) score used when calling score on a regressor uses multioutput='uniform_average' from version 0.23 to keep consistent with default value of r2_score. This influences the score method of all the multioutput regressors (except for MultiOutputRegressor).
set_params(**params) [source]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object. Parameters
**paramsdict
Estimator parameters. Returns
selfestimator instance
Estimator instance. | |
doc_76 | See Migration guide for more details. tf.compat.v1.raw_ops.SelfAdjointEig
tf.raw_ops.SelfAdjointEig(
input, name=None
)
The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices, with the same constraints as the single matrix SelfAdjointEig. The result is a [..., M+1, M] matrix with [..., 0,:] containing the eigenvalues, and subsequent [...,1:, :] containing the eigenvectors. The eigenvalues are sorted in non-decreasing order.
Args
input A Tensor. Must be one of the following types: float64, float32, half. Shape is [..., M, M].
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | |
doc_77 | Return or set the pencolor. Four input formats are allowed:
pencolor()
Return the current pencolor as color specification string or as a tuple (see example). May be used as input to another color/pencolor/fillcolor call.
pencolor(colorstring)
Set pencolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".
pencolor((r, g, b))
Set pencolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode()).
pencolor(r, g, b)
Set pencolor to the RGB color represented by r, g, and b. Each of r, g, and b must be in the range 0..colormode. If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor. >>> colormode()
1.0
>>> turtle.pencolor()
'red'
>>> turtle.pencolor("brown")
>>> turtle.pencolor()
'brown'
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
(0.2, 0.8, 0.5490196078431373)
>>> colormode(255)
>>> turtle.pencolor()
(51.0, 204.0, 140.0)
>>> turtle.pencolor('#32c18f')
>>> turtle.pencolor()
(50.0, 193.0, 143.0) | |
doc_78 |
Set the styles on the current Styler. Possibly uses styles from Styler.export. Parameters
styles:dict(str, Any)
List of attributes to add to Styler. Dict keys should contain only:
“apply”: list of styler functions, typically added with apply or applymap. “table_attributes”: HTML attributes, typically added with set_table_attributes. “table_styles”: CSS selectors and properties, typically added with set_table_styles. “hide_index”: whether the index is hidden, typically added with hide_index, or a boolean list for hidden levels. “hide_columns”: whether column headers are hidden, typically added with hide_columns, or a boolean list for hidden levels. “hide_index_names”: whether index names are hidden. “hide_column_names”: whether column header names are hidden. “css”: the css class names used. Returns
self:Styler
See also Styler.export
Export the non data dependent attributes to the current Styler. Examples
>>> styler = DataFrame([[1, 2], [3, 4]]).style
>>> styler2 = DataFrame([[9, 9, 9]]).style
>>> styler.hide(axis=0).highlight_max(axis=1)
>>> export = styler.export()
>>> styler2.use(export) | |
doc_79 |
Set the zorder for the artist. Artists with lower zorder values are drawn first. Parameters
levelfloat | |
doc_80 |
A LinearReLU module fused from Linear and ReLU modules, attached with FakeQuantize modules for weight, used in quantization aware training. We adopt the same interface as torch.nn.Linear. Similar to torch.nn.intrinsic.LinearReLU, with FakeQuantize modules initialized to default. Variables
~LinearReLU.weight – fake quant module for weight Examples: >>> m = nn.qat.LinearReLU(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30]) | |
doc_81 |
Bases: skimage.viewer.widgets.core.BaseWidget
__init__(name=None, text='') [source]
Initialize self. See help(type(self)) for accurate signature.
property text | |
doc_82 | Same as isexpr(st). | |
doc_83 | Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more. This function however can help you keep the context around for longer: from flask import stream_with_context, request, Response
@app.route('/stream')
def streamed_response():
@stream_with_context
def generate():
yield 'Hello '
yield request.args['name']
yield '!'
return Response(generate())
Alternatively it can also be used around a specific generator: from flask import stream_with_context, request, Response
@app.route('/stream')
def streamed_response():
def generate():
yield 'Hello '
yield request.args['name']
yield '!'
return Response(stream_with_context(generate()))
Changelog New in version 0.9. Parameters
generator_or_function (Union[Generator, Callable]) – Return type
Generator | |
doc_84 |
Return the JoinStyle for dashed lines. See also set_dash_joinstyle. | |
doc_85 | Asserts that a queryset qs matches a particular iterable of values values. If transform is provided, values is compared to a list produced by applying transform to each member of qs. By default, the comparison is also ordering dependent. If qs doesn’t provide an implicit ordering, you can set the ordered parameter to False, which turns the comparison into a collections.Counter comparison. If the order is undefined (if the given qs isn’t ordered and the comparison is against more than one ordered value), a ValueError is raised. Output in case of error can be customized with the msg argument. Changed in Django 3.2: The default value of transform argument was changed to None. New in Django 3.2: Support for direct comparison between querysets was added. Deprecated since version 3.2: If transform is not provided and values is a list of strings, it’s compared to a list produced by applying repr() to each member of qs. This behavior is deprecated and will be removed in Django 4.1. If you need it, explicitly set transform to repr. | |
doc_86 |
Set the offset of the container. Parameters
xy(float, float)
The (x, y) coordinates of the offset in display units. | |
doc_87 |
Return int position of the smallest value in the Series. If the minimum is achieved in multiple locations, the first row position is returned. Parameters
axis:{None}
Dummy argument for consistency with Series.
skipna:bool, default True
Exclude NA/null values when showing the result. *args, **kwargs
Additional arguments and keywords for compatibility with NumPy. Returns
int
Row position of the minimum value. See also Series.argmin
Return position of the minimum value. Series.argmax
Return position of the maximum value. numpy.ndarray.argmin
Equivalent method for numpy arrays. Series.idxmax
Return index label of the maximum values. Series.idxmin
Return index label of the minimum values. Examples Consider dataset containing cereal calories
>>> s = pd.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0,
... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0})
>>> s
Corn Flakes 100.0
Almond Delight 110.0
Cinnamon Toast Crunch 120.0
Cocoa Puff 110.0
dtype: float64
>>> s.argmax()
2
>>> s.argmin()
0
The maximum cereal calories is the third element and the minimum cereal calories is the first element, since series is zero-indexed. | |
doc_88 | See Migration guide for more details. tf.compat.v1.raw_ops.RepeatDataset
tf.raw_ops.RepeatDataset(
input_dataset, count, output_types, output_shapes, name=None
)
Args
input_dataset A Tensor of type variant.
count A Tensor of type int64. A scalar representing the number of times that input_dataset should be repeated. A value of -1 indicates that it should be repeated infinitely.
output_types A list of tf.DTypes that has length >= 1.
output_shapes A list of shapes (each a tf.TensorShape or list of ints) that has length >= 1.
name A name for the operation (optional).
Returns A Tensor of type variant. | |
doc_89 |
Update null elements with value in the same location in ‘other’. Combine two Series objects by filling null values in one Series with non-null values from the other Series. Result index will be the union of the two indexes. Parameters
other:Series
The value(s) to be used for filling null values. Returns
Series
The result of combining the provided Series with the other object. See also Series.combine
Perform element-wise operation on two Series using a given function. Examples
>>> s1 = pd.Series([1, np.nan])
>>> s2 = pd.Series([3, 4, 5])
>>> s1.combine_first(s2)
0 1.0
1 4.0
2 5.0
dtype: float64
Null values still persist if the location of that null value does not exist in other
>>> s1 = pd.Series({'falcon': np.nan, 'eagle': 160.0})
>>> s2 = pd.Series({'eagle': 200.0, 'duck': 30.0})
>>> s1.combine_first(s2)
duck 30.0
eagle 160.0
falcon NaN
dtype: float64 | |
doc_90 |
Alias for set_linewidth. | |
doc_91 | Returns the set of permission strings the user_obj has from their own user permissions. Returns an empty set if is_anonymous or is_active is False. | |
doc_92 | Computes the numerical rank of a matrix input, or of each matrix in a batched input. The matrix rank is computed as the number of singular values (or absolute eigenvalues when hermitian is True) that are greater than the specified tol threshold. If tol is not specified, tol is set to S.max(dim=-1)*max(input.shape[-2:])*eps, where S is the singular values (or absolute eigenvalues when hermitian is True), and eps is the epsilon value for the datatype of input. The epsilon value can be obtained using the eps attribute of torch.finfo. Supports input of float, double, cfloat and cdouble dtypes. Note When given inputs on a CUDA device, this function synchronizes that device with the CPU. Note The matrix rank is computed using singular value decomposition (see torch.linalg.svd()) by default. If hermitian is True, then input is assumed to be Hermitian (symmetric if real-valued), and the computation is done by obtaining the eigenvalues (see torch.linalg.eigvalsh()). Parameters
input (Tensor) – the input matrix of size (m, n) or the batch of matrices of size (*, m, n) where * is one or more batch dimensions.
tol (float, optional) – the tolerance value. Default is None
hermitian (bool, optional) – indicates whether input is Hermitian. Default is False. Keyword Arguments
out (Tensor, optional) – tensor to write the output to. Default is None. Examples: >>> a = torch.eye(10)
>>> torch.linalg.matrix_rank(a)
tensor(10)
>>> b = torch.eye(10)
>>> b[0, 0] = 0
>>> torch.linalg.matrix_rank(b)
tensor(9)
>>> a = torch.randn(4, 3, 2)
>>> torch.linalg.matrix_rank(a)
tensor([2, 2, 2, 2])
>>> a = torch.randn(2, 4, 2, 3)
>>> torch.linalg.matrix_rank(a)
tensor([[2, 2, 2, 2],
[2, 2, 2, 2]])
>>> a = torch.randn(2, 4, 3, 3, dtype=torch.complex64)
>>> torch.linalg.matrix_rank(a)
tensor([[3, 3, 3, 3],
[3, 3, 3, 3]])
>>> torch.linalg.matrix_rank(a, hermitian=True)
tensor([[3, 3, 3, 3],
[3, 3, 3, 3]])
>>> torch.linalg.matrix_rank(a, tol=1.0)
tensor([[3, 2, 2, 2],
[1, 2, 1, 2]])
>>> torch.linalg.matrix_rank(a, tol=1.0, hermitian=True)
tensor([[2, 2, 2, 1],
[1, 2, 2, 2]]) | |
doc_93 |
The category codes of this categorical. Codes are an array of integers which are the positions of the actual values in the categories array. There is no setter, use the other categorical methods and the normal item setter to change values in the categorical. Returns
ndarray[int]
A non-writable view of the codes array. | |
doc_94 | See Migration guide for more details. tf.compat.v1.raw_ops.QuantizedBiasAdd
tf.raw_ops.QuantizedBiasAdd(
input, bias, min_input, max_input, min_bias, max_bias, out_type, name=None
)
Broadcasts the values of bias on dimensions 0..N-2 of 'input'.
Args
input A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16.
bias A Tensor. Must be one of the following types: qint8, quint8, qint32, qint16, quint16. A 1D bias Tensor with size matching the last dimension of 'input'.
min_input A Tensor of type float32. The float value that the lowest quantized input value represents.
max_input A Tensor of type float32. The float value that the highest quantized input value represents.
min_bias A Tensor of type float32. The float value that the lowest quantized bias value represents.
max_bias A Tensor of type float32. The float value that the highest quantized bias value represents.
out_type A tf.DType from: tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16.
name A name for the operation (optional).
Returns A tuple of Tensor objects (output, min_out, max_out). output A Tensor of type out_type.
min_out A Tensor of type float32.
max_out A Tensor of type float32. | |
doc_95 | Set the default content type. ctype should either be text/plain or message/rfc822, although this is not enforced. The default content type is not stored in the Content-Type header, so it only affects the return value of the get_content_type methods when no Content-Type header is present in the message. | |
doc_96 |
Calculate texture properties of a GLCM. Compute a feature of a grey level co-occurrence matrix to serve as a compact summary of the matrix. The properties are computed as follows: ‘contrast’: \(\sum_{i,j=0}^{levels-1} P_{i,j}(i-j)^2\)
‘dissimilarity’: \(\sum_{i,j=0}^{levels-1}P_{i,j}|i-j|\)
‘homogeneity’: \(\sum_{i,j=0}^{levels-1}\frac{P_{i,j}}{1+(i-j)^2}\)
‘ASM’: \(\sum_{i,j=0}^{levels-1} P_{i,j}^2\)
‘energy’: \(\sqrt{ASM}\)
‘correlation’:
\[\sum_{i,j=0}^{levels-1} P_{i,j}\left[\frac{(i-\mu_i) \ (j-\mu_j)}{\sqrt{(\sigma_i^2)(\sigma_j^2)}}\right]\] Each GLCM is normalized to have a sum of 1 before the computation of texture properties. Parameters
Pndarray
Input array. P is the grey-level co-occurrence histogram for which to compute the specified property. The value P[i,j,d,theta] is the number of times that grey-level j occurs at a distance d and at an angle theta from grey-level i.
prop{‘contrast’, ‘dissimilarity’, ‘homogeneity’, ‘energy’, ‘correlation’, ‘ASM’}, optional
The property of the GLCM to compute. The default is ‘contrast’. Returns
results2-D ndarray
2-dimensional array. results[d, a] is the property ‘prop’ for the d’th distance and the a’th angle. References
1
The GLCM Tutorial Home Page, http://www.fp.ucalgary.ca/mhallbey/tutorial.htm Examples Compute the contrast for GLCMs with distances [1, 2] and angles [0 degrees, 90 degrees] >>> image = np.array([[0, 0, 1, 1],
... [0, 0, 1, 1],
... [0, 2, 2, 2],
... [2, 2, 3, 3]], dtype=np.uint8)
>>> g = greycomatrix(image, [1, 2], [0, np.pi/2], levels=4,
... normed=True, symmetric=True)
>>> contrast = greycoprops(g, 'contrast')
>>> contrast
array([[0.58333333, 1. ],
[1.25 , 2.75 ]]) | |
doc_97 | Return a string containing linesep characters as required to correctly fold the header according to policy. A cte_type of 8bit will be treated as if it were 7bit, since headers may not contain arbitrary binary data. If utf8 is False, non-ASCII data will be RFC 2047 encoded. | |
doc_98 | Resets an element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to None. | |
doc_99 | Return a contiguous flattened tensor. A copy is made only if needed. Parameters
input (Tensor) – the input tensor. Example: >>> t = torch.tensor([[[1, 2],
... [3, 4]],
... [[5, 6],
... [7, 8]]])
>>> torch.ravel(t)
tensor([1, 2, 3, 4, 5, 6, 7, 8]) |