API Reference¶
Graph source code in the DOT language. |
|
Directed graph source code in the DOT language. |
|
Verbatim DOT source code string to be rendered by Graphviz. |
|
Return string disabling special meaning of backslashes and |
|
Return string not treating |
|
|
|
|
|
|
|
Render file with |
|
Return |
|
Return |
|
Return DOT |
|
Open filepath with its default viewing application (platform-specific). |
|
Return the upstream version number tuple from |
Hint
The two main classes Graph
and Digraph
(creating undirected vs. directed graphs) have exactly the same API.
Their division reflects the fact that both graph syntaxes cannot be mixed.
Graph¶
- class graphviz.Graph(name=None, comment=None, filename=None, directory=None, format=None, engine=None, encoding='utf-8', graph_attr=None, node_attr=None, edge_attr=None, body=None, strict=False, *, renderer=None, formatter=None)[source]¶
Graph source code in the DOT language.
- Parameters:
comment (
Optional
[str
]) – Comment added to the first line of the source.filename – Filename for saving the source (defaults to
name
+'.gv'
).directory – (Sub)directory for source saving and rendering.
format (
Optional
[str
]) – Rendering output format ('pdf'
,'png'
, …).engine (
Optional
[str
]) – Layout command used ('dot'
,'neato'
, …).renderer (
Optional
[str
]) – Output renderer used ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – Output formatter used ('cairo'
,'gd'
, …).graph_attr – Mapping of
(attribute, value)
pairs for the graph.node_attr – Mapping of
(attribute, value)
pairs set for all nodes.edge_attr – Mapping of
(attribute, value)
pairs set for all edges.body – Iterable of verbatim lines (including their final newline) to add to the graph
body
.strict (bool) – Rendering should merge multi-edges.
Note
All parameters are optional and can be changed under their corresponding attribute name after instance creation.
- __iter__(subgraph=False)¶
Yield the DOT source code line by line (as graph or subgraph).
Yields: Line ending with a newline (
'\n'
).
- _repr_mimebundle_(include=None, exclude=None, **_)¶
Return the rendered graph as IPython mimebundle.
- Parameters:
- Return type:
- Returns:
Mapping from mimetypes to data.
Example
>>> doctest_mark_exe() >>> import graphviz >>> dot = graphviz.Graph() >>> dot._repr_mimebundle_() {'image/svg+xml': '<?xml version=... >>> dot._repr_mimebundle_(include=['image/png']) {'image/png': b'\x89PNG... >>> dot._repr_mimebundle_(include=[]) {} >>> dot._repr_mimebundle_(include=['image/svg+xml', 'image/jpeg'], ... exclude=['image/svg+xml']) {'image/jpeg': b'\xff... >>> list(dot._repr_mimebundle_(include=['image/png', 'image/jpeg'])) ['image/jpeg', 'image/png']
See also
IPython documentation: - https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#functions - https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject._repr_mimebundle_ # noqa: E501 - https://nbviewer.org/github/ipython/ipython/blob/master/examples/IPython%20Kernel/Custom%20Display%20Logic.ipynb#Custom-Mimetypes-with-_repr_mimebundle_ # noqa: E501
- attr(kw=None, _attributes=None, **attrs)¶
Add a general or graph/node/edge attribute statement.
- Parameters:
- Return type:
See the usage examples in the User Guide.
- clear(keep_attrs=False)¶
Reset content to an empty body, clear graph/node/egde_attr mappings.
- copy()¶
Return a copied instance of the object.
- Returns:
An independent copy of the current object.
- edge(tail_name, head_name, label=None, _attributes=None, **attrs)¶
Create an edge between two nodes.
- Parameters:
- Return type:
Note
The
tail_name
andhead_name
strings are separated by (optional) colon(s) intonode
name,port
name, andcompass
(e.g.sw
). See details in the User Guide.Attention
When rendering
label
, backslash-escapes and strings of the form<...>
have a special meaning. See the sections Backslash escapes and Quoting and HTML-like labels in the user guide for details.
- edges(tail_head_iter)¶
Create a bunch of edges.
- Parameters:
tail_head_iter – Iterable of
(tail_name, head_name)
pairs (format:node[:port[:compass]]
).- Return type:
Note
The
tail_name
andhead_name
strings are separated by (optional) colon(s) intonode
name,port
name, andcompass
(e.g.sw
). See details in the User Guide.
- node(name, label=None, _attributes=None, **attrs)¶
Create a node.
- Parameters:
- Return type:
Attention
When rendering
label
, backslash-escapes and strings of the form<...>
have a special meaning. See the sections Backslash escapes and Quoting and HTML-like labels in the user guide for details.
- pipe(format=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, *, engine=None, encoding=None)¶
Return the source piped through the Graphviz layout command.
- Parameters:
format (
Optional
[str
]) – The output format used for rendering ('pdf'
,'png'
, etc.).renderer (
Optional
[str
]) – The output renderer used for rendering ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – The output formatter used for rendering ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (bool) – Suppress
stderr
output from the layout subprocess.engine (
Optional
[str
]) – Layout engine for rendering ('dot'
,'neato'
, …).encoding (
Optional
[str
]) – Encoding for decoding the stdout.
- Return type:
- Returns:
- Bytes or if encoding is given decoded string
(stdout of the layout command).
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.
Example
>>> doctest_mark_exe() >>> import graphviz >>> source = 'graph { spam }' >>> graphviz.Source(source, format='svg').pipe()[:14] b'<?xml version=' >>> graphviz.Source(source, format='svg').pipe(encoding='ascii')[:14] '<?xml version=' >>> graphviz.Source(source, format='svg').pipe(encoding='utf-8')[:14] '<?xml version='
- render(filename=None, directory=None, view=False, cleanup=False, format=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, quiet_view=False, *, outfile=None, engine=None, raise_if_result_exists=False, overwrite_source=False)¶
Save the source to file and render with the Graphviz engine.
- Parameters:
filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults toname
+'.gv'
).sdirectory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.view (bool) – Open the rendered result with the default application.
cleanup (bool) – Delete the source file after successful rendering.
format (
Optional
[str
]) – The output format used for rendering ('pdf'
,'png'
, etc.).renderer (
Optional
[str
]) – The output renderer used for rendering ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – The output formatter used for rendering ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (bool) – Suppress
stderr
output from the layout subprocess.quiet_view (bool) – Suppress
stderr
output from the viewer process (impliesview=True
, ineffective on Windows platform).outfile (
Union
[PathLike
,str
,None
]) – Path for the rendered output file.engine (
Optional
[str
]) – Layout engine for rendering ('dot'
,'neato'
, …).raise_if_result_exists (
bool
) – Raisegraphviz.FileExistsError
if the result file exists.overwrite_source (
bool
) – Allowdot
to write to the file it reads from. Incompatible withraise_if_result_exists
.
- Return type:
- Returns:
The (possibly relative) path of the rendered file.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.ValueError – If
outfile
is the same file as the source file unlessoverwite_source=True
.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.RuntimeError – If viewer opening is requested but not supported.
Example
>>> doctest_mark_exe() >>> import graphviz >>> dot = graphviz.Graph(name='spam', directory='doctest-output') >>> dot.render(format='png').replace('\\', '/') 'doctest-output/spam.gv.png' >>> dot.render(outfile='spam.svg').replace('\\', '/') 'doctest-output/spam.svg'
Note
The layout command is started from the directory of
filepath
, so that references to external files (e.g.[image=images/camelot.png]
) can be given as paths relative to the DOT source file.
- save(filename=None, directory=None, *, skip_existing=False)¶
Save the DOT source to file. Ensure the file ends with a newline.
- Parameters:
- Return type:
- Returns:
The (possibly relative) path of the saved source file.
- subgraph(graph=None, name=None, comment=None, graph_attr=None, node_attr=None, edge_attr=None, body=None)¶
- Add the current content of the given sole
graph
argument as subgraph or return a context manager returning a new graph instance created with the given (
name
,comment
, etc.) arguments whose content is added as subgraph when leaving the context manager’swith
-block.
- Parameters:
graph – An instance of the same kind (
Graph
,Digraph
) as the current graph (sole argument in non-with-block use).comment (
Optional
[str
]) – Subgraph comment (with
-block use).graph_attr – Subgraph-level attribute-value mapping (
with
-block use).node_attr – Node-level attribute-value mapping (
with
-block use).edge_attr – Edge-level attribute-value mapping (
with
-block use).body – Verbatim lines to add to the subgraph
body
(with
-block use).
See the usage examples in the User Guide.
When used as a context manager, the returned new graph instance uses
strict=None
and the parent graph’s values fordirectory
,format
,engine
, andencoding
by default.Note
If the
name
of the subgraph begins with'cluster'
(all lowercase) the layout engine will treat it as a special cluster subgraph.- Add the current content of the given sole
- unflatten(stagger=None, fanout=False, chain=None)¶
- Return a new
Source
instance with the source piped through the Graphviz unflatten preprocessor.
- Parameters:
- Return type:
- Returns:
Prepocessed DOT source code (improved layout aspect ratio).
- Raises:
graphviz.RequiredArgumentError – If
fanout
is given butstagger
is None.graphviz.ExecutableNotFound – If the Graphviz
unflatten
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the unflattening ‘unflatten’ subprocess is non-zero.
See also
Upstream documentation: https://www.graphviz.org/pdf/unflatten.1.pdf
- Return a new
- view(filename=None, directory=None, cleanup=False, quiet=False, quiet_view=False)¶
Save the source to file, open the rendered result in a viewer.
Convenience short-cut for running
.render(view=True)
.- Parameters:
filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults toname
+'.gv'
).directory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.cleanup (bool) – Delete the source file after successful rendering.
quiet (bool) – Suppress
stderr
output from the layout subprocess.quiet_view (bool) – Suppress
stderr
output from the viewer process (ineffective on Windows).
- Return type:
- Returns:
The (possibly relative) path of the rendered file.
- Raises:
graphviz.ExecutableNotFound – If the Graphviz executable is not found.
graphviz.CalledProcessError – If the exit status is non-zero.
RuntimeError – If opening the viewer is not supported.
Short-cut method for calling
render()
withview=True
.Note
There is no option to wait for the application to close, and no way to retrieve the application’s exit status.
Digraph¶
- class graphviz.Digraph(name=None, comment=None, filename=None, directory=None, format=None, engine=None, encoding='utf-8', graph_attr=None, node_attr=None, edge_attr=None, body=None, strict=False, *, renderer=None, formatter=None)[source]¶
Directed graph source code in the DOT language.
- Parameters:
comment (
Optional
[str
]) – Comment added to the first line of the source.filename – Filename for saving the source (defaults to
name
+'.gv'
).directory – (Sub)directory for source saving and rendering.
format (
Optional
[str
]) – Rendering output format ('pdf'
,'png'
, …).engine (
Optional
[str
]) – Layout command used ('dot'
,'neato'
, …).renderer (
Optional
[str
]) – Output renderer used ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – Output formatter used ('cairo'
,'gd'
, …).graph_attr – Mapping of
(attribute, value)
pairs for the graph.node_attr – Mapping of
(attribute, value)
pairs set for all nodes.edge_attr – Mapping of
(attribute, value)
pairs set for all edges.body – Iterable of verbatim lines (including their final newline) to add to the graph
body
.strict (bool) – Rendering should merge multi-edges.
Note
All parameters are optional and can be changed under their corresponding attribute name after instance creation.
- __iter__(subgraph=False)¶
Yield the DOT source code line by line (as graph or subgraph).
Yields: Line ending with a newline (
'\n'
).
- _repr_mimebundle_(include=None, exclude=None, **_)¶
Return the rendered graph as IPython mimebundle.
- Parameters:
- Return type:
- Returns:
Mapping from mimetypes to data.
Example
>>> doctest_mark_exe() >>> import graphviz >>> dot = graphviz.Graph() >>> dot._repr_mimebundle_() {'image/svg+xml': '<?xml version=... >>> dot._repr_mimebundle_(include=['image/png']) {'image/png': b'\x89PNG... >>> dot._repr_mimebundle_(include=[]) {} >>> dot._repr_mimebundle_(include=['image/svg+xml', 'image/jpeg'], ... exclude=['image/svg+xml']) {'image/jpeg': b'\xff... >>> list(dot._repr_mimebundle_(include=['image/png', 'image/jpeg'])) ['image/jpeg', 'image/png']
See also
IPython documentation: - https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#functions - https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject._repr_mimebundle_ # noqa: E501 - https://nbviewer.org/github/ipython/ipython/blob/master/examples/IPython%20Kernel/Custom%20Display%20Logic.ipynb#Custom-Mimetypes-with-_repr_mimebundle_ # noqa: E501
- attr(kw=None, _attributes=None, **attrs)¶
Add a general or graph/node/edge attribute statement.
- Parameters:
- Return type:
See the usage examples in the User Guide.
- clear(keep_attrs=False)¶
Reset content to an empty body, clear graph/node/egde_attr mappings.
- copy()¶
Return a copied instance of the object.
- Returns:
An independent copy of the current object.
- edge(tail_name, head_name, label=None, _attributes=None, **attrs)¶
Create an edge between two nodes.
- Parameters:
- Return type:
Note
The
tail_name
andhead_name
strings are separated by (optional) colon(s) intonode
name,port
name, andcompass
(e.g.sw
). See details in the User Guide.Attention
When rendering
label
, backslash-escapes and strings of the form<...>
have a special meaning. See the sections Backslash escapes and Quoting and HTML-like labels in the user guide for details.
- edges(tail_head_iter)¶
Create a bunch of edges.
- Parameters:
tail_head_iter – Iterable of
(tail_name, head_name)
pairs (format:node[:port[:compass]]
).- Return type:
Note
The
tail_name
andhead_name
strings are separated by (optional) colon(s) intonode
name,port
name, andcompass
(e.g.sw
). See details in the User Guide.
- node(name, label=None, _attributes=None, **attrs)¶
Create a node.
- Parameters:
- Return type:
Attention
When rendering
label
, backslash-escapes and strings of the form<...>
have a special meaning. See the sections Backslash escapes and Quoting and HTML-like labels in the user guide for details.
- pipe(format=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, *, engine=None, encoding=None)¶
Return the source piped through the Graphviz layout command.
- Parameters:
format (
Optional
[str
]) – The output format used for rendering ('pdf'
,'png'
, etc.).renderer (
Optional
[str
]) – The output renderer used for rendering ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – The output formatter used for rendering ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (bool) – Suppress
stderr
output from the layout subprocess.engine (
Optional
[str
]) – Layout engine for rendering ('dot'
,'neato'
, …).encoding (
Optional
[str
]) – Encoding for decoding the stdout.
- Return type:
- Returns:
- Bytes or if encoding is given decoded string
(stdout of the layout command).
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.
Example
>>> doctest_mark_exe() >>> import graphviz >>> source = 'graph { spam }' >>> graphviz.Source(source, format='svg').pipe()[:14] b'<?xml version=' >>> graphviz.Source(source, format='svg').pipe(encoding='ascii')[:14] '<?xml version=' >>> graphviz.Source(source, format='svg').pipe(encoding='utf-8')[:14] '<?xml version='
- render(filename=None, directory=None, view=False, cleanup=False, format=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, quiet_view=False, *, outfile=None, engine=None, raise_if_result_exists=False, overwrite_source=False)¶
Save the source to file and render with the Graphviz engine.
- Parameters:
filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults toname
+'.gv'
).sdirectory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.view (bool) – Open the rendered result with the default application.
cleanup (bool) – Delete the source file after successful rendering.
format (
Optional
[str
]) – The output format used for rendering ('pdf'
,'png'
, etc.).renderer (
Optional
[str
]) – The output renderer used for rendering ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – The output formatter used for rendering ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (bool) – Suppress
stderr
output from the layout subprocess.quiet_view (bool) – Suppress
stderr
output from the viewer process (impliesview=True
, ineffective on Windows platform).outfile (
Union
[PathLike
,str
,None
]) – Path for the rendered output file.engine (
Optional
[str
]) – Layout engine for rendering ('dot'
,'neato'
, …).raise_if_result_exists (
bool
) – Raisegraphviz.FileExistsError
if the result file exists.overwrite_source (
bool
) – Allowdot
to write to the file it reads from. Incompatible withraise_if_result_exists
.
- Return type:
- Returns:
The (possibly relative) path of the rendered file.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.ValueError – If
outfile
is the same file as the source file unlessoverwite_source=True
.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.RuntimeError – If viewer opening is requested but not supported.
Example
>>> doctest_mark_exe() >>> import graphviz >>> dot = graphviz.Graph(name='spam', directory='doctest-output') >>> dot.render(format='png').replace('\\', '/') 'doctest-output/spam.gv.png' >>> dot.render(outfile='spam.svg').replace('\\', '/') 'doctest-output/spam.svg'
Note
The layout command is started from the directory of
filepath
, so that references to external files (e.g.[image=images/camelot.png]
) can be given as paths relative to the DOT source file.
- save(filename=None, directory=None, *, skip_existing=False)¶
Save the DOT source to file. Ensure the file ends with a newline.
- Parameters:
- Return type:
- Returns:
The (possibly relative) path of the saved source file.
- subgraph(graph=None, name=None, comment=None, graph_attr=None, node_attr=None, edge_attr=None, body=None)¶
- Add the current content of the given sole
graph
argument as subgraph or return a context manager returning a new graph instance created with the given (
name
,comment
, etc.) arguments whose content is added as subgraph when leaving the context manager’swith
-block.
- Parameters:
graph – An instance of the same kind (
Graph
,Digraph
) as the current graph (sole argument in non-with-block use).comment (
Optional
[str
]) – Subgraph comment (with
-block use).graph_attr – Subgraph-level attribute-value mapping (
with
-block use).node_attr – Node-level attribute-value mapping (
with
-block use).edge_attr – Edge-level attribute-value mapping (
with
-block use).body – Verbatim lines to add to the subgraph
body
(with
-block use).
See the usage examples in the User Guide.
When used as a context manager, the returned new graph instance uses
strict=None
and the parent graph’s values fordirectory
,format
,engine
, andencoding
by default.Note
If the
name
of the subgraph begins with'cluster'
(all lowercase) the layout engine will treat it as a special cluster subgraph.- Add the current content of the given sole
- unflatten(stagger=None, fanout=False, chain=None)¶
- Return a new
Source
instance with the source piped through the Graphviz unflatten preprocessor.
- Parameters:
- Return type:
- Returns:
Prepocessed DOT source code (improved layout aspect ratio).
- Raises:
graphviz.RequiredArgumentError – If
fanout
is given butstagger
is None.graphviz.ExecutableNotFound – If the Graphviz
unflatten
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the unflattening ‘unflatten’ subprocess is non-zero.
See also
Upstream documentation: https://www.graphviz.org/pdf/unflatten.1.pdf
- Return a new
- view(filename=None, directory=None, cleanup=False, quiet=False, quiet_view=False)¶
Save the source to file, open the rendered result in a viewer.
Convenience short-cut for running
.render(view=True)
.- Parameters:
filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults toname
+'.gv'
).directory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.cleanup (bool) – Delete the source file after successful rendering.
quiet (bool) – Suppress
stderr
output from the layout subprocess.quiet_view (bool) – Suppress
stderr
output from the viewer process (ineffective on Windows).
- Return type:
- Returns:
The (possibly relative) path of the rendered file.
- Raises:
graphviz.ExecutableNotFound – If the Graphviz executable is not found.
graphviz.CalledProcessError – If the exit status is non-zero.
RuntimeError – If opening the viewer is not supported.
Short-cut method for calling
render()
withview=True
.Note
There is no option to wait for the application to close, and no way to retrieve the application’s exit status.
Source¶
- class graphviz.Source(source, filename=None, directory=None, format=None, engine=None, encoding='utf-8', *, renderer=None, formatter=None, loaded_from_path=None)[source]¶
Verbatim DOT source code string to be rendered by Graphviz.
- Parameters:
source (
str
) – The verbatim DOT source code string.filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults to'Source.gv'
).directory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.format (
Optional
[str
]) – Rendering output format ('pdf'
,'png'
, …).engine (
Optional
[str
]) – Layout engine used ('dot'
,'neato'
, …).
Note
All parameters except
source
are optional. All of them can be changed under their corresponding attribute name after instance creation.- __iter__()[source]¶
Yield the DOT source code read from file line by line.
Yields: Line ending with a newline (
'\n'
).
- _repr_mimebundle_(include=None, exclude=None, **_)¶
Return the rendered graph as IPython mimebundle.
- Parameters:
- Return type:
- Returns:
Mapping from mimetypes to data.
Example
>>> doctest_mark_exe() >>> import graphviz >>> dot = graphviz.Graph() >>> dot._repr_mimebundle_() {'image/svg+xml': '<?xml version=... >>> dot._repr_mimebundle_(include=['image/png']) {'image/png': b'\x89PNG... >>> dot._repr_mimebundle_(include=[]) {} >>> dot._repr_mimebundle_(include=['image/svg+xml', 'image/jpeg'], ... exclude=['image/svg+xml']) {'image/jpeg': b'\xff... >>> list(dot._repr_mimebundle_(include=['image/png', 'image/jpeg'])) ['image/jpeg', 'image/png']
See also
IPython documentation: - https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#functions - https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject._repr_mimebundle_ # noqa: E501 - https://nbviewer.org/github/ipython/ipython/blob/master/examples/IPython%20Kernel/Custom%20Display%20Logic.ipynb#Custom-Mimetypes-with-_repr_mimebundle_ # noqa: E501
- copy()¶
Return a copied instance of the object.
- Returns:
An independent copy of the current object.
- classmethod from_file(cls, filename, directory=None, format=None, engine=None, encoding='utf-8', renderer=None, formatter=None)[source]¶
Return an instance with the source string read from the given file.
- Parameters:
filename (
Union
[PathLike
,str
]) – Filename for loading/saving the source.directory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source loading/saving and rendering.format (
Optional
[str
]) – Rendering output format ('pdf'
,'png'
, …).engine (
Optional
[str
]) – Layout command used ('dot'
,'neato'
, …).encoding (
Optional
[str
]) – Encoding for loading/saving the source.
- Return type:
- pipe(format=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, *, engine=None, encoding=None)¶
Return the source piped through the Graphviz layout command.
- Parameters:
format (
Optional
[str
]) – The output format used for rendering ('pdf'
,'png'
, etc.).renderer (
Optional
[str
]) – The output renderer used for rendering ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – The output formatter used for rendering ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (bool) – Suppress
stderr
output from the layout subprocess.engine (
Optional
[str
]) – Layout engine for rendering ('dot'
,'neato'
, …).encoding (
Optional
[str
]) – Encoding for decoding the stdout.
- Return type:
- Returns:
- Bytes or if encoding is given decoded string
(stdout of the layout command).
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.
Example
>>> doctest_mark_exe() >>> import graphviz >>> source = 'graph { spam }' >>> graphviz.Source(source, format='svg').pipe()[:14] b'<?xml version=' >>> graphviz.Source(source, format='svg').pipe(encoding='ascii')[:14] '<?xml version=' >>> graphviz.Source(source, format='svg').pipe(encoding='utf-8')[:14] '<?xml version='
- render(filename=None, directory=None, view=False, cleanup=False, format=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, quiet_view=False, *, outfile=None, engine=None, raise_if_result_exists=False, overwrite_source=False)¶
Save the source to file and render with the Graphviz engine.
- Parameters:
filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults toname
+'.gv'
).sdirectory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.view (bool) – Open the rendered result with the default application.
cleanup (bool) – Delete the source file after successful rendering.
format (
Optional
[str
]) – The output format used for rendering ('pdf'
,'png'
, etc.).renderer (
Optional
[str
]) – The output renderer used for rendering ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – The output formatter used for rendering ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (bool) – Suppress
stderr
output from the layout subprocess.quiet_view (bool) – Suppress
stderr
output from the viewer process (impliesview=True
, ineffective on Windows platform).outfile (
Union
[PathLike
,str
,None
]) – Path for the rendered output file.engine (
Optional
[str
]) – Layout engine for rendering ('dot'
,'neato'
, …).raise_if_result_exists (
bool
) – Raisegraphviz.FileExistsError
if the result file exists.overwrite_source (
bool
) – Allowdot
to write to the file it reads from. Incompatible withraise_if_result_exists
.
- Return type:
- Returns:
The (possibly relative) path of the rendered file.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.ValueError – If
outfile
is the same file as the source file unlessoverwite_source=True
.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.RuntimeError – If viewer opening is requested but not supported.
Example
>>> doctest_mark_exe() >>> import graphviz >>> dot = graphviz.Graph(name='spam', directory='doctest-output') >>> dot.render(format='png').replace('\\', '/') 'doctest-output/spam.gv.png' >>> dot.render(outfile='spam.svg').replace('\\', '/') 'doctest-output/spam.svg'
Note
The layout command is started from the directory of
filepath
, so that references to external files (e.g.[image=images/camelot.png]
) can be given as paths relative to the DOT source file.
- save(filename=None, directory=None, *, skip_existing=None)[source]¶
Save the DOT source to file. Ensure the file ends with a newline.
- Parameters:
filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults toname
+'.gv'
)directory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.skip_existing (
Optional
[bool
]) – Skip write if file exists (default:None
). By default skips if instance was loaded from the target path:.from_file(self.filepath)
.
- Return type:
- Returns:
The (possibly relative) path of the saved source file.
- property source: str¶
The DOT source code as string.
Normalizes so that the string always ends in a final newline.
- unflatten(stagger=None, fanout=False, chain=None)¶
- Return a new
Source
instance with the source piped through the Graphviz unflatten preprocessor.
- Parameters:
- Return type:
- Returns:
Prepocessed DOT source code (improved layout aspect ratio).
- Raises:
graphviz.RequiredArgumentError – If
fanout
is given butstagger
is None.graphviz.ExecutableNotFound – If the Graphviz
unflatten
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the unflattening ‘unflatten’ subprocess is non-zero.
See also
Upstream documentation: https://www.graphviz.org/pdf/unflatten.1.pdf
- Return a new
- view(filename=None, directory=None, cleanup=False, quiet=False, quiet_view=False)¶
Save the source to file, open the rendered result in a viewer.
Convenience short-cut for running
.render(view=True)
.- Parameters:
filename (
Union
[PathLike
,str
,None
]) – Filename for saving the source (defaults toname
+'.gv'
).directory (
Union
[PathLike
,str
,None
]) – (Sub)directory for source saving and rendering.cleanup (bool) – Delete the source file after successful rendering.
quiet (bool) – Suppress
stderr
output from the layout subprocess.quiet_view (bool) – Suppress
stderr
output from the viewer process (ineffective on Windows).
- Return type:
- Returns:
The (possibly relative) path of the rendered file.
- Raises:
graphviz.ExecutableNotFound – If the Graphviz executable is not found.
graphviz.CalledProcessError – If the exit status is non-zero.
RuntimeError – If opening the viewer is not supported.
Short-cut method for calling
render()
withview=True
.Note
There is no option to wait for the application to close, and no way to retrieve the application’s exit status.
Quoting/escaping¶
- graphviz.escape(s)[source]¶
Return string disabling special meaning of backslashes and
'<...>'
.- Parameters:
s (
str
) – String in which backslashes and'<...>'
should be treated as literal.- Return type:
- Returns:
Escaped string subclass instance.
- Raises:
TypeError – If
s
is not astr
.
Example
>>> import graphviz >>> print(graphviz.escape(r'\l')) \\l
See also
Upstream documentation: https://www.graphviz.org/doc/info/attrs.html#k:escString
- graphviz.nohtml(s)[source]¶
Return string not treating
'<...>'
as DOT HTML string in quoting.- Parameters:
s (
str
) – String in which leading'<'
and trailing'>'
should be treated as literal.- Return type:
- Returns:
String subclass instance.
- Raises:
TypeError – If
s
is not astr
.
Example
>>> import graphviz >>> g = graphviz.Graph() >>> g.node(graphviz.nohtml('<>-*-<>')) >>> print(g.source) graph { "<>-*-<>" }
Exceptions¶
- exception graphviz.ExecutableNotFound(args)[source]¶
RuntimeError
raised if the Graphviz executable is not found.
- exception graphviz.CalledProcessError(returncode, cmd, output=None, stderr=None)[source]¶
CalledProcessError
raised if a subprocessreturncode
is not0
.
- exception graphviz.RequiredArgumentError[source]¶
TypeError
raised if a required argument is missing.
- exception graphviz.FileExistsError[source]¶
FileExistsError
raised withraise_if_exists=True
.
Warnings¶
- exception graphviz.UnknownSuffixWarning[source]¶
RuntimeWarning
raised if the suffix ofoutfile
is unknown and the givenformat
is used instead.
- exception graphviz.FormatSuffixMismatchWarning[source]¶
UserWarning
raised if the suffixoutfile
does not match the givenformat
.
- exception graphviz.DotSyntaxWarning[source]¶
RuntimeWarning
raised if a quoted string is expected to cause aCalledProcessError
from rendering.
Low-level functions¶
The functions in this section are provided to work directly with existing files and strings instead of using the object-oriented DOT creation methods documented above.
- graphviz.render(engine, format=None, filepath=None, renderer=None, formatter=None, neato_no_op=None, quiet=False, *, outfile=None, raise_if_result_exists=False, overwrite_filepath=False)[source]¶
Render file with
engine
intoformat
and return result filename.- Parameters:
engine (
str
) – Layout engine for rendering ('dot'
,'neato'
, …).format (
Optional
[str
]) – Output format for rendering ('pdf'
,'png'
, …). Can be omitted if anoutfile
with a knownformat
is given, i.e. ifoutfile
ends with a known.{format}
suffix.filepath (
Union
[PathLike
,str
,None
]) – Path to the DOT source file to render. Can be omitted ifoutfile
is given, in which case it defaults tooutfile.with_suffix('.gv')
.renderer (
Optional
[str
]) – Output renderer ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – Output formatter ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (
bool
) – Suppressstderr
output from the layout subprocess.outfile (
Union
[PathLike
,str
,None
]) – Path for the rendered output file.raise_if_result_exists (
bool
) – Raisegraphviz.FileExistsError
if the result file exists.overwrite_filepath (
bool
) – Allowdot
to write to the file it reads from. Incompatible withraise_if_result_exists
.
- Return type:
- Returns:
The (possibly relative) path of the rendered file.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
format
orfilepath
are None unlessoutfile
is given.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.ValueError – If
outfile
andfilename
are the same file unlessoverwite_filepath=True
.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.graphviz.FileExistsError – If
raise_if_exists
and the result file exists.
- Warns:
graphviz.UnknownSuffixWarning – If the suffix of
outfile
is empty or unknown.graphviz.FormatSuffixMismatchWarning – If the suffix of
outfile
does not match the givenformat
.
Example
>>> doctest_mark_exe() >>> import pathlib >>> import graphviz >>> assert pathlib.Path('doctest-output/spam.gv').write_text('graph { spam }') == 14 >>> graphviz.render('dot', 'png', 'doctest-output/spam.gv').replace('\\', '/') 'doctest-output/spam.gv.png' >>> graphviz.render('dot', filepath='doctest-output/spam.gv', ... outfile='doctest-output/spam.png').replace('\\', '/') 'doctest-output/spam.png' >>> graphviz.render('dot', outfile='doctest-output/spam.pdf').replace('\\', '/') 'doctest-output/spam.pdf'
Note
The layout command is started from the directory of
filepath
, so that references to external files (e.g.[image=images/camelot.png]
) can be given as paths relative to the DOT source file.See also
Upstream docs: https://www.graphviz.org/doc/info/command.html
- graphviz.pipe(engine, format, data, renderer=None, formatter=None, neato_no_op=None, quiet=False)[source]¶
Return
data
(bytes
) piped throughengine
intoformat
asbytes
.- Parameters:
engine (
str
) – Layout engine for rendering ('dot'
,'neato'
, …).format (
str
) – Output format for rendering ('pdf'
,'png'
, …).data (
bytes
) – Binary (encoded) DOT source bytes to render.renderer (
Optional
[str
]) – Output renderer ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – Output formatter ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (
bool
) – Suppressstderr
output from the layout subprocess.
- Return type:
- Returns:
Binary (encoded) stdout of the layout command.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.
Example
>>> doctest_mark_exe() >>> import graphviz >>> graphviz.pipe('dot', 'svg', b'graph { hello -- world }')[:14] b'<?xml version='
Note
The layout command is started from the current directory.
- graphviz.pipe_string(engine, format, input_string, *, encoding, renderer=None, formatter=None, neato_no_op=None, quiet=False)[source]¶
Return
input_string
piped throughengine
intoformat
as string.- Parameters:
engine (
str
) – Layout engine for rendering ('dot'
,'neato'
, …).format (
str
) – Output format for rendering ('pdf'
,'png'
, …).input_string (
str
) – Binary (encoded) DOT source bytes to render.encoding (
str
) – Encoding to en/decode subprocess stdin and stdout (required).renderer (
Optional
[str
]) – Output renderer ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – Output formatter ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (
bool
) – Suppressstderr
output from the layout subprocess.
- Return type:
- Returns:
Decoded stdout of the layout command.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.
Example
>>> doctest_mark_exe() >>> import graphviz >>> graphviz.pipe_string('dot', 'svg', 'graph { spam }', ... encoding='ascii')[:14] '<?xml version='
Note
The layout command is started from the current directory.
- graphviz.pipe_lines(engine, format, input_lines, *, input_encoding, renderer=None, formatter=None, neato_no_op=None, quiet=False)[source]¶
Return
input_lines
piped throughengine
intoformat
asbytes
.- Parameters:
engine (
str
) – Layout engine for rendering ('dot'
,'neato'
, …).format (
str
) – Output format for rendering ('pdf'
,'png'
, …).input_lines (
Iterator
[str
]) – DOT source lines to render (including final newline).input_encoding (
str
) – Encode input_lines for subprocess stdin (required).renderer (
Optional
[str
]) – Output renderer ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – Output formatter ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (
bool
) – Suppressstderr
output from the layout subprocess.
- Return type:
- Returns:
Binary stdout of the layout command.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.
Example
>>> doctest_mark_exe() >>> import graphviz >>> graphviz.pipe_lines('dot', 'svg', iter(['graph { spam }\n']), ... input_encoding='ascii')[:14] b'<?xml version='
Note
The layout command is started from the current directory.
- graphviz.pipe_lines_string(engine, format, input_lines, *, encoding, renderer=None, formatter=None, neato_no_op=None, quiet=False)[source]¶
Return
input_lines
piped throughengine
intoformat
as string.- Parameters:
engine (
str
) – Layout engine for rendering ('dot'
,'neato'
, …).format (
str
) – Output format for rendering ('pdf'
,'png'
, …).input_lines (
Iterator
[str
]) – DOT source lines to render (including final newline).encoding (
str
) – Encoding to en/decode subprocess stdin and stdout (required).renderer (
Optional
[str
]) – Output renderer ('cairo'
,'gd'
, …).formatter (
Optional
[str
]) – Output formatter ('cairo'
,'gd'
, …).neato_no_op (
Union
[bool
,int
,None
]) – Neato layout engine no-op flag.quiet (
bool
) – Suppressstderr
output from the layout subprocess.
- Return type:
- Returns:
Decoded stdout of the layout command.
- Raises:
ValueError – If
engine
,format
,renderer
, orformatter
are unknown.graphviz.RequiredArgumentError – If
formatter
is given butrenderer
is None.graphviz.ExecutableNotFound – If the Graphviz
dot
executable is not found.graphviz.CalledProcessError – If the returncode (exit status) of the rendering
dot
subprocess is non-zero.
Example
>>> doctest_mark_exe() >>> import graphviz >>> graphviz.pipe_lines_string('dot', 'svg', iter(['graph { spam }\n']), ... encoding='ascii')[:14] '<?xml version='
Note
The layout command is started from the current directory.
- graphviz.unflatten(source, stagger=None, fanout=False, chain=None, encoding='utf-8')[source]¶
Return DOT
source
piped throughunflatten
preprocessor as string.- Parameters:
source (
str
) – DOT source to process (improve layout aspect ratio).stagger (
Optional
[int
]) – Stagger the minimum length of leaf edges between 1 and this small integer.fanout (
bool
) – Fanout nodes with indegree = outdegree = 1 when staggering (requiresstagger
).chain (
Optional
[int
]) – Form disconnected nodes into chains of up to this many nodes.encoding (
str
) – Encoding to encode unflatten stdin and decode its stdout.
- Return type:
- Returns:
Decoded stdout of the Graphviz unflatten command.
- Raises:
graphviz.RequiredArgumentError – If
fanout
is given but nostagger
.graphviz.ExecutableNotFound – If the Graphviz ‘unflatten’ executable is not found.
graphviz.CalledProcessError – If the returncode (exit status) of the unflattening ‘unflatten’ subprocess is non-zero.
See also
Upstream documentation: https://www.graphviz.org/pdf/unflatten.1.pdf
- graphviz.view(filepath, quiet=False)[source]¶
Open filepath with its default viewing application (platform-specific).
- Parameters:
- Raises:
RuntimeError – If the current platform is not supported.
- Return type:
Note
There is no option to wait for the application to close, and no way to retrieve the application’s exit status.
Constants¶
Manually maintained allowlists for Graphviz parameters
(cf. man dot, outputs, and dot -T:
output):
Supported IPython/Jupyter display formats:
- graphviz.SUPPORTED_JUPYTER_FORMATS¶
set
of supported formats for_repr_mimebundle_()
('svg'
,'png'
, …).
Names of upstream binaries:
- graphviz.DOT_BINARY¶
pathlib.Path
of rendering command (Path('dot')
).
- graphviz.UNFLATTEN_BINARY¶
pathlib.Path
of unflatten command (Path('unflatten')
).
Defaults¶
Functions for setting package-wide defaults for engine
and format
:
Attention
These functions are provided mainly to simplify testing
but may also be used by end-users for convenience in scripts.
They should be avoided in library code.
Prefer passing or setting engine
and format
explicitly
if you create a library that depends on this package.
- graphviz.set_default_engine(engine)[source]¶
Change the default
engine
and return the old default value.
- graphviz.set_default_format(format)[source]¶
Change the default
format
and return the old default value.
Function for setting the package-wide default for IPython/Jupyter display format:
Attention
This function is provided for end-users. Prefer IPython.display functions in library code.
Other¶
- graphviz.version()[source]¶
Return the upstream version number tuple from
stderr
ofdot -V
.- Return type:
- Returns:
Two, three, or four
int
versiontuple
.- Raises:
graphviz.ExecutableNotFound – If the Graphviz executable is not found.
graphviz.CalledProcessError – If the exit status is non-zero.
RuntimeError – If the output cannot be parsed into a version number.
Example
>>> doctest_mark_exe() >>> import graphviz >>> graphviz.version() (...)
Note
Ignores the
~dev.<YYYYmmdd.HHMM>
portion of development versions.See also
Upstream release version entry format: https://gitlab.com/graphviz/graphviz/-/blob/f94e91ba819cef51a4b9dcb2d76153684d06a913/gen_version.py#L17-20
Online help()
(internal)¶
Results of help()
for graphviz.Graph
, graphviz.Digraph
,
and graphviz.Source
for reference.
Attention
The outputs in this section may contain (some) internals (implementation details). They serve to record some current implementation details and their changes. They mainly serve the development process (e.g. checking the MRO). They might be outdated. They may change at any point in time. See above for the full (public) API. First shalt thou take out the Holy Pin. Then shalt thou count to three, no more, no less.
To update help()
outputs below:
$ ./update-help.py
To debug: remove +SKIP
flags below and check output(s):
$ ./run-tests.py docs --doctest-report none
Graph¶
Partially syntax-highlighted: https://github.com/xflr6/graphviz/blob/master/docs/api.rst#graph-1
>>> import graphviz
>>> help(graphviz.Graph)
Help on class Graph in module graphviz.graphs:
class Graph(graphviz.dot.GraphSyntax, BaseGraph)
| Graph(name: Optional[str] = None,
comment: Optional[str] = None,
filename=None,
directory=None,
format: Optional[str] = None,
engine: Optional[str] = None,
encoding: Optional[str] = 'utf-8',
graph_attr=None,
node_attr=None,
edge_attr=None,
body=None,
strict: bool = False, *,
renderer: Optional[str] = None,
formatter: Optional[str] = None) -> None
|
| Graph source code in the DOT language.
|
| Args:
| name: Graph name used in the source code.
| comment: Comment added to the first line of the source.
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).
| directory: (Sub)directory for source saving and rendering.
| format: Rendering output format (``'pdf'``, ``'png'``, ...).
| engine: Layout command used (``'dot'``, ``'neato'``, ...).
| renderer: Output renderer used (``'cairo'``, ``'gd'``, ...).
| formatter: Output formatter used (``'cairo'``, ``'gd'``, ...).
| encoding: Encoding for saving the source.
| graph_attr: Mapping of ``(attribute, value)`` pairs for the graph.
| node_attr: Mapping of ``(attribute, value)`` pairs set for all nodes.
| edge_attr: Mapping of ``(attribute, value)`` pairs set for all edges.
| body: Iterable of verbatim lines (including their final newline)
| to add to the graph ``body``.
| strict (bool): Rendering should merge multi-edges.
|
| Note:
| All parameters are `optional` and can be changed under their
| corresponding attribute name after instance creation.
|
| Method resolution order:
| Graph
| graphviz.dot.GraphSyntax
| BaseGraph
| graphviz.dot.Dot
| graphviz.quoting.Quote
| graphviz.rendering.Render
| graphviz.saving.Save
| graphviz.jupyter_integration.JupyterIntegration
| graphviz.piping.Pipe
| graphviz.unflattening.Unflatten
| graphviz.encoding.Encoding
| graphviz.base.Base
| graphviz.base.LineIterable
| graphviz.backend.mixins.Render
| graphviz.backend.mixins.Pipe
| graphviz.parameters.mixins.Parameters
| graphviz.parameters.engines.Engine
| graphviz.parameters.formats.Format
| graphviz.parameters.renderers.Renderer
| graphviz.parameters.formatters.Formatter
| graphviz.parameters.base.ParameterBase
| graphviz.copying.CopyBase
| graphviz.backend.mixins.View
| graphviz.backend.mixins.Unflatten
| builtins.object
|
| Readonly properties defined here:
|
| directed
| ``False``
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.dot.GraphSyntax:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from BaseGraph:
|
| __init__(self,
name: Optional[str] = None,
comment: Optional[str] = None,
filename=None,
directory=None,
format: Optional[str] = None,
engine: Optional[str] = None,
encoding: Optional[str] = 'utf-8',
graph_attr=None,
node_attr=None,
edge_attr=None,
body=None,
strict: bool = False, *,
renderer: Optional[str] = None,
formatter: Optional[str] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseGraph:
|
| source
| The generated DOT source code as string.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.dot.Dot:
|
| __iter__(self, subgraph: bool = False) -> Iterator[str]
| Yield the DOT source code line by line (as graph or subgraph).
|
| Yields: Line ending with a newline (``'\n'``).
|
| attr(self, kw: Optional[str] = None, _attributes=None, **attrs) -> None
| Add a general or graph/node/edge attribute statement.
|
| Args:
| kw: Attributes target
| (``None`` or ``'graph'``, ``'node'``, ``'edge'``).
| attrs: Attributes to be set (must be strings, may be empty).
|
| See the :ref:`usage examples in the User Guide <attributes>`.
|
| clear(self, keep_attrs: bool = False) -> None
| Reset content to an empty body, clear graph/node/egde_attr mappings.
|
| Args:
| keep_attrs (bool): preserve graph/node/egde_attr mappings
|
| edge(self,
tail_name: str,
head_name: str,
label: Optional[str] = None,
_attributes=None, **attrs) -> None
| Create an edge between two nodes.
|
| Args:
| tail_name: Start node identifier
| (format: ``node[:port[:compass]]``).
| head_name: End node identifier
| (format: ``node[:port[:compass]]``).
| label: Caption to be displayed near the edge.
| attrs: Any additional edge attributes (must be strings).
|
| Note:
| The ``tail_name`` and ``head_name`` strings are separated
| by (optional) colon(s) into ``node`` name, ``port`` name,
| and ``compass`` (e.g. ``sw``).
| See :ref:`details in the User Guide <node-ports-compass>`.
|
| Attention:
| When rendering ``label``, backslash-escapes
| and strings of the form ``<...>`` have a special meaning.
| See the sections :ref:`backslash-escapes` and
| :ref:`quoting-and-html-like-labels` in the user guide for details.
|
| edges(self, tail_head_iter) -> None
| Create a bunch of edges.
|
| Args:
| tail_head_iter: Iterable of ``(tail_name, head_name)`` pairs
| (format:``node[:port[:compass]]``).
|
|
| Note:
| The ``tail_name`` and ``head_name`` strings are separated
| by (optional) colon(s) into ``node`` name, ``port`` name,
| and ``compass`` (e.g. ``sw``).
| See :ref:`details in the User Guide <node-ports-compass>`.
|
| node(self,
name: str,
label: Optional[str] = None,
_attributes=None, **attrs) -> None
| Create a node.
|
| Args:
| name: Unique identifier for the node inside the source.
| label: Caption to be displayed (defaults to the node ``name``).
| attrs: Any additional node attributes (must be strings).
|
| Attention:
| When rendering ``label``, backslash-escapes
| and strings of the form ``<...>`` have a special meaning.
| See the sections :ref:`backslash-escapes` and
| :ref:`quoting-and-html-like-labels` in the user guide for details.
|
| subgraph(self,
graph=None,
name: Optional[str] = None,
comment: Optional[str] = None,
graph_attr=None,
node_attr=None,
edge_attr=None,
body=None)
| Add the current content of the given sole ``graph`` argument
| as subgraph or return a context manager
| returning a new graph instance
| created with the given (``name``, ``comment``, etc.) arguments
| whose content is added as subgraph
| when leaving the context manager's ``with``-block.
|
| Args:
| graph: An instance of the same kind
| (:class:`.Graph`, :class:`.Digraph`) as the current graph
| (sole argument in non-with-block use).
| name: Subgraph name (``with``-block use).
| comment: Subgraph comment (``with``-block use).
| graph_attr: Subgraph-level attribute-value mapping
| (``with``-block use).
| node_attr: Node-level attribute-value mapping
| (``with``-block use).
| edge_attr: Edge-level attribute-value mapping
| (``with``-block use).
| body: Verbatim lines to add to the subgraph ``body``
| (``with``-block use).
|
| See the :ref:`usage examples in the User Guide <subgraphs-clusters>`.
|
| When used as a context manager, the returned new graph instance
| uses ``strict=None`` and the parent graph's values
| for ``directory``, ``format``, ``engine``, and ``encoding`` by default.
|
| Note:
| If the ``name`` of the subgraph begins with
| ``'cluster'`` (all lowercase)
| the layout engine will treat it as a special cluster subgraph.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.rendering.Render:
|
| render(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
view: bool = False,
cleanup: bool = False,
format: Optional[str] = None,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
neato_no_op: Union[bool, int, NoneType] = None,
quiet: bool = False,
quiet_view: bool = False, *,
outfile: Union[os.PathLike, str, NoneType] = None,
engine: Optional[str] = None,
raise_if_result_exists: bool = False,
overwrite_source: bool = False) -> str
| Save the source to file and render with the Graphviz engine.
|
| Args:
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).s
| directory: (Sub)directory for source saving and rendering.
| view (bool): Open the rendered result
| with the default application.
| cleanup (bool): Delete the source file
| after successful rendering.
| format: The output format used for rendering
| (``'pdf'``, ``'png'``, etc.).
| renderer: The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
| formatter: The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
| neato_no_op: Neato layout engine no-op flag.
| quiet (bool): Suppress ``stderr`` output
| from the layout subprocess.
| quiet_view (bool): Suppress ``stderr`` output
| from the viewer process
| (implies ``view=True``, ineffective on Windows platform).
| outfile: Path for the rendered output file.
| engine: Layout engine for rendering
| (``'dot'``, ``'neato'``, ...).
| raise_if_result_exists: Raise :exc:`graphviz.FileExistsError`
| if the result file exists.
| overwrite_source: Allow ``dot`` to write to the file it reads from.
| Incompatible with ``raise_if_result_exists``.
|
| Returns:
| The (possibly relative) path of the rendered file.
|
| Raises:
| ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter``
| are unknown.
| graphviz.RequiredArgumentError: If ``formatter`` is given
| but ``renderer`` is None.
| ValueError: If ``outfile`` is the same file as the source file
| unless ``overwite_source=True``.
| graphviz.ExecutableNotFound: If the Graphviz ``dot`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the rendering ``dot`` subprocess is non-zero.
| RuntimeError: If viewer opening is requested but not supported.
|
| Example:
| >>> doctest_mark_exe()
| >>> import graphviz
| >>> dot = graphviz.Graph(name='spam', directory='doctest-output')
| >>> dot.render(format='png').replace('\', '/')
| 'doctest-output/spam.gv.png'
| >>> dot.render(outfile='spam.svg').replace('\', '/')
| 'doctest-output/spam.svg'
|
| Note:
| The layout command is started from the directory of ``filepath``,
| so that references to external files
| (e.g. ``[image=images/camelot.png]``)
| can be given as paths relative to the DOT source file.
|
| view(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
cleanup: bool = False,
quiet: bool = False,
quiet_view: bool = False) -> str
| Save the source to file, open the rendered result in a viewer.
|
| Convenience short-cut for running ``.render(view=True)``.
|
| Args:
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).
| directory: (Sub)directory for source saving and rendering.
| cleanup (bool): Delete the source file after successful rendering.
| quiet (bool): Suppress ``stderr`` output from the layout subprocess.
| quiet_view (bool): Suppress ``stderr`` output
| from the viewer process (ineffective on Windows).
|
| Returns:
| The (possibly relative) path of the rendered file.
|
| Raises:
| graphviz.ExecutableNotFound: If the Graphviz executable
| is not found.
| graphviz.CalledProcessError: If the exit status is non-zero.
| RuntimeError: If opening the viewer is not supported.
|
| Short-cut method for calling :meth:`.render` with ``view=True``.
|
| Note:
| There is no option to wait for the application to close,
| and no way to retrieve the application's exit status.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.saving.Save:
|
| save(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None, *,
skip_existing: Optional[bool] = False) -> str
| Save the DOT source to file. Ensure the file ends with a newline.
|
| Args:
| filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
| directory: (Sub)directory for source saving and rendering.
| skip_existing: Skip write if file exists (default: ``False``).
|
| Returns:
| The (possibly relative) path of the saved source file.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from graphviz.saving.Save:
|
| filepath
| The target path for saving the DOT source file.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from graphviz.saving.Save:
|
| directory = ''
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.piping.Pipe:
|
| pipe(self,
format: Optional[str] = None,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
neato_no_op: Union[bool, int, NoneType] = None,
quiet: bool = False, *,
engine: Optional[str] = None,
encoding: Optional[str] = None) -> Union[bytes, str]
| Return the source piped through the Graphviz layout command.
|
| Args:
| format: The output format used for rendering
| (``'pdf'``, ``'png'``, etc.).
| renderer: The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
| formatter: The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
| neato_no_op: Neato layout engine no-op flag.
| quiet (bool): Suppress ``stderr`` output
| from the layout subprocess.
| engine: Layout engine for rendering
| (``'dot'``, ``'neato'``, ...).
| encoding: Encoding for decoding the stdout.
|
| Returns:
| Bytes or if encoding is given decoded string
| (stdout of the layout command).
|
| Raises:
| ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter``
| are unknown.
| graphviz.RequiredArgumentError: If ``formatter`` is given
| but ``renderer`` is None.
| graphviz.ExecutableNotFound: If the Graphviz ``dot`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the rendering ``dot`` subprocess is non-zero.
|
| Example:
| >>> doctest_mark_exe()
| >>> import graphviz
| >>> source = 'graph { spam }'
| >>> graphviz.Source(source, format='svg').pipe()[:14]
| b'<?xml version='
| >>> graphviz.Source(source, format='svg').pipe(encoding='ascii')[:14]
| '<?xml version='
| >>> graphviz.Source(source, format='svg').pipe(encoding='utf-8')[:14]
| '<?xml version='
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.unflattening.Unflatten:
|
| unflatten(self,
stagger: Optional[int] = None,
fanout: bool = False,
chain: Optional[int] = None) -> 'graphviz.Source'
| Return a new :class:`.Source` instance with the source
| piped through the Graphviz *unflatten* preprocessor.
|
| Args:
| stagger: Stagger the minimum length
| of leaf edges between 1 and this small integer.
| fanout: Fanout nodes with indegree = outdegree = 1
| when staggering (requires ``stagger``).
| chain: Form disconnected nodes into chains
| of up to this many nodes.
|
| Returns:
| Prepocessed DOT source code (improved layout aspect ratio).
|
| Raises:
| graphviz.RequiredArgumentError: If ``fanout`` is given
| but ``stagger`` is None.
| graphviz.ExecutableNotFound: If the Graphviz ``unflatten`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the unflattening 'unflatten' subprocess is non-zero.
|
| See also:
| Upstream documentation:
| https://www.graphviz.org/pdf/unflatten.1.pdf
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.encoding.Encoding:
|
| encoding
| The encoding for the saved source file.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.base.Base:
|
| __str__(self) -> str
| The DOT source code as string.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.engines.Engine:
|
| engine
| The layout engine used for rendering
| (``'dot'``, ``'neato'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.formats.Format:
|
| format
| The output format used for rendering
| (``'pdf'``, ``'png'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.renderers.Renderer:
|
| renderer
| The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.formatters.Formatter:
|
| formatter
| The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.copying.CopyBase:
|
| copy(self)
| Return a copied instance of the object.
|
| Returns:
| An independent copy of the current object.
Digraph¶
Partially symntax-highlighed: https://github.com/xflr6/graphviz/blob/master/docs/api.rst#digraph-1
>>> import graphviz
>>> help(graphviz.Digraph)
Help on class Digraph in module graphviz.graphs:
class Digraph(graphviz.dot.DigraphSyntax, BaseGraph)
| Digraph(name: Optional[str] = None,
comment: Optional[str] = None,
filename=None,
directory=None,
format: Optional[str] = None,
engine: Optional[str] = None,
encoding: Optional[str] = 'utf-8',
graph_attr=None,
node_attr=None,
edge_attr=None,
body=None,
strict: bool = False, *,
renderer: Optional[str] = None,
formatter: Optional[str] = None) -> None
|
| Directed graph source code in the DOT language.
|
| Args:
| name: Graph name used in the source code.
| comment: Comment added to the first line of the source.
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).
| directory: (Sub)directory for source saving and rendering.
| format: Rendering output format (``'pdf'``, ``'png'``, ...).
| engine: Layout command used (``'dot'``, ``'neato'``, ...).
| renderer: Output renderer used (``'cairo'``, ``'gd'``, ...).
| formatter: Output formatter used (``'cairo'``, ``'gd'``, ...).
| encoding: Encoding for saving the source.
| graph_attr: Mapping of ``(attribute, value)`` pairs for the graph.
| node_attr: Mapping of ``(attribute, value)`` pairs set for all nodes.
| edge_attr: Mapping of ``(attribute, value)`` pairs set for all edges.
| body: Iterable of verbatim lines (including their final newline)
| to add to the graph ``body``.
| strict (bool): Rendering should merge multi-edges.
|
| Note:
| All parameters are `optional` and can be changed under their
| corresponding attribute name after instance creation.
|
| Method resolution order:
| Digraph
| graphviz.dot.DigraphSyntax
| BaseGraph
| graphviz.dot.Dot
| graphviz.quoting.Quote
| graphviz.rendering.Render
| graphviz.saving.Save
| graphviz.jupyter_integration.JupyterIntegration
| graphviz.piping.Pipe
| graphviz.unflattening.Unflatten
| graphviz.encoding.Encoding
| graphviz.base.Base
| graphviz.base.LineIterable
| graphviz.backend.mixins.Render
| graphviz.backend.mixins.Pipe
| graphviz.parameters.mixins.Parameters
| graphviz.parameters.engines.Engine
| graphviz.parameters.formats.Format
| graphviz.parameters.renderers.Renderer
| graphviz.parameters.formatters.Formatter
| graphviz.parameters.base.ParameterBase
| graphviz.copying.CopyBase
| graphviz.backend.mixins.View
| graphviz.backend.mixins.Unflatten
| builtins.object
|
| Readonly properties defined here:
|
| directed
| ``True``
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.dot.DigraphSyntax:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Methods inherited from BaseGraph:
|
| __init__(self,
name: Optional[str] = None,
comment: Optional[str] = None,
filename=None,
directory=None,
format: Optional[str] = None,
engine: Optional[str] = None,
encoding: Optional[str] = 'utf-8',
graph_attr=None,
node_attr=None,
edge_attr=None,
body=None,
strict: bool = False, *,
renderer: Optional[str] = None,
formatter: Optional[str] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from BaseGraph:
|
| source
| The generated DOT source code as string.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.dot.Dot:
|
| __iter__(self, subgraph: bool = False) -> Iterator[str]
| Yield the DOT source code line by line (as graph or subgraph).
|
| Yields: Line ending with a newline (``'\n'``).
|
| attr(self, kw: Optional[str] = None, _attributes=None, **attrs) -> None
| Add a general or graph/node/edge attribute statement.
|
| Args:
| kw: Attributes target
| (``None`` or ``'graph'``, ``'node'``, ``'edge'``).
| attrs: Attributes to be set (must be strings, may be empty).
|
| See the :ref:`usage examples in the User Guide <attributes>`.
|
| clear(self, keep_attrs: bool = False) -> None
| Reset content to an empty body, clear graph/node/egde_attr mappings.
|
| Args:
| keep_attrs (bool): preserve graph/node/egde_attr mappings
|
| edge(self,
tail_name: str,
head_name: str,
label: Optional[str] = None,
_attributes=None, **attrs) -> None
| Create an edge between two nodes.
|
| Args:
| tail_name: Start node identifier
| (format: ``node[:port[:compass]]``).
| head_name: End node identifier
| (format: ``node[:port[:compass]]``).
| label: Caption to be displayed near the edge.
| attrs: Any additional edge attributes (must be strings).
|
| Note:
| The ``tail_name`` and ``head_name`` strings are separated
| by (optional) colon(s) into ``node`` name, ``port`` name,
| and ``compass`` (e.g. ``sw``).
| See :ref:`details in the User Guide <node-ports-compass>`.
|
| Attention:
| When rendering ``label``, backslash-escapes
| and strings of the form ``<...>`` have a special meaning.
| See the sections :ref:`backslash-escapes` and
| :ref:`quoting-and-html-like-labels` in the user guide for details.
|
| edges(self, tail_head_iter) -> None
| Create a bunch of edges.
|
| Args:
| tail_head_iter: Iterable of ``(tail_name, head_name)`` pairs
| (format:``node[:port[:compass]]``).
|
|
| Note:
| The ``tail_name`` and ``head_name`` strings are separated
| by (optional) colon(s) into ``node`` name, ``port`` name,
| and ``compass`` (e.g. ``sw``).
| See :ref:`details in the User Guide <node-ports-compass>`.
|
| node(self,
name: str,
label: Optional[str] = None,
_attributes=None, **attrs) -> None
| Create a node.
|
| Args:
| name: Unique identifier for the node inside the source.
| label: Caption to be displayed (defaults to the node ``name``).
| attrs: Any additional node attributes (must be strings).
|
| Attention:
| When rendering ``label``, backslash-escapes
| and strings of the form ``<...>`` have a special meaning.
| See the sections :ref:`backslash-escapes` and
| :ref:`quoting-and-html-like-labels` in the user guide for details.
|
| subgraph(self,
graph=None,
name: Optional[str] = None,
comment: Optional[str] = None,
graph_attr=None,
node_attr=None,
edge_attr=None,
body=None)
| Add the current content of the given sole ``graph`` argument
| as subgraph or return a context manager
| returning a new graph instance
| created with the given (``name``, ``comment``, etc.) arguments
| whose content is added as subgraph
| when leaving the context manager's ``with``-block.
|
| Args:
| graph: An instance of the same kind
| (:class:`.Graph`, :class:`.Digraph`) as the current graph
| (sole argument in non-with-block use).
| name: Subgraph name (``with``-block use).
| comment: Subgraph comment (``with``-block use).
| graph_attr: Subgraph-level attribute-value mapping
| (``with``-block use).
| node_attr: Node-level attribute-value mapping
| (``with``-block use).
| edge_attr: Edge-level attribute-value mapping
| (``with``-block use).
| body: Verbatim lines to add to the subgraph ``body``
| (``with``-block use).
|
| See the :ref:`usage examples in the User Guide <subgraphs-clusters>`.
|
| When used as a context manager, the returned new graph instance
| uses ``strict=None`` and the parent graph's values
| for ``directory``, ``format``, ``engine``, and ``encoding`` by default.
|
| Note:
| If the ``name`` of the subgraph begins with
| ``'cluster'`` (all lowercase)
| the layout engine will treat it as a special cluster subgraph.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.rendering.Render:
|
| render(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
view: bool = False,
cleanup: bool = False,
format: Optional[str] = None,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
neato_no_op: Union[bool, int, NoneType] = None,
quiet: bool = False,
quiet_view: bool = False, *,
outfile: Union[os.PathLike, str, NoneType] = None,
engine: Optional[str] = None,
raise_if_result_exists: bool = False,
overwrite_source: bool = False) -> str
| Save the source to file and render with the Graphviz engine.
|
| Args:
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).s
| directory: (Sub)directory for source saving and rendering.
| view (bool): Open the rendered result
| with the default application.
| cleanup (bool): Delete the source file
| after successful rendering.
| format: The output format used for rendering
| (``'pdf'``, ``'png'``, etc.).
| renderer: The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
| formatter: The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
| neato_no_op: Neato layout engine no-op flag.
| quiet (bool): Suppress ``stderr`` output
| from the layout subprocess.
| quiet_view (bool): Suppress ``stderr`` output
| from the viewer process
| (implies ``view=True``, ineffective on Windows platform).
| outfile: Path for the rendered output file.
| engine: Layout engine for rendering
| (``'dot'``, ``'neato'``, ...).
| raise_if_result_exists: Raise :exc:`graphviz.FileExistsError`
| if the result file exists.
| overwrite_source: Allow ``dot`` to write to the file it reads from.
| Incompatible with ``raise_if_result_exists``.
|
| Returns:
| The (possibly relative) path of the rendered file.
|
| Raises:
| ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter``
| are unknown.
| graphviz.RequiredArgumentError: If ``formatter`` is given
| but ``renderer`` is None.
| ValueError: If ``outfile`` is the same file as the source file
| unless ``overwite_source=True``.
| graphviz.ExecutableNotFound: If the Graphviz ``dot`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the rendering ``dot`` subprocess is non-zero.
| RuntimeError: If viewer opening is requested but not supported.
|
| Example:
| >>> doctest_mark_exe()
| >>> import graphviz
| >>> dot = graphviz.Graph(name='spam', directory='doctest-output')
| >>> dot.render(format='png').replace('\', '/')
| 'doctest-output/spam.gv.png'
| >>> dot.render(outfile='spam.svg').replace('\', '/')
| 'doctest-output/spam.svg'
|
| Note:
| The layout command is started from the directory of ``filepath``,
| so that references to external files
| (e.g. ``[image=images/camelot.png]``)
| can be given as paths relative to the DOT source file.
|
| view(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
cleanup: bool = False,
quiet: bool = False,
quiet_view: bool = False) -> str
| Save the source to file, open the rendered result in a viewer.
|
| Convenience short-cut for running ``.render(view=True)``.
|
| Args:
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).
| directory: (Sub)directory for source saving and rendering.
| cleanup (bool): Delete the source file after successful rendering.
| quiet (bool): Suppress ``stderr`` output from the layout subprocess.
| quiet_view (bool): Suppress ``stderr`` output
| from the viewer process (ineffective on Windows).
|
| Returns:
| The (possibly relative) path of the rendered file.
|
| Raises:
| graphviz.ExecutableNotFound: If the Graphviz executable
| is not found.
| graphviz.CalledProcessError: If the exit status is non-zero.
| RuntimeError: If opening the viewer is not supported.
|
| Short-cut method for calling :meth:`.render` with ``view=True``.
|
| Note:
| There is no option to wait for the application to close,
| and no way to retrieve the application's exit status.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.saving.Save:
|
| save(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None, *,
skip_existing: Optional[bool] = False) -> str
| Save the DOT source to file. Ensure the file ends with a newline.
|
| Args:
| filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
| directory: (Sub)directory for source saving and rendering.
| skip_existing: Skip write if file exists (default: ``False``).
|
| Returns:
| The (possibly relative) path of the saved source file.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from graphviz.saving.Save:
|
| filepath
| The target path for saving the DOT source file.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from graphviz.saving.Save:
|
| directory = ''
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.piping.Pipe:
|
| pipe(self,
format: Optional[str] = None,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
neato_no_op: Union[bool, int, NoneType] = None,
quiet: bool = False, *,
engine: Optional[str] = None,
encoding: Optional[str] = None) -> Union[bytes, str]
| Return the source piped through the Graphviz layout command.
|
| Args:
| format: The output format used for rendering
| (``'pdf'``, ``'png'``, etc.).
| renderer: The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
| formatter: The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
| neato_no_op: Neato layout engine no-op flag.
| quiet (bool): Suppress ``stderr`` output
| from the layout subprocess.
| engine: Layout engine for rendering
| (``'dot'``, ``'neato'``, ...).
| encoding: Encoding for decoding the stdout.
|
| Returns:
| Bytes or if encoding is given decoded string
| (stdout of the layout command).
|
| Raises:
| ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter``
| are unknown.
| graphviz.RequiredArgumentError: If ``formatter`` is given
| but ``renderer`` is None.
| graphviz.ExecutableNotFound: If the Graphviz ``dot`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the rendering ``dot`` subprocess is non-zero.
|
| Example:
| >>> doctest_mark_exe()
| >>> import graphviz
| >>> source = 'graph { spam }'
| >>> graphviz.Source(source, format='svg').pipe()[:14]
| b'<?xml version='
| >>> graphviz.Source(source, format='svg').pipe(encoding='ascii')[:14]
| '<?xml version='
| >>> graphviz.Source(source, format='svg').pipe(encoding='utf-8')[:14]
| '<?xml version='
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.unflattening.Unflatten:
|
| unflatten(self,
stagger: Optional[int] = None,
fanout: bool = False,
chain: Optional[int] = None) -> 'graphviz.Source'
| Return a new :class:`.Source` instance with the source
| piped through the Graphviz *unflatten* preprocessor.
|
| Args:
| stagger: Stagger the minimum length
| of leaf edges between 1 and this small integer.
| fanout: Fanout nodes with indegree = outdegree = 1
| when staggering (requires ``stagger``).
| chain: Form disconnected nodes into chains
| of up to this many nodes.
|
| Returns:
| Prepocessed DOT source code (improved layout aspect ratio).
|
| Raises:
| graphviz.RequiredArgumentError: If ``fanout`` is given
| but ``stagger`` is None.
| graphviz.ExecutableNotFound: If the Graphviz ``unflatten`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the unflattening 'unflatten' subprocess is non-zero.
|
| See also:
| Upstream documentation:
| https://www.graphviz.org/pdf/unflatten.1.pdf
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.encoding.Encoding:
|
| encoding
| The encoding for the saved source file.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.base.Base:
|
| __str__(self) -> str
| The DOT source code as string.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.engines.Engine:
|
| engine
| The layout engine used for rendering
| (``'dot'``, ``'neato'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.formats.Format:
|
| format
| The output format used for rendering
| (``'pdf'``, ``'png'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.renderers.Renderer:
|
| renderer
| The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.formatters.Formatter:
|
| formatter
| The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.copying.CopyBase:
|
| copy(self)
| Return a copied instance of the object.
|
| Returns:
| An independent copy of the current object.
Source¶
Partially syntax-highlighted: https://github.com/xflr6/graphviz/blob/master/docs/api.rst#source-1
>>> import graphviz
>>> help(graphviz.Source)
Help on class Source in module graphviz.sources:
class Source(graphviz.rendering.Render,
graphviz.saving.Save,
graphviz.jupyter_integration.JupyterIntegration,
graphviz.piping.Pipe,
graphviz.unflattening.Unflatten)
| Source(source: str,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
format: Optional[str] = None,
engine: Optional[str] = None,
encoding: Optional[str] = 'utf-8', *,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
loaded_from_path: Optional[os.PathLike] = None) -> None
|
| Verbatim DOT source code string to be rendered by Graphviz.
|
| Args:
| source: The verbatim DOT source code string.
| filename: Filename for saving the source (defaults to ``'Source.gv'``).
| directory: (Sub)directory for source saving and rendering.
| format: Rendering output format (``'pdf'``, ``'png'``, ...).
| engine: Layout engine used (``'dot'``, ``'neato'``, ...).
| encoding: Encoding for saving the source.
|
| Note:
| All parameters except ``source`` are optional. All of them
| can be changed under their corresponding attribute name
| after instance creation.
|
| Method resolution order:
| Source
| graphviz.rendering.Render
| graphviz.saving.Save
| graphviz.jupyter_integration.JupyterIntegration
| graphviz.piping.Pipe
| graphviz.unflattening.Unflatten
| graphviz.encoding.Encoding
| graphviz.base.Base
| graphviz.base.LineIterable
| graphviz.backend.mixins.Render
| graphviz.backend.mixins.Pipe
| graphviz.parameters.mixins.Parameters
| graphviz.parameters.engines.Engine
| graphviz.parameters.formats.Format
| graphviz.parameters.renderers.Renderer
| graphviz.parameters.formatters.Formatter
| graphviz.parameters.base.ParameterBase
| graphviz.copying.CopyBase
| graphviz.backend.mixins.View
| graphviz.backend.mixins.Unflatten
| builtins.object
|
| Methods defined here:
|
| __init__(self,
source: str,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
format: Optional[str] = None,
engine: Optional[str] = None,
encoding: Optional[str] = 'utf-8', *,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
loaded_from_path: Optional[os.PathLike] = None) -> None
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self) -> Iterator[str]
| Yield the DOT source code read from file line by line.
|
| Yields: Line ending with a newline (``'\n'``).
|
| save(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None, *,
skip_existing: Optional[bool] = None) -> str
| Save the DOT source to file. Ensure the file ends with a newline.
|
| Args:
| filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
| directory: (Sub)directory for source saving and rendering.
| skip_existing: Skip write if file exists (default: ``None``).
| By default skips if instance was loaded from the target path:
| ``.from_file(self.filepath)``.
|
| Returns:
| The (possibly relative) path of the saved source file.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_file(filename: Union[os.PathLike, str],
directory: Union[os.PathLike, str, NoneType] = None,
format: Optional[str] = None,
engine: Optional[str] = None,
encoding: Optional[str] = 'utf-8',
renderer: Optional[str] = None,
formatter: Optional[str] = None) -> 'Source' from builtins.type
| Return an instance with the source string read from the given file.
|
| Args:
| filename: Filename for loading/saving the source.
| directory: (Sub)directory for source loading/saving and rendering.
| format: Rendering output format (``'pdf'``, ``'png'``, ...).
| engine: Layout command used (``'dot'``, ``'neato'``, ...).
| encoding: Encoding for loading/saving the source.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| source
| The DOT source code as string.
|
| Normalizes so that the string always ends in a final newline.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {'_loaded_from_path': typing.Optional[os.PathLike], ...
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.rendering.Render:
|
| render(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
view: bool = False,
cleanup: bool = False,
format: Optional[str] = None,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
neato_no_op: Union[bool, int, NoneType] = None,
quiet: bool = False,
quiet_view: bool = False, *,
outfile: Union[os.PathLike, str, NoneType] = None,
engine: Optional[str] = None,
raise_if_result_exists: bool = False,
overwrite_source: bool = False) -> str
| Save the source to file and render with the Graphviz engine.
|
| Args:
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).s
| directory: (Sub)directory for source saving and rendering.
| view (bool): Open the rendered result
| with the default application.
| cleanup (bool): Delete the source file
| after successful rendering.
| format: The output format used for rendering
| (``'pdf'``, ``'png'``, etc.).
| renderer: The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
| formatter: The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
| neato_no_op: Neato layout engine no-op flag.
| quiet (bool): Suppress ``stderr`` output
| from the layout subprocess.
| quiet_view (bool): Suppress ``stderr`` output
| from the viewer process
| (implies ``view=True``, ineffective on Windows platform).
| outfile: Path for the rendered output file.
| engine: Layout engine for rendering
| (``'dot'``, ``'neato'``, ...).
| raise_if_result_exists: Raise :exc:`graphviz.FileExistsError`
| if the result file exists.
| overwrite_source: Allow ``dot`` to write to the file it reads from.
| Incompatible with ``raise_if_result_exists``.
|
| Returns:
| The (possibly relative) path of the rendered file.
|
| Raises:
| ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter``
| are unknown.
| graphviz.RequiredArgumentError: If ``formatter`` is given
| but ``renderer`` is None.
| ValueError: If ``outfile`` is the same file as the source file
| unless ``overwite_source=True``.
| graphviz.ExecutableNotFound: If the Graphviz ``dot`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the rendering ``dot`` subprocess is non-zero.
| RuntimeError: If viewer opening is requested but not supported.
|
| Example:
| >>> doctest_mark_exe()
| >>> import graphviz
| >>> dot = graphviz.Graph(name='spam', directory='doctest-output')
| >>> dot.render(format='png').replace('\', '/')
| 'doctest-output/spam.gv.png'
| >>> dot.render(outfile='spam.svg').replace('\', '/')
| 'doctest-output/spam.svg'
|
| Note:
| The layout command is started from the directory of ``filepath``,
| so that references to external files
| (e.g. ``[image=images/camelot.png]``)
| can be given as paths relative to the DOT source file.
|
| view(self,
filename: Union[os.PathLike, str, NoneType] = None,
directory: Union[os.PathLike, str, NoneType] = None,
cleanup: bool = False,
quiet: bool = False,
quiet_view: bool = False) -> str
| Save the source to file, open the rendered result in a viewer.
|
| Convenience short-cut for running ``.render(view=True)``.
|
| Args:
| filename: Filename for saving the source
| (defaults to ``name`` + ``'.gv'``).
| directory: (Sub)directory for source saving and rendering.
| cleanup (bool): Delete the source file after successful rendering.
| quiet (bool): Suppress ``stderr`` output from the layout subprocess.
| quiet_view (bool): Suppress ``stderr`` output
| from the viewer process (ineffective on Windows).
|
| Returns:
| The (possibly relative) path of the rendered file.
|
| Raises:
| graphviz.ExecutableNotFound: If the Graphviz executable
| is not found.
| graphviz.CalledProcessError: If the exit status is non-zero.
| RuntimeError: If opening the viewer is not supported.
|
| Short-cut method for calling :meth:`.render` with ``view=True``.
|
| Note:
| There is no option to wait for the application to close,
| and no way to retrieve the application's exit status.
|
| ----------------------------------------------------------------------
| Readonly properties inherited from graphviz.saving.Save:
|
| filepath
| The target path for saving the DOT source file.
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from graphviz.saving.Save:
|
| directory = ''
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.piping.Pipe:
|
| pipe(self,
format: Optional[str] = None,
renderer: Optional[str] = None,
formatter: Optional[str] = None,
neato_no_op: Union[bool, int, NoneType] = None,
quiet: bool = False, *,
engine: Optional[str] = None,
encoding: Optional[str] = None) -> Union[bytes, str]
| Return the source piped through the Graphviz layout command.
|
| Args:
| format: The output format used for rendering
| (``'pdf'``, ``'png'``, etc.).
| renderer: The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
| formatter: The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
| neato_no_op: Neato layout engine no-op flag.
| quiet (bool): Suppress ``stderr`` output
| from the layout subprocess.
| engine: Layout engine for rendering
| (``'dot'``, ``'neato'``, ...).
| encoding: Encoding for decoding the stdout.
|
| Returns:
| Bytes or if encoding is given decoded string
| (stdout of the layout command).
|
| Raises:
| ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter``
| are unknown.
| graphviz.RequiredArgumentError: If ``formatter`` is given
| but ``renderer`` is None.
| graphviz.ExecutableNotFound: If the Graphviz ``dot`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the rendering ``dot`` subprocess is non-zero.
|
| Example:
| >>> doctest_mark_exe()
| >>> import graphviz
| >>> source = 'graph { spam }'
| >>> graphviz.Source(source, format='svg').pipe()[:14]
| b'<?xml version='
| >>> graphviz.Source(source, format='svg').pipe(encoding='ascii')[:14]
| '<?xml version='
| >>> graphviz.Source(source, format='svg').pipe(encoding='utf-8')[:14]
| '<?xml version='
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.unflattening.Unflatten:
|
| unflatten(self,
stagger: Optional[int] = None,
fanout: bool = False,
chain: Optional[int] = None) -> 'graphviz.Source'
| Return a new :class:`.Source` instance with the source
| piped through the Graphviz *unflatten* preprocessor.
|
| Args:
| stagger: Stagger the minimum length
| of leaf edges between 1 and this small integer.
| fanout: Fanout nodes with indegree = outdegree = 1
| when staggering (requires ``stagger``).
| chain: Form disconnected nodes into chains
| of up to this many nodes.
|
| Returns:
| Prepocessed DOT source code (improved layout aspect ratio).
|
| Raises:
| graphviz.RequiredArgumentError: If ``fanout`` is given
| but ``stagger`` is None.
| graphviz.ExecutableNotFound: If the Graphviz ``unflatten`` executable
| is not found.
| graphviz.CalledProcessError: If the returncode (exit status)
| of the unflattening 'unflatten' subprocess is non-zero.
|
| See also:
| Upstream documentation:
| https://www.graphviz.org/pdf/unflatten.1.pdf
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.encoding.Encoding:
|
| encoding
| The encoding for the saved source file.
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.base.Base:
|
| __str__(self) -> str
| The DOT source code as string.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.base.LineIterable:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.engines.Engine:
|
| engine
| The layout engine used for rendering
| (``'dot'``, ``'neato'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.formats.Format:
|
| format
| The output format used for rendering
| (``'pdf'``, ``'png'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.renderers.Renderer:
|
| renderer
| The output renderer used for rendering
| (``'cairo'``, ``'gd'``, ...).
|
| ----------------------------------------------------------------------
| Data descriptors inherited from graphviz.parameters.formatters.Formatter:
|
| formatter
| The output formatter used for rendering
| (``'cairo'``, ``'gd'``, ...).
|
| ----------------------------------------------------------------------
| Methods inherited from graphviz.copying.CopyBase:
|
| copy(self)
| Return a copied instance of the object.
|
| Returns:
| An independent copy of the current object.