Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPython line continuation of command shell string literal

Tags:

ipython

In iPython, when using the command shell command (the exclamation point operator), is there a way to do line continuation of long string literals?

E.g.

t = !echo "Hello"\
"World"
t

produces ['Hello'] as the value for t instead of the expected ['HelloWorld'].

like image 545
Michael Malak Avatar asked Jun 20 '26 19:06

Michael Malak


1 Answers

You can use a "cell magic" (which is basically a multi-line version of other magics like !). If you enter %%bash at the command prompt, it will give you a new line with ..., meaning that you should type your command. Press enter again, and you get another ..., until you just hit enter twice in a row, and it runs your commands. For example, you can type just the following.

%%bash --out t
echo "Hello "\
"World"

(and hit enter twice at the end). It works as expected. In particular, note the --out t, which stores the standard output in the variable t. If you evaluate that now, you get 'Hello World\n'. You can also get the standard error output with --err, as described nicely on this page.

In the ipython notebook, you just put the whole thing in one cell and evaluate it all together. (If you haven't tried the notebook, I highly recommend it.)

like image 154
Mike Avatar answered Jun 23 '26 06:06

Mike