Python Tutorial Learning (ii)--using the Python Interpreter

Source: Internet
Author: User
Tags stack trace

Using the Python interpreter

2.1. Invoking the Interpreter

The Python interpreter is usually installed as /usr/local/bin/python in those machines where it is available; Putting /usr/local/bin in your Unix Shell's search path makes it possible to start it by typing the command

Python

to the shell. Since the choice of the directory where the Interpreter lives is an installation option, and other places is possible; Check with your local Python guru or system administrator. (e.g., /usr/local/python is a popular alternative location.)

On Windows machines, the Python installation are usually placed in C:\Python27, though you can change this when yo U ' re running the installer. To add this directory to your path, you can type the following command into the command prompt in a DOS box:

Set path=%path%; C:\python27

Typing an end-of-file character (control-d on Unix, control-z on Windows" in the primary prompt causes the interpreter to exit with a zero exit status. If that doesn ' t work, you can exit the interpreter by typing the following command: quit () .

The interpreter ' s line-editing features usually aren ' t very sophisticated. On Unix, whoever installed the interpreter could have an enabled support for the GNU ReadLine Library, which adds more Elaborat e Interactive editing and history features. Perhaps the quickest check to see whether command line editing are supported are typing control-p to the first Python prompt You get. If It beeps, you are command line editing; See Appendix Interactive Input Editing and Substitution for a introduction to the keys. If nothing appears to happen, or if ^p was echoed, command line editing isn ' t available; You'll have only been able to use BACKSPACE to remove characters from the current line.

The interpreter operates somewhat like the Unix shell:when called with standard input connected to a TTY device, it reads and executes commands interactively; When called with a file name argument or with a file as standard input, it reads and executes a script from that File.

A second The starting the interpreter is python- C Command [arg] ..., whic H executes the statement (s) command, analogous to the shell's- c option. Since Python statements often contain spaces or other characters that's special to the shell, it's usually advised to Q The Uote command is entirety with a single quotes.

Some Python modules is also useful as scripts. These can be invoked using python- m module [arg] ..., which executes the SOU RCE file for module as if you had spelled out it full name on the command line.

When a script file was used, it was sometimes useful to being able to run the script and enter interactive mode afterwards. This can is done by passing -I before the script.

2.1.1. Argument passing

When known to the interpreter, the script name and additional arguments thereafter is turned into a list of strings and a Ssigned to theargvVariable in theSYSModule. You can access the this list by executingimport sys . The length of the list is at least one; When no script and no arguments is given,Sys.argv[0]is an empty string. When the script name is given as'-'(meaning standard input),Sys.argv[0]is set to'-'. When- C Commandis used,Sys.argv[0]is set to'-C '. When- M Moduleis used,Sys.argv[0]is set to the full name of the located module. Options found after- C CommandOr- M Moduleis not consumed by the Python interpreter ' s option processingSYS.ARGVFor the command or module to handle.

2.1.2. Interactive Mode

When commands was read from a TTY, the interpreter was said to being in Interactive mode. In this mode it prompts to the next command with the primary prompt, usually three Greater-than signs (>& Gt;>); For continuation lines it prompts and the secondary prompt, by default three dots (...). The Interpreter prints a welcome message stating its version number and a copyright notice before printing the first Promp T:

Pythonpython 2.7 (#1, Feb, 00:02:06) Type ' help ', ' copyright ', ' credits ' or ' license ' for more information.>> >

Continuation lines is needed when entering a multi-line construct. As an example, take a look at this if statement:

1the_world_is_flat:"being careful not to fall off!" ... Be careful not to fall off!    
2.2. The interpreter and its Environment2.2.1. Error Handling

When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; When input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by the except clause in a try statement is not errors in this context.) Some errors is unconditionally fatal and cause an exit with a nonzero exit; This applies to internal inconsistencies and some cases of running of memory. All error messages is written to the standard error stream; Normal output from executed commands are written to standard output.

Typing the interrupt character (usually control-c or DEL) to the primary or secondary prompt cancels the input and returns To the primary prompt. [1] Typing an interrupt while a command was executing raises the Keyboardinterrupt exception, which may be handled By a try statement.

2.2.2. Executable Python Scripts

On BSD ' ish Unix systems, Python scripts can is made directly executable, like shell scripts, by putting the line

#! /usr/bin/env python

(assuming that interpreter was on the user's PATH) at the beginning of the script and giving the file an E xecutable mode. The #! must be the first and the characters of the file. On some platforms, this first line must end with a unix-style line ending (' \ n '), not a Windows (' \ r \ n ') Line ending. Note that the hash, or pound, character, ' # ', was used to start a comment in Python.

The script can be given an executable mode, or permission, using the chmod command:

$ chmod +x myscript.py

On Windows systems, there are no notion of an "executable mode". The Python installer automatically associates . py files with Python.exe So, a double-click on a Pyth On file would run it as a script. The extension can also be . Pyw, in the, and the console window, the normally appears is suppressed.

2.2.3. Source Code Encoding

It is possible to use encodings different than ASCII in Python source files. The best-by-doing it is-put-one more special comment line-right after the #! line to define the source file E Ncoding:

#-*-Coding:encoding-*-

With this declaration, all characters in the source file would be treated as have the encoding encoding, and it would be possible to directly write Unicode string literals in the selected encoding. The list of possible encodings can be found in the Python Library Reference, in the sections on codecs.

For example, to write Unicode literals including the Euro currency symbol, the iso-8859-15 encoding can is used, with the Euro symbol has the ordinal value 164. This script, when saved in the Iso-8859-15 encoding, would print the value 8364 (the Unicode codepoint corresponding to the Euro symbol) and then exit:

#-*-coding:iso-8859-15-*-u "€"ord(currency)    

If your editor supports saving files as utf-8 with a UTF-8 byte order Mark ( aka BOM), you can use this instead of an encoding declaration. IDLE supports this capability if options/general/default source encoding/utf-8 is set. Notice that this signature are not understood in older Python releases (2.2 and earlier), and also isn't understood by the OP erating system for script files with #! lines (only used on Unix systems).

By using UTF-8 (either through the signature or a encoding declaration), characters of most languages in the world can be Used simultaneously in string literals and comments. Using non-ascii characters in identifiers are not supported. To display all these characters properly, your editor must recognize that the file was UTF-8, and it must use a font that s Upports all the characters in the file.

2.2.4. The Interactive Startup File

When you use Python interactively, it's frequently handy to has some standard commands executed every time the interpret ER is started. Setting an environment variable named Pythonstartup to the name of a file containing your Start-up commands. This was similar to the . profile feature of the Unix shells.

This "is" only "read in interactive sessions" when the Python reads commands from a script, and if /dev/tty is given as the explicit source of commands (which otherwise behaves like an interactive session). It is executed in the same namespace where interactive commands be executed, so this objects that it defines or imports C An is used without qualification in the interactive session. You can also a change of the prompts sys.ps1 and sys.ps2 in this file.

If you want to read a additional start-up file from the current directory, you can program this in the global start-up fi Le using code like if os.path.isfile ('. pythonrc.py '): execfile ('. pythonrc.py '). If you want to use the "startup file in a" script, you must does this explicitly in the script:

OSos.  Environ.  Get(' Pythonstartup ')os.  Path.  Isfile(filenameexecfile(filename)       
2.2.5. The Customization Modules

Python provides-hooks to let you customize it: sitecustomize and usercustomize. To see how it works, you need first-to-find the location of your user site-packages directory. Start Python and run this code:

Sitesite.  Getusersitepackages()'/home/user/.local/lib/python2.7/site-packages '    

Now the can create a file named usercustomize.py in that directory and put anything you want in it. It'll affect every invocation of Python, unless it's started with the- s option to disable the automatic imp Ort.

Sitecustomize works in the same-in-the-the-same-the-typically created by an administrator of the-computer in the global s Ite-packages directory, and is imported before usercustomize. See the documentation of the site module for more details.

Footnotes

[1] A problem with the GNU Readline package is prevent this.

Python Tutorial Learning (ii)--using the Python Interpreter

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.