Common ipython functions, ipython installation is easier than Shell

Source: Internet
Author: User
Tags python list
Overview
Ipython is a python Interactive Shell, which is much better and more powerful than the default Python shell.
She supports syntax highlighting, Automatic completion, Code Debugging, object introspection, support for bash shell commands, many built-in
It is very easy to use.
Application
Install ipython in Windows
Install ipython in windows in the following steps:
1. Download ipython-0.8.4.win32-setup.exe and pyreadline-1.5-win32-setup.exe.
(1) download ipython-0.8.4.win32: http://ipython.scipy.org/dist/ipython-0.8.4.win32-setup.exe
Exquisite address: http://bit.ly/YqbkJ
Download pyreadline-1.5-win32: http://ipython.scipy.org/dist/pyreadline-1.5-win32-setup.exe
Exquisite address: http://bit.ly/2JFKDM installation pyreadline. Double-click to install

 

Install in Ubuntu

Sudo apt-Get install 'ipython'

In the interaction environment and in the default Python interaction environment, write code for debugging and testing. But compared with the default
The Python environment is as follows.
1. Magic. Ipython has some "magic" keywords:
% Exit, % pprint, % quit, % alias, % autocall, % autoindent, % automagic,
% Bookmark, % Cd, % color_info, % colors, % config, % dhist, % dirs, % Ed,
% Edit, % ENV, % Hist, % logoff, % logon, % logstart, % logstate, % lsmagic,
% Macro, % magic, % P, % PAGE, % PDB, % PDEF, % pdoc, % pfile, % pinfo, % popd,
% Profile, % prun, % psource, % pushd, % PWD, % R, % rehash, % rehashx, % reset,
% Run, % runlog, % save, % SC, % Sx, % system_verbose, % unalias, % Who,
% Who_ls, % whos, % xmode
Ipython checks whether the command passed to it contains the magic keyword. If the command is a magic keyword,
Ipython will handle it by yourself. If it is not the Magic keyword, submit it to python for processing. If
Automagic is enabled (default). You do not need to add the % sign before the magic keyword. Conversely, if automagic
Yes, % is required. Enter the command magic at the command prompt to display all the magic keys.
Word list and their brief usage instructions. Good documentation for any part of a software
Is important, from the online ipython User Manual to the embedded document (% magic), ipython will certainly not be in this
Surface is missing. The following describes some commonly used magic functions, such:
% BG Function
Put the function in the background for execution, for example, % BG myfunc (x, y, z = 1). Then you can use jobs to complete the function.
If the result is retrieved, myvar = jobs. Result (5) or myvar = jobs [5]. result. In addition, jobs. Status ()
You can view the status of an existing task.
% Ed or % Edit
Edit a file and run it. If you only want to edit but not execute it, use ed-x filename.
% Env
Show Environment Variables
% Hist or % history
Show history
% Macro name n1-n2 n3-n4... N5... N6...
Create a macro named name and execute name is to execute n1-n2 n3-n4... N5... N6... this
Some code.
% Pwd
Show Current Directory
% Pycat filename
Highlight a python file with syntax (. py suffix is not required)
% Save filename n1-n2 n3-n4... N5 .... N6...
Saves excessive code execution as a file
% Time statement
Calculate the execution time of a piece of code
% Timeit statement
It is too convenient to automatically calculate the execution time of a piece of code based on the number of repetitions and loops.

2. ipython! Run the shell command to convert the python variable to the shell variable with $. Pass
These two symbols can be used to interact with shell commands, making it very convenient to do a lot of complex
Work. For example, you can easily create a group of directories:
For I in range (10 ):
S = "dir % s" % I
! Mkdir $ s
However, there are still some restrictions in writing. $ can only be followed by the variable name, and cannot directly write complex expressions,
$ "Dir % s" % I is the incorrect method. Therefore, you must generate a python variable before using it. For example:
For I in! Ls:
Print I

This statement is also incorrect. You can:
A =! Ls
For I in:
Print I
Another note is that if $ exists in a common shell command, two $ is required. Ratio
For example, the original echo $ path must be written now! Echo $ path.

