is there any way to use "less" view python output in ipython [duplicate]

  • Last Update :
  • Techknowledgy :
In[21]: x = os.environ.keys()
In[22]: % page x

Suggestion : 2

To see the options IPython accepts, use ipython --help (and you probably should run the output through a pager such as ipython --help | less for more convenient reading). This shows all the options that have a single-word alias to control them, but IPython lets you configure all of its objects from the command-line by passing the full class name and a corresponding value; type ipython --help-all to see this full list. For example:,IPython is smart enough to filter out input prompts, be they plain Python ones (>>> and ...) or IPython ones (In [N]: and ...:). You can therefore copy and paste from existing interactive sessions without worry.,This is probably useful to developers who manage multiple Python versions and don’t want to have correspondingly multiple IPython versions. Note that in this mode, there is no way to pass IPython any command-line options, as those are trapped first by Python itself.,You can also have multiple IPython instances in your program and open them separately, for example with different options for data presentation. If you close and open the same instance multiple times, its prompt counters simply continue from each execution to the next.

$ ipython[options] files
ipython--matplotlib qt
ipython--TerminalIPythonApp.matplotlib = 'qt'
In[8]: % cd /
   home / fperez
In[10]: % % timeit x = range(10000)
   ...: min(x)
   ...: max(x)
   ...:
   1000 loops, best of 3: 438 us per loop
In[9]: cd mydir /
   home / fperez / mydir

Suggestion : 3

This access to the shell from within the same terminal window as your Python session means that there is a lot less switching back and forth between interpreter and shell as you write your Python code.,There are several options to fine-tune how your code is run; you can see the documentation in the normal way, by typing %run? in the IPython interpreter.,Because finding help on an object is so common and useful, IPython introduces the ? character as a shorthand for accessing this documentation and other relevant information:,In this chapter, we’ve just scratched the surface of using IPython to enable data science tasks. Much more information is available both in print and on the Web, and here we’ll list some other resources that you may find helpful.

Once you do this, you should see a prompt like the following:

IPython 4.0 .1--An enhanced Interactive Python. ?
   - > Introduction and overview of IPython 's features. %
   quickref - > Quick reference.
help - > Python 's own help system.
object ? - > Details about 'object', use 'object??'
for extra details.
In[1]:

Though the IPython notebook is viewed and edited through your web browser window, it must connect to a running Python process in order to execute code. To start this process (known as a “kernel”), run the following command in your system shell:

$ jupyter notebook

This command will launch a local web server that will be visible to your browser. It immediately spits out a log showing what it is doing; that log will look something like this:

$ jupyter notebook
   [NotebookApp] Serving notebooks from local directory: /Users/jakevdp / ...[NotebookApp] 0 active kernels[NotebookApp] The IPython Notebook is running at: http: //localhost:8888/
   [NotebookApp] Use Control - C to stop this server and shut down all kernels...

The Python language and its data science ecosystem are built with the user in mind, and one big part of that is access to documentation. Every Python object contains the reference to a string, known as a docstring, which in most cases will contain a concise summary of the object and how to use it. Python has a built-in help() function that can access this information and print the results. For example, to see the documentation of the built-in len function, you can do the following:

In[1]: help(len)
Help on built - in
function len in module builtins:

   len(...)
len(object) - > integer

Return the number of items of a sequence or mapping.

Because finding help on an object is so common and useful, IPython introduces the ? character as a shorthand for accessing this documentation and other relevant information:

In [2]: len?
Type: builtin_function_or_method
String form: <built-in function len>
   Namespace: Python builtin
   Docstring:
   len(object) -> integer

   Return the number of items of a sequence or mapping.

This notation works for just about anything, including object methods:

In [3]: L = [1, 2, 3]
In [4]: L.insert?
Type: builtin_function_or_method
String form: <built-in method insert of list object at 0x1024b8ea8>
   Docstring: L.insert(index, object) -- insert object before index

Importantly, this will even work for functions or other objects you create yourself! Here we’ll define a small function with a docstring:

In[6]: def square(a):
   ....: ""
"Return the square of a."
""
....: return a ** 2
   ....:

Now we’ll use the ? mark to find this docstring:

In [7]: square?
Type: function
String form: <function square at 0x103713cb0>
   Definition: square(a)
   Docstring: Return the square of a.

Because the Python language is so easily readable, you can usually gain another level of insight by reading the source code of the object you’re curious about. IPython provides a shortcut to the source code with the double question mark (??):

In [8]: square??
Type: function
String form: <function square at 0x103713cb0>
   Definition: square(a)
   Source:
   def square(a):
   "Return the square of a"
   return a ** 2

If you play with this much, you’ll notice that sometimes the ?? suffix doesn’t display any source code: this is generally because the object in question is not implemented in Python, but in C or some other compiled extension language. If this is the case, the ?? suffix gives the same output as the ? suffix. You’ll find this particularly with many of Python’s built-in objects and types, for example len from above:

In [9]: len??
Type: builtin_function_or_method
String form: <built-in function len>
   Namespace: Python builtin
   Docstring:
   len(object) -> integer

   Return the number of items of a sequence or mapping.

