I want to run a bash script in my ipython Notebook and save the output as a string in a python variable for further manipulation. Basically I want to pipe the output of the bash magic to a variable, For example the output of something like this:
%%bash some_command [options] foo bar
Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable.
Both ! and % allow you to run shell commands from a Jupyter notebook. % is provided by the IPython kernel and allows you to run "magic commands", many of which include well-known shell commands. ! , provided by Jupyter, allows shell commands to be run within cells.
%%writefile lets you output code developed in a Notebook to a Python module. The sys library connects a Python program to the system it is running on. The list sys. argv contains the command-line arguments that a program was run with.
2. Download Jupyter Notebook as PDF. The Jupyter Notebook has an option to export the notebook to many formats. It can be accessed by clicking File -> Download as -> PDF via LaTeX (or PDF via HTML - not visible in the screenshot).
What about using this:
myvar = !some_command --option1 --option2 foo bar
instead of the %%bash
magic? Using the !
symbol runs the following command as a shell command, and the results are all stored in myvar
. For running multiple commands and collecting the output of all of them, just put together a quick shell script.
For completeness, if you would still like to use the %%bash
cell magic, you can pass the --out
and --err
flags to redirect the outputs from the stdout and stderr to a variable of your choice.
From the doucumentation:
%%bash --out output --err error echo "hi, stdout" echo "hello, stderr" >&2
will store the outputs in the variables output
and error
so that:
print(error) print(output)
will print to the python console:
hello, stderr hi, stdout
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With