3. Automatically complete the tab. An extremely powerful function of ipython is the automatic completion of tabs. Standard Python Interactive Solution
the Releaser can also be automatically supplemented by tab:
~ $ Python
Python 2.5.1 (r5.1: 54863, Mar 7 2008, 04:10:12)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
type "help", "Copyright", "Credits" or "License" for more information.
Import rlcompleter, Readline
Readline. parse_and_bind ('tab: complete ')
H
hasattr hash help hex
both standard Python interactive interpreter and ipython support "normal" Automatic completion and menu completion.
to use auto-completion, enter a matching model and press the tab key. For "normal" auto-completion
mode (default), press the tab key and then:
the matching model is expanded by the maximum match.
all matching results are listed.
example:
in [1]: Import OS
in [2]: OS. po
OS. popen OS. popen2 OS. popen3 OS. popen4
in [2]: OS. popen
input OS. po and press the tab key, OS. the po is expanded to OS. popen (as shown at the in [2]: prompt)
and displays all modules, classes, and functions starting with Po in the OS, they are popen, popen2, popen3, and popen4.
menu completion is slightly different. Disable default tab completion and use menu completion. You need to modify the configuration file
$ home/. ipython/ipythonrc.
comment out:
readline_parse_and_bind tab: complete

Uncomment:
Readline_parse_and_bind tab: menu-complete
Unlike the auto-completion display of "normal", the menus of all matching lists of the current command are supplemented with each
The secondary Tab key is used to display items in the matching list cyclically. For example:
In [1]: Import OS
In [2]: OS. Po
The result is:
In [3]: OS. popen
Each time you press the tab key, other items in the matching list will be displayed cyclically: popen2, popen3, popen4,
Finally, return to the PO. In the menu completion mode, the shortcut key for viewing all matching lists is Ctrl + L.

5. History. When a large number of commands and statements are input interactively in ipython shell, the following is the case:
In [1]: A = 1
In [2]: B = 2
In [3]: c = 3
In [4]: D = {}
In [5]: E = []
In [6]: for I in range (20 ):
...: E. append (I)
...: D [I] = B
...:
You can enter the command "Hist" to quickly view input history records:
In [7]: hist
1: A = 1
2: B = 2
3: c = 3
4: D = {}
5: E = []
6:
For I in range (20 ):
E. append (I)
D [I] = B
7: _ IP. Magic ("hist ")
To remove the sequence numbers in the History (from 1 to 7), run the "hist-n" command ":
In [8]: hist-n
A = 1
B = 2
C = 3
D = {}
E = []
For I in range (20 ):
E. append (I)
D [I] = B
_ IP. Magic ("hist ")
_ IP. Magic ("hist-n ")
In this way, the code can be easily copied to a text editor. To search for history records, you can first enter
Enter a matching model and press Ctrl + P. After a match is found, continue to press Ctrl + P to search backward.
Press Ctrl + n to search for the nearest match.
6. Edit. If you want to experiment with an idea at a python prompt, you should often modify it in the editor. Source code (Even
). Enter edit in ipython to call the Corresponding Editor according to the environment variable $ editor.
. If $ editor is empty, VI (UNIX) or notepad (Windows) is called ). Back to ipython
Prompt to exit the editor. If you save and exit the editor, enter the editor code in
The current namespace is automatically executed. If you do not want this, you can use Edit + X. If you want to edit the last time
The last edited code is edit + P. In the previous feature, we mentioned that using hist −n can easily
Copy the code to the editor. A simpler method is to add the slice syntax of the edit and Python list.
Assume that the hist output is as follows:
In [29]: hist
1: A = 1
2: B = 2
3: c = 3
4: D = {}
5: E = []

6:
For I in range (20 ):
E. append (I)
D [I] = B
7: % hist
To export 4th, 5, and 6 sentences of code to the editor, just enter:
Edit 4: 7
7. debugger interface. Another feature of ipython is its interface with Python debugger. In ipython Shell
Enter the magic keyword PDB to enable automatic debugging when an exception occurs. In PDB
When the automatic call is enabled, when Python encounters an unhandled exception, the python debugger will
Dynamic startup. The current row in the debugger is the row where an exception occurs. The author of ipython said that sometimes when
When debugging is required in a line of code, he will put an expression 1/0 at the start of debugging. Enable PDB,
Run the code in ipython. When the interpreter processes the row 1/0,
Zerodivisionerror is abnormal, and then it is taken from the specified code to a debugging session.
8. Run. Sometimes in an interactive shell, it is useful to run the content in a source file.
Run the magic keyword run with a source file name to run a file in the ipython interpreter (for example
For example, run <Source File> <parameters required to run the source File> ). The following parameters are used:
-N when the source file code is blocked from running, the variable {{__ name __}} is set to "{{__ main __}}}". This will
Prevent if {__name __}}== "{{__ main __}}}": code in the block from being executed.
-I: the source file runs in the namespace of the current ipython instance instead of in a new namespace. If
You need the source code to use the variables defined in the interactive session, which will be very useful.
-P uses the python profiler module to run and analyze the source code. The code that uses this option does not run.
In the current namespace.
9. Macro. A macro allows you to define a name for a piece of code so that you can use this name to run this section later.
Code. As mentioned in the magic keyword edit, the list slicing method also applies to macro definition. Assume that
History records are as follows:
In [3]: hist
1: L = []
2:
For I in L:
Print I
You can define a macro as follows:
In [4]: Macro print_l 2

