3

In ipython there is a magic %less which enables the regular shell less command. So we can use

less fname

or

%less fname

to see the content of fname. Even wonderful thing is that we can also use

cat fname | less

or

%cat fname | less

but NOT(!!!) cat fname | %less or %cat fname | %less.

in ipython as well!

Sadly I find that for the non-magic python functions, the output seems not able to be used together with pipe to less. For example, none of the below works.

print(os.environ.keys()) | %less
print(os.environ.keys()) | less
echo os.environ.keys() | %less
echo os.environ.keys() | less
os.environ.keys() | %less
os.environ.keys() | less

Is there way to resolve this?


Sorry I didn't search SO carefully since 2 similar questions are already answered.

PLUS: I would appreciate if someone tells the strange behaviours for the % and non-% magic version with the existence of "|". I guess this is also answered, but it's hard for me to search with correct keywords.

Hongxu Chen
  • 5,240
  • 2
  • 45
  • 85

1 Answers1

10
In [21]: x = os.environ.keys()
In [22]: %page x

This was found by typing %magic and searching backward through the output for the string "page".


When a string like %less, %page, %cat, or %ls appears at the beginning of a command, it is treated as a magic function by IPython. Note that if you have automagic enabled, you do not need to type % explicitly for line magic; that is why less may behave the same as %less when typed at the beginning of a command.

When the magic function does not appear at the beginning of a command, the command is passed to Python and treated like regular Python code.

In Python | is the bitwise-or operator.

% calls the __mod__ special method.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677