官术网_书友最值得收藏!

Python interactive shell

Now that we've got a command-line window, we'll go straight into the Python interactive shell. We do that by typing python into the command-line window.

If you have multiple versions of Python installed and we want to interact with a specified version, we can explicitly choose the version from the command line by typing in that version's name. For example, if we type python3, we'll explicitly start up some version of Python 3.X:

The python3 command is used for Linux users. Windows users should type python command line to work.

Now, the fun really starts!

When we see the >>> prompt, we can type in any Python expression or statement and see the result immediately (as shown in the following screenshot of code example):

This is incredibly useful because it means that we don't have to remember every detail about how functions work, what class members are called, which exceptions are raised under what circumstances, and so on. Whenever we're unsure about something, we can just open up an interactive shell and find out. So, let's discuss this using a simple example.

Let's imagine we're working on an application that uses Python's set data type and we're unsure about what exception gets raised. When we try to add a set to itself, we could go digging through the documentation, but it's quicker and easier to just create a set in the interactive shell and try adding it to itself:

Right away, the system tells us that adding a set to itself raises a TypeError exception. Sometimes, running a quick experiment in the interactive shell is the fastest way to get information we want, but documentation is nice too.

Fortunately, Python has a very good documentation system that we can access straight from the interactive shell by calling the help function. We could pass any object as the parameter of the help function and it will print out that object's documentation for us. So, if we want to find out about functools.wraps, we just pass it to help using the following two commands and read all about it (refer to the following screenshot):

import functools 
help(functools.wraps) 

The help function can also take the name of the object you want to read about instead of the object itself using the following code:

help('collections.defaultdict')   

This format can save us the time of typing in an import statement in the interactive shell:

The difference is that the help parameter is a string and not an expression that evaluates to the object we're interested in.

主站蜘蛛池模板: 临沧市| 琼海市| 澄迈县| 安化县| 拉孜县| 通化县| 阳城县| 凤凰县| 革吉县| 甘泉县| 乌鲁木齐县| 庆云县| 冷水江市| 赤壁市| 正安县| 广南县| 罗山县| 静安区| 绍兴市| 车致| 安庆市| 潍坊市| 东宁县| 广西| 那曲县| 谷城县| 浦城县| 兴城市| 南和县| 安乡县| 南开区| 泌阳县| 江山市| 丹巴县| 凭祥市| 浑源县| 阿勒泰市| 连江县| 姚安县| 壶关县| 福清市|