Tom Hale
Tom Hale

Reputation: 46983

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'

Upvotes: 10

Views: 1204

Answers (2)

wjandrea
wjandrea

Reputation: 33127

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

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

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

* 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.

Upvotes: 1

ntg
ntg

Reputation: 14145

TL;DR: You cannot as things stand. This might or might not be an error in the implementation of %cd.

Until this is fixed, one way to avoid this is to use:

import os
os.chdir("dir") #some comment here

A second alternative is using bash commands. However % is a magic command, not equivalent to a bash command. This is on purpose, as it can change the current directory of the notebook.

This is not the same as e.g.

!cd dir #some comment here

Which will spawn a shell and execute the command there thus not changing the current directory. (You can verify using pwd before/after each command)

Note that if your goal is not to change the current jupyter notebook directory, you can issue multiple commands in one cell with the magic %sh:

%%sh 
cd dir #some comment here
ls #some more commands here
....

This command will spawn a shell and all bash commands will be executed there, so the current jupyter directory will not change.

Upvotes: -1

Related Questions