Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a comment after a IPython magic command

How can I put a comment at the end of an IPython magic command?

Eg, trying to use %cd:

%cd "dir"  # comment

I want to change to directory dir but instead I get:

[Errno 2] No such file or directory: 'dir # comment'
like image 530
Tom Hale Avatar asked May 04 '26 07:05

Tom Hale


1 Answers

It's not possible in general because IPython magic commands parse their own command lines.*

There are some magic commands where comments seem to work, but actually they're being handled in another way. For example:

  • %ls # comment works properly, but %ls is an alias to a shell command, so the shell is what's parsing the comment.
  • %automagic 0 # comment behaves like %automagic, toggling the setting instead of exclusively disabling it like %automagic 0 would do. It's as if the 0 # comment is all one string, which it ignores.
  • %run $filename # comment treats the comment as arguments, so ['#', 'comment'] ends up in sys.argv for $filename.

Workaround

You could call magic commands using exclusively Python syntax.

First get the running IPython instance with get_ipython():

ipython = get_ipython()

Then:

ipython.run_line_magic('cd', 'dir')  # comment
  • Docs: InteractiveShell.run_line_magic()

Or for cell magics, you could go from this (which doesn't work):

%%script bash  # comment
echo hello

to this:

ipython.run_cell_magic('script', 'bash', 'echo hello')  # comment
  • Docs: InteractiveShell.run_cell_magic()

Another option, I suppose, is to run an entire cell, although, suppressing the output since it returns an ExecutionResult object:

ipython.run_cell('%cd dir');  # comment
  • Docs: InteractiveShell.run_cell()

* I'm not sure if this is documented explicitly, but it is documented implicitly under defining custom magics, and I found the clues in this GitHub issue: Allow comments after arguments in magic_arguments.

like image 88
wjandrea Avatar answered May 07 '26 15:05

wjandrea



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!