Macro 'print _ L' created. to execute, type its name (without quotes ).
Macro contents:
For I in L:
Print I
Run macro:
In [5]: print_l
------> Print_l ()
Here, list l is empty, so nothing is output. However, this is actually a very powerful function
List l some actual values, and run the macro again to see different results:
In [7]: L = range (5)
In [8]: print_l
------> Print_l ()
0
1
2
3
4
When running a macro, it is as if you re-enter the code contained in the macro print_l. It can also be used
The new variable L. Because Python syntax does not have a macro structure (maybe never ),
It is a useful feature in shell.
10. Environment (profiles ). As mentioned earlier, ipython has installed multiple configuration files for different loops.
Environment. The Configuration File naming rule is ipythonrc -. To start ipython with a specific configuration, You need:
Ipython-P
You can create an ipython configuration file in the $ home/. ipython directory,
The name is ipythonrc-. Here is the name of the environment you want. If you have several projects at the same time
Some projects use different special libraries. At this time, each project has its own environment, which is very useful.
You can also create a configuration file for each project.
Modules Used.
11. Use the shell of the operating system. Using the default ipython configuration file, there are several Unix shell commands (of course,
Is On Unix systems), Cd, PWD, and LS can all work as in bash. Run other shell commands
Before the command, add it! Or !!. Use the magic keyword % SC and % SX to capture the output of shell commands.
The pysh environment can be used to replace shell. Ipython started with the-P pysh parameter can accept and execute
You can also use all Python modules, Python keywords, and
Built-in function.

For example, if you want to create 500 directories and the naming rules are from d_0_d to d_499_d, you can use
-P pysh starts ipython, and then it is like this:
[~ /TTT] | 1> for I in range (500 ):
|.> Mkdir D _ $ {I} _ d
|.>
This will create 500 directories:
[~ /TTT] | 2> ls-d * | WC-l
500

Note that the range Function of Python and the mkdir command of UNIX are mixed here. Although ipython-P pysh
A powerful shell alternative, but it lacks proper job control. When running a very time-consuming task
Press Ctrl + Z to stop ipython session instead of the child process.
Finally, exit ipython. You can enter Ctrl + d (you will be asked to confirm), or enter exit or quit (note
Case Sensitive) exit without confirmation.
Summary
After introducing the features and basic usage of ipython, I have fully realized the powerful functions of ipython.
Yes! So, let's use it as a favorable tool to help us develop it! For further configuration and more
Interested readers can find more information on the following network.
Ipython: http://ipython.scipy.org
Ipython English document: http://ipython.scipy.org/moin/Documentation
Exquisite address: http://bit.ly/GdPZU
Some magic letters in ipython: http://guyingbo.javaeye.com/blog/111142
Exquisite address: http://bit.ly/3GVxE8

 

Ipython is very powerful and has many features, but I cannot remember it. The frequently used features are recorded as follows:

A Automatic completion

Install the pyreadline module separately,

Http://launchpad.net/pyreadline/1.6/1.6.1/+download/pyreadline-1.6.1.win32.exe

After installation, enter the ipython interactive command line and execute the following code before it is available. The same is true for standard Python command lines:

>>> Import Readline, rlcompleter

>>> Readline. parse_and_bind ('tab complete ')

B is convenient?

? Moudle can view the description of the module, which is better than dir.

C history

Hist allows you to view the history of input commands.

Hist-n remove the number of rows before history

Press Ctrl + P to quickly enter the command entered last time. If you press the previous command to enter a match, the command will match the previous command, and then enter

D. Quick Edit

The statements found by hist can be quickly inserted into the default text editor using edit [X: Y], which is very convenient.

E. execute system commands.

! Command can execute the system command and return the following example:

! Whoami

The variable in Python must be prefixed with $ before it can be used in shell commands.

F magic keyword

Enter magic to see the detailed description. ipython defines some common commands. When executing the user input, it will first determine whether it is a magic keyword. If yes, it will be processed directly. Edit is a magic keyword.

G running source code

Run pyname. py [-Arg]

*-N when the source file code is blocked, the variable _ name _ is set to "_ main __". This prevents
If _ name _ = "_ main __":
the code in the block is executed
*-The I source file runs in the namespace of the current ipython instance instead of in a new namespace. If you need the source code to use the variables defined in the interactive session, it will be very useful.
*-P uses the python profiler module to run and analyze the source code. The code using this option will not run in the current namespace.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.