Movatterモバイル変換


[0]ホーム

URL:


Navigation

2. Using the Python Interpreter

2.1. Invoking the Interpreter

The Python interpreter is usually installed as/usr/local/bin/python3.3on those machines where it is available; putting/usr/local/bin in yourUnix shell’s search path makes it possible to start it by typing the command:

python3.3

to the shell.[1] Since the choice of the directory where the interpreter livesis an installation option, other places are possible; check with your localPython guru or system administrator. (E.g.,/usr/local/python is apopular alternative location.)

On Windows machines, the Python installation is usually placed inC:\Python33, though you can change this when you’re running theinstaller. To add this directory to your path, you can type the followingcommand into the command prompt in a DOS box:

setpath=%path%;C:\python33

Typing an end-of-file character (Control-D on Unix,Control-Z onWindows) at the primary prompt causes the interpreter to exit with a zero exitstatus. If that doesn’t work, you can exit the interpreter by typing thefollowing command:quit().

The interpreter’s line-editing features usually aren’t very sophisticated. OnUnix, whoever installed the interpreter may have enabled support for the GNUreadline library, which adds more elaborate interactive editing and historyfeatures. Perhaps the quickest check to see whether command line editing issupported is typing Control-P to the first Python prompt you get. If it beeps,you have command line editing; see AppendixInteractive Input Editing and History Substitution for anintroduction to the keys. If nothing appears to happen, or if^P is echoed,command line editing isn’t available; you’ll only be able to use backspace toremove characters from the current line.

The interpreter operates somewhat like the Unix shell: when called with standardinput 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 readsand executes ascript from that file.

A second way of starting the interpreter ispython-ccommand[arg]...,which executes the statement(s) incommand, analogous to the shell’s-c option. Since Python statements often contain spaces or othercharacters that are special to the shell, it is usually advised to quotecommand in its entirety with single quotes.

Some Python modules are also useful as scripts. These can be invoked usingpython-mmodule[arg]..., which executes the source file formodule asif you had spelled out its full name on the command line.

When a script file is used, it is sometimes useful to be able to run the scriptand enter interactive mode afterwards. This can be done by passing-ibefore the script.

2.1.1. Argument Passing

When known to the interpreter, the script name and additional argumentsthereafter are turned into a list of strings and assigned to theargvvariable in thesys module. You can access this list by executingimportsys. The length of the list is at least one; when no script and no argumentsare 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-ccommand is used,sys.argv[0] is set to'-c'. When-mmodule is used,sys.argv[0] is set to the full name of thelocated module. Options found after-ccommand or-mmodule are not consumed by the Python interpreter’s option processing butleft insys.argv for the command or module to handle.

2.1.2. Interactive Mode

When commands are read from a tty, the interpreter is said to be ininteractivemode. In this mode it prompts for the next command with theprimary prompt,usually three greater-than signs (>>>); for continuation lines it promptswith thesecondary prompt, by default three dots (...). The interpreterprints a welcome message stating its version number and a copyright noticebefore printing the first prompt:

$ python3.3Python 3.3 (default, Sep 24 2012, 09:25:04)[GCC 4.6.3] on linux2Type "help", "copyright", "credits" or "license" for more information.>>>

Continuation lines are needed when entering a multi-line construct. As anexample, take a look at thisif statement:

>>>the_world_is_flat=1>>>ifthe_world_is_flat:...print("Be careful not to fall off!")...Be careful not to fall off!

2.2. The Interpreter and Its Environment

2.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 froma file, it exits with a nonzero exit status after printing the stack trace.(Exceptions handled by anexcept clause in atry statementare not errors in this context.) Some errors are unconditionally fatal andcause an exit with a nonzero exit; this applies to internal inconsistencies andsome cases of running out of memory. All error messages are written to thestandard error stream; normal output from executed commands is written tostandard output.

Typing the interrupt character (usually Control-C or DEL) to the primary orsecondary prompt cancels the input and returns to the primary prompt.[2]Typing an interrupt while a command is executing raises theKeyboardInterrupt exception, which may be handled by atrystatement.

2.2.2. Executable Python Scripts

On BSD’ish Unix systems, Python scripts can be made directly executable, likeshell scripts, by putting the line

#! /usr/bin/env python3.3

(assuming that the interpreter is on the user’sPATH) at the beginningof the script and giving the file an executable mode. The#! must be thefirst two characters of the file. On some platforms, this first line must endwith a Unix-style line ending ('\n'), not a Windows ('\r\n') lineending. Note that the hash, or pound, character,'#', is used to start acomment in Python.

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

$ chmod +x myscript.py

On Windows systems, there is no notion of an “executable mode”. The Pythoninstaller automatically associates.py files withpython.exe so thata double-click on a Python file will run it as a script. The extension canalso be.pyw, in that case, the console window that normally appears issuppressed.

2.2.3. Source Code Encoding

By default, Python source files are treated as encoded in UTF-8. In thatencoding, characters of most languages in the world can be used simultaneouslyin string literals, identifiers and comments — although the standard libraryonly uses ASCII characters for identifiers, a convention that any portable codeshould follow. To display all these characters properly, your editor mustrecognize that the file is UTF-8, and it must use a font that supports all thecharacters in the file.

It is also possible to specify a different encoding for source files. In orderto do this, put one more special comment line right after the#! line todefine the source file encoding:

# -*- coding: encoding -*-

With that declaration, everything in the source file will be treated as havingthe encodingencoding instead of UTF-8. The list of possible encodings can befound in the Python Library Reference, in the section oncodecs.

For example, if your editor of choice does not support UTF-8 encoded files andinsists on using some other encoding, say Windows-1252, you can write:

# -*- coding: cp-1252 -*-

and still use all characters in the Windows-1252 character set in the sourcefiles. The special encoding comment must be in thefirst or second linewithin the file.

2.2.4. The Interactive Startup File

When you use Python interactively, it is frequently handy to have some standardcommands executed every time the interpreter is started. You can do this bysetting an environment variable namedPYTHONSTARTUP to the name of afile containing your start-up commands. This is similar to the.profilefeature of the Unix shells.

This file is only read in interactive sessions, not when Python reads commandsfrom a script, and not when/dev/tty is given as the explicit source ofcommands (which otherwise behaves like an interactive session). It is executedin the same namespace where interactive commands are executed, so that objectsthat it defines or imports can be used without qualification in the interactivesession. You can also change the promptssys.ps1 andsys.ps2 in thisfile.

If you want to read an additional start-up file from the current directory, youcan program this in the global start-up file using code likeifos.path.isfile('.pythonrc.py'):exec(open('.pythonrc.py').read()).If you want to use the startup file in a script, you must do this explicitlyin the script:

importosfilename=os.environ.get('PYTHONSTARTUP')iffilenameandos.path.isfile(filename):exec(open(filename).read())

2.2.5. The Customization Modules

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

>>>importsite>>>site.getusersitepackages()'/home/user/.local/lib/python3.2/site-packages'

Now you can create a file namedusercustomize.py in that directory andput anything you want in it. It will affect every invocation of Python, unlessit is started with the-s option to disable the automatic import.

sitecustomize works in the same way, but is typically created by anadministrator of the computer in the global site-packages directory, and isimported beforeusercustomize. See the documentation of thesitemodule for more details.

Footnotes

[1]On Unix, the Python 3.x interpreter is by default not installed with theexecutable namedpython, so that it does not conflict with asimultaneously installed Python 2.x executable.
[2]A problem with the GNU Readline package may prevent this.

Table Of Contents

Previous topic

1. Whetting Your Appetite

Next topic

3. An Informal Introduction to Python

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp