File: default_arguments.rst

package info (click to toggle)
python-sh 2.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 900 kB
  • sloc: python: 4,157; makefile: 25
file content (38 lines) | stat: -rw-r--r-- 894 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
.. _default_arguments:

Default Arguments
=================

Many times, you want to override the default arguments of all commands launched
through sh.  For example, suppose you want the output of all commands to be
aggregated into a :class:`io.StringIO` buffer.  The naive way would be this:

.. code-block:: python

    import sh
    from io import StringIO

    buf = StringIO()

    sh.ls("/", _out=buf)
    sh.whoami(_out=buf)
    sh.ps("auxwf", _out=buf)

Clearly, this gets tedious quickly.  Fortunately, we can create execution
contexts that allow us to set default arguments on all commands spawned from
that context:

.. code-block:: python

    import sh
    from io import StringIO

    buf = StringIO()
    sh2 = sh.bake(_out=buf)

    sh2.ls("/")
    sh2.whoami()
    sh2.ps("auxwf")

Now, anything launched from ``sh2`` will send its output to the ``StringIO``
instance ``buf``.