Every Python object has various attributes and methods associated with it. Like with the help function discussed before, Python has a built-in dir function that returns a list of these, but the tab-completion interface is much easier to use in practice. To see a list of all available attributes of an object, you can type the name of the object followed by a period (.) character and the Tab key:

In [10]: L.<TAB>
   L.append L.copy L.extend L.insert L.remove L.sort
   L.clear L.count L.index L.pop L.reverse

To narrow down the list, you can type the first character or several characters of the name, and the Tab key will find the matching attributes and methods:

In [10]: L.c<TAB>
   L.clear L.copy L.count

   In [10]: L.co<TAB>
      L.copy L.count

If there is only a single option, pressing the Tab key will complete the line for you. For example, the following will instantly be replaced with L.count:

In [10]: L.cou<TAB>

Tab completion is also useful when importing objects from packages. Here we’ll use it to find all possible imports in the itertools package that start with co:

In [10]: from itertools import co<TAB>
   combinations compress
   combinations_with_replacement count

Similarly, you can use tab completion to see which imports are available on your system (this will change depending on which third-party scripts and modules are visible to your Python session):

In [10]: import <TAB>
   Display all 399 possibilities? (y or n)
   Crypto dis py_compile
   Cython distutils pyclbr
   ... ... ...
   difflib pwd zmq

   In [10]: import h<TAB>
      hashlib hmac http
      heapq html husl

Suggestion : 4

Because finding help on an object is so common and useful, IPython introduces the ? character as a shorthand for accessing this documentation and other relevant information:,Because the Python language is so easily readable, another level of insight can usually be gained by reading the source code of the object you're curious about. IPython provides a shortcut to the source code with the double question mark (??):,Using ? and/or ?? gives a powerful and quick interface for finding information about what any Python function or module does.,Tab completion is also useful when importing objects from packages. Here we'll use it to find all possible imports in the itertools package that start with co:

In[1]: help(len)
Help on built - in
function len in module builtins:

   len(...)
len(object) - > integer

Return the number of items of a sequence or mapping.
In [2]: len?
Type: builtin_function_or_method
String form: <built-in function len>
   Namespace: Python builtin
   Docstring:
   len(object) -> integer

   Return the number of items of a sequence or mapping.
In [3]: L = [1, 2, 3]
In [4]: L.insert?
Type: builtin_function_or_method
String form: <built-in method insert of list object at 0x1024b8ea8>
   Docstring: L.insert(index, object) -- insert object before index
In[5]: L ?
   Type : list
String form: [1, 2, 3]
Length: 3
Docstring:
   list() - > new empty list
list(iterable) - > new list initialized from iterable 's items
In[6]: def square(a):
   ....: ""
"Return the square of a."
""
....: return a ** 2
   ....:
In [7]: square?
Type: function
String form: <function square at 0x103713cb0>
   Definition: square(a)
   Docstring: Return the square of a.

Suggestion : 5

The functions testmod() and testfile() provide a simple interface to doctest that should be sufficient for most basic uses. For a less formal introduction to these two functions, see sections Simple Usage: Checking Examples in Docstrings and Simple Usage: Checking Examples in a Text File.,Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function:,This won’t display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout, and the final line of output is ***Test Failed*** N failures., where N is the number of examples that failed.,This function is used internally by other functions (see below), but can also be useful when you want to transform an interactive Python session into a Python script.

""
"
This is the "example"
module.

The example module supplies one
function, factorial().For example,

   >>>
   factorial(5)
120
   ""
"

def factorial(n):
   ""
"Return the factorial of n, an exact integer >= 0.

>>>
[factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120] >>>
factorial(30)
265252859812191058636308480000000
   >>>
   factorial(-1)
Traceback(most recent call last):
   ...
   ValueError: n must be >= 0

Factorials of floats are OK, but the float must be an exact integer:
   >>>
   factorial(30.1)
Traceback(most recent call last):
   ...
   ValueError: n must be exact integer >>>
   factorial(30.0)
265252859812191058636308480000000

It must also not be ridiculously large:
   >>>
   factorial(1e100)
Traceback(most recent call last):
   ...
   OverflowError: n too large ""
"

import math
if not n >= 0:
   raise ValueError("n must be >= 0")
if math.floor(n) != n:
   raise ValueError("n must be exact integer")
if n + 1 == n: #
catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
   result *= factor
factor += 1
return result

if __name__ == "__main__":
   import doctest
doctest.testmod()
$ python example.py
$
$ python example.py - v
Trying:
   factorial(5)
Expecting:
   120
ok
Trying: [factorial(n) for n in range(6)]
Expecting: [1, 1, 2, 6, 24, 120]
ok
Trying:
   factorial(1e100)
Expecting:
   Traceback(most recent call last):
   ...
   OverflowError: n too large
ok
2 items passed all tests:
   1 tests in __main__
8 tests in __main__.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$
if __name__ == "__main__":
   import doctest
doctest.testmod()
python M.py

Suggestion : 6

CSS, SCSS and Less , Formatting and Linting , Command Line Interface , Run and Debug

You define Jupyter-like code cells within Python code using a # %% comment:

# % %
   msg = "Hello World"
print(msg)

# % %
   msg = "Hello again"
print(msg)