2012 · 2012 well licensed - figures con- licensed this a the page chap- may licenses, of 477

512
Python unter Linux Wikibooks.org

Upload: others

Post on 18-Oct-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Pyth

onun

ter

Lin

ux

Wik

iboo

ks.o

rg

Page 2: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

26.J

uni2

012

On

the

28th

ofA

pril

2012

the

cont

ents

ofth

eE

nglis

has

wel

las

Ger

man

Wik

iboo

ksan

dW

ikip

edia

proj

ects

wer

elic

ense

dun

derC

reat

ive

Com

mon

sA

ttrib

utio

n-Sh

areA

like

3.0

Unp

or-

ted

licen

se.A

nU

RIt

oth

islic

ense

isgi

ven

inth

elis

toffi

gure

son

page

477.

Ifth

isdo

cum

enti

sa

deriv

edw

ork

from

the

con-

tent

sof

one

ofth

ese

proj

ects

and

the

cont

entw

asst

illlic

ense

dby

the

proj

ectu

nder

this

licen

seat

the

time

ofde

rivat

ion

this

docu

men

thas

tobe

licen

sed

unde

rth

esa

me,

asi

mila

ror

aco

mpa

tible

licen

se,a

sst

ated

inse

ctio

n4b

ofth

elic

ense

.The

listo

fcon

tribu

tors

isin

clud

edin

chap

terC

ontri

buto

rson

page

471.

The

licen

ses

GPL

,LG

PLan

dG

FDL

are

incl

uded

inch

ap-

terL

icen

seso

npa

ge48

3,si

nce

this

book

and/

orpa

rtsof

itm

ayor

may

notb

elic

ense

dun

der

one

orm

ore

ofth

ese

licen

ses,

and

thus

requ

ire

incl

usio

nof

thes

elic

ense

s.T

helic

ense

sof

the

figur

esar

egi

ven

inth

elis

toffi

gure

son

page

477.

Page 3: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Inha

ltsve

rzei

chni

s1

Vorw

ort

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.3

2E

rste

Schr

itte

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

72.

1H

allo

,Wel

t!.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

72.

2U

mla

ute

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.10

2.3

Ein

gabe

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.11

2.4

Wei

tere

Aus

gabe

n.

..

..

..

..

..

..

..

..

..

..

..

..

.13

2.5

Ele

men

tare

Dat

enty

pen

..

..

..

..

..

..

..

..

..

..

..

.16

2.6

Funk

tione

nun

dM

odul

e.

..

..

..

..

..

..

..

..

..

..

..

182.

7K

omm

enta

re.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

202.

8E

inrü

ckun

gen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.21

2.9

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.23

2.10

Anm

erku

ngen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

23

III

Page 4: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3D

aten

type

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

253.

1B

oole

an.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

263.

2Z

ahle

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.28

3.3

Stri

ngs

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

343.

4Z

eich

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.43

3.5

Lis

ten

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

443.

6Tu

pel

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.48

3.7

Sequ

enze

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.50

3.8

Set

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

543.

9D

ictio

nary

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.56

3.10

Bes

onde

rhei

ten

beim

Kop

iere

n.

..

..

..

..

..

..

..

..

..

603.

11K

onve

rtie

rung

..

..

..

..

..

..

..

..

..

..

..

..

..

..

633.

12Ty

pena

bfra

ge.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

643.

13K

onst

ante

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.65

3.14

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.66

3.15

Anm

erku

ngen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

674

Kon

trol

lstr

uktu

ren

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

694.

1if

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.70

4.2

if-e

lif-e

lse

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

744.

3if

--ga

nzku

rz.

..

..

..

..

..

..

..

..

..

..

..

..

..

.77

Page 5: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

4.4

Ver

glei

chso

pera

tore

nin

derÜ

bers

icht

..

..

..

..

..

..

..

..

794.

5fo

r-Sc

hlei

fe.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

824.

6w

hile

-Sch

leif

e.

..

..

..

..

..

..

..

..

..

..

..

..

..

.88

4.7

brea

kun

dco

ntin

ue.

..

..

..

..

..

..

..

..

..

..

..

..

..

914.

8Sc

hlei

fen-

Els

e.

..

..

..

..

..

..

..

..

..

..

..

..

..

.94

4.9

Try-

Exc

ept

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

974.

10Tr

y-Fi

nally

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.101

4.11

Ass

ert

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

103

4.12

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.10

54.

13A

nmer

kung

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

.10

55

Funk

tione

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

107

5.1

Funk

tione

n.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.10

75.

2Fu

nktio

nsdo

kum

enta

tion

..

..

..

..

..

..

..

..

..

..

..

113

5.3

Para

met

er.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.11

45.

4V

aria

ble

Para

met

er.

..

..

..

..

..

..

..

..

..

..

..

..

.11

75.

5G

loba

leun

dlo

kale

Var

iabl

en.

..

..

..

..

..

..

..

..

..

.11

95.

6Fu

nktio

nen

aufW

erte

men

gen

..

..

..

..

..

..

..

..

..

..

122

5.7

lam

bda

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

123

5.8

Lis

ten

erze

ugen

sich

selb

st.

..

..

..

..

..

..

..

..

..

..

.12

65.

9G

ener

ator

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

130

Page 6: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

5.10

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.13

45.

11A

nmer

kung

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

.13

56

Mod

ule

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.13

76.

1A

ufba

uei

nes

Mod

ules

..

..

..

..

..

..

..

..

..

..

..

..

137

6.2

Impo

rtie

ren

imD

etai

l.

..

..

..

..

..

..

..

..

..

..

..

.13

96.

3In

halt

von

Mod

ulen

..

..

..

..

..

..

..

..

..

..

..

..

.14

36.

4Pa

kete

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

147

6.5

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

..1

517

Run

dum

OO

P.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.15

37.

1A

ufba

uei

nerK

lass

e.

..

..

..

..

..

..

..

..

..

..

..

..

154

7.2

Priv

at-m

ehro

derw

enig

er.

..

..

..

..

..

..

..

..

..

..

..1

617.

3G

ette

rund

Sette

r.

..

..

..

..

..

..

..

..

..

..

..

..

..

166

7.4

Stat

isch

eM

etho

den

..

..

..

..

..

..

..

..

..

..

..

..

..1

717.

5Po

lym

orph

ie.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

174

7.6

Ver

erbu

ng.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.17

87.

7Z

usam

men

fass

ung

..

..

..

..

..

..

..

..

..

..

..

..

..

184

7.8

Anm

erku

ngen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

184

8D

atei

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

185

8.1

Öff

nen

und

Schl

ieße

nvo

nD

atei

en.

..

..

..

..

..

..

..

..

185

8.2

Les

enun

dSc

hrei

ben

..

..

..

..

..

..

..

..

..

..

..

..

.18

7

Page 7: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

8.3

Dat

eien

mit

Pick

le.

..

..

..

..

..

..

..

..

..

..

..

..

.19

28.

4Z

eich

enor

ient

iert

eD

atei

en.

..

..

..

..

..

..

..

..

..

..

.19

38.

5B

lock

orie

ntie

rte

Dat

eien

..

..

..

..

..

..

..

..

..

..

..

.19

58.

6B

inär

date

ien

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.20

28.

7V

erze

ichn

isse

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.20

58.

8Z

usam

men

fass

ung

..

..

..

..

..

..

..

..

..

..

..

..

..

208

9R

egul

äre

Aus

drüc

ke.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

209

9.1

Find

eirg

endw

o.

..

..

..

..

..

..

..

..

..

..

..

..

..

210

9.2

Aus

drüc

keim

Übe

rblic

k.

..

..

..

..

..

..

..

..

..

..

..

214

9.3

Gie

rige

sSu

chen

..

..

..

..

..

..

..

..

..

..

..

..

..

.21

79.

4M

atch

ing

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.21

89.

5Ic

hw

illm

ehr!

..

..

..

..

..

..

..

..

..

..

..

..

..

..

220

9.6

Mod

i.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

222

9.7

Gru

ppen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.22

59.

8W

eite

rfüh

rend

eH

inw

eise

..

..

..

..

..

..

..

..

..

..

..

232

9.9

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.23

410

Hal

bzei

t.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

235

11Ü

berb

lick

über

Mod

ule

..

..

..

..

..

..

..

..

..

..

..

..

..

.23

711

.1M

odul

cmat

h.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

238

11.2

Mod

ulda

tetim

e.

..

..

..

..

..

..

..

..

..

..

..

..

..

239

Page 8: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

11.3

Mod

ulge

topt

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.24

211

.4M

odul

mat

h.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

246

11.5

Mod

ulos

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.24

811

.6M

odul

os.p

ath

..

..

..

..

..

..

..

..

..

..

..

..

..

..

254

11.7

Mod

ulra

ndom

..

..

..

..

..

..

..

..

..

..

..

..

..

..

256

11.8

Mod

ulre

adlin

e.

..

..

..

..

..

..

..

..

..

..

..

..

..

.25

711

.9M

odul

sys

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

258

11.1

0M

odul

tarfi

le.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

262

11.1

1M

odul

time

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

263

11.1

2M

odul

uu.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

265

11.1

3A

llgem

eine

Info

rmat

ione

nüb

erM

odul

e.

..

..

..

..

..

..

.26

711

.14

Anm

erku

ngen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

268

12X

ML

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.26

912

.1E

inle

itung

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

270

12.2

XM

L-D

okum

ente

rzeu

gen

..

..

..

..

..

..

..

..

..

..

..

.271

12.3

XM

Lle

sen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

278

12.4

SAX

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.28

512

.5N

ützl

iche

Hel

fer

..

..

..

..

..

..

..

..

..

..

..

..

..

.28

912

.6Z

usam

men

fass

ung

..

..

..

..

..

..

..

..

..

..

..

..

..

.291

Page 9: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

13D

aten

bank

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.29

313

.1SQ

Lite

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

294

13.2

MyS

QL

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.29

813

.3A

nyD

BM

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.30

213

.4Z

usam

men

fass

ung

..

..

..

..

..

..

..

..

..

..

..

..

..

304

13.5

Anm

erku

ngen

..

..

..

..

..

..

..

..

..

..

..

..

..

..

304

14N

etzw

erk

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

305

14.1

Ein

fach

erZ

ugri

ffau

fWeb

ress

ourc

en.

..

..

..

..

..

..

..

.30

514

.2L

esen

beiW

ikiB

ooks

..

..

..

..

..

..

..

..

..

..

..

..

307

14.3

Auf

Wik

iBoo

kssc

hrei

ben

..

..

..

..

..

..

..

..

..

..

..

310

14.4

Anm

elde

nm

itC

ooki

es.

..

..

..

..

..

..

..

..

..

..

..

314

14.5

Zei

tser

ver

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

316

14.6

Cha

tser

ver

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.321

14.7

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.32

414

.8A

nmer

kung

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.32

515

PyG

ame

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.32

715

.1E

inG

rafik

fens

ter

..

..

..

..

..

..

..

..

..

..

..

..

..

.32

815

.2M

alpr

ogra

mm

..

..

..

..

..

..

..

..

..

..

..

..

..

..

332

15.3

Ani

mat

ion

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

338

15.4

Bild

erun

dFo

nts

..

..

..

..

..

..

..

..

..

..

..

..

..

.34

5

Page 10: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

15.5

Mus

ik.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.35

015

.6Z

usam

men

fass

ung

..

..

..

..

..

..

..

..

..

..

..

..

..

352

16G

rafis

che

Ben

utze

robe

rfläc

hen

mit

Qt4

..

..

..

..

..

..

..

..

..

.35

316

.1Fe

nste

r,öf

fne

Dic

h!.

..

..

..

..

..

..

..

..

..

..

..

..

354

16.2

Sign

ale

empf

ange

n.

..

..

..

..

..

..

..

..

..

..

..

..

.35

616

.3M

ehrW

idge

ts.

..

..

..

..

..

..

..

..

..

..

..

..

..

..3

6116

.4D

esig

n-Se

rver

..

..

..

..

..

..

..

..

..

..

..

..

..

..

369

16.5

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.37

717

Gra

fisch

eB

enut

zero

berfl

äche

nm

itw

xPyt

hon

..

..

..

..

..

..

..

.37

917

.1Vo

rber

eitu

ngun

dIn

stal

latio

n.

..

..

..

..

..

..

..

..

..

.38

017

.2Pl

opp!

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

382

17.3

Ein

enSc

hritt

wei

ter

..

..

..

..

..

..

..

..

..

..

..

..

.38

417

.4W

indo

ws

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.38

617

.5E

vent

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.38

817

.6A

nmer

kung

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

.39

218

Gra

fisch

eB

enut

zero

berfl

äche

nm

itG

TK

+.

..

..

..

..

..

..

..

..

393

18.1

Das

erst

eFe

nste

r.

..

..

..

..

..

..

..

..

..

..

..

..

..

394

18.2

Lay

out

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

398

18.3

Gra

fisch

eE

lem

ente

..

..

..

..

..

..

..

..

..

..

..

..

.40

618

.4B

enut

zero

berfl

äche

n-s

chne

llun

dei

nfac

h.

..

..

..

..

..

..

.421

Page 11: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18.5

Zus

amm

enfa

ssun

g.

..

..

..

..

..

..

..

..

..

..

..

..

.43

018

.6A

nmer

kung

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

..4

3119

Text

orie

ntie

rte

Ben

utze

robe

rfläc

hen

mit

Cur

ses

..

..

..

..

..

..

..

433

19.1

Hal

lo,W

elt!

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.43

419

.2K

urzr

efer

enz

Cur

ses

..

..

..

..

..

..

..

..

..

..

..

..

.43

819

.3M

ehrF

enst

er.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

446

19.4

Gro

ßeFe

nste

r.

..

..

..

..

..

..

..

..

..

..

..

..

..

.45

219

.5M

ause

reig

niss

e.

..

..

..

..

..

..

..

..

..

..

..

..

..

.45

619

.6Te

xtbo

x.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.45

819

.7Z

usam

men

fass

ung

..

..

..

..

..

..

..

..

..

..

..

..

..

.461

20W

eite

rfüh

rend

eIn

form

atio

nen

..

..

..

..

..

..

..

..

..

..

..

.46

320

.1E

infü

hrun

g,er

ste

Schr

itte

..

..

..

..

..

..

..

..

..

..

..

463

20.2

Mod

ule

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

464

20.3

Dat

eien

,I/O

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.46

520

.4X

ML

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.46

520

.5D

aten

bank

en.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

466

20.6

PyG

ame

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.46

620

.7Q

t.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.46

720

.8w

xPyt

hon

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

467

20.9

PyG

TK

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

468

Page 12: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

20.1

0C

urse

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.46

820

.11

Sons

tiges

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.46

821

Con

trib

utor

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.471

Abb

ildun

gsve

rzei

chni

s.

..

..

..

..

..

..

..

..

..

..

..

..

..

..

477

22L

icen

ses

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

..

.48

322

.1G

NU

GE

NE

RA

LPU

BL

ICL

ICE

NSE

..

..

..

..

..

..

..

..

483

22.2

GN

UFr

eeD

ocum

enta

tion

Lic

ense

..

..

..

..

..

..

..

..

.49

222

.3G

NU

Les

serG

ener

alPu

blic

Lic

ense

..

..

..

..

..

..

..

..

499

Page 13: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 14: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

1Vo

rwor

t

Her

zlic

hW

illko

mm

enzu

Pyth

onun

ter

Lin

ux.D

iese

sB

uch

möc

hte

Ihne

nei

neH

ilfe

beid

erB

enut

zung

von

Pyth

onun

teru

nixä

hnlic

hen

Bet

rieb

ssys

te-

men

sein

.Wir

lege

nW

erta

ufvo

llstä

ndig

eSk

ript

e,di

eSi

epe

rC

opy&

Past

eal

sG

rund

lage

eige

nerÜ

bung

enve

rwen

den

dürf

en.A

lleSk

ript

ew

urde

nun

ter

vers

chie

dene

nL

inux

dist

ribu

tione

nge

prüf

t,ei

neH

aftu

ngfü

reve

ntue

lleSc

hä-

den

wir

dje

doch

ausg

esch

loss

en.I

ndi

esem

Buc

hw

ird

davo

nau

sgeg

ange

n,da

ssPy

thon

inde

rVer

sion

ab2.

5in

stal

liert

wur

de.F

ürdi

eIn

stal

latio

nse

lbst

wir

dau

fdie

zahl

reic

hen

Ref

eren

zen

und

HO

WTO

sve

rwie

sen.

Jena

chL

inux

-D

istr

ibut

ion

iste

ine

neue

Pyth

on-V

ersi

onnu

rzw

eiM

ausk

licks

wei

tent

fern

t.

3

Page 15: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ein

zeln

eSk

ript

ebe

nötig

enev

entu

elln

euer

eV

ersi

onen

von

Pyth

on,i

nde

mFa

ller

folg

tein

kurz

erH

inw

eis.

Die

ses

Buc

hri

chte

tsic

han

Ein

stei

ger

indi

ePr

ogra

mm

ieru

ngvo

nPy

thon

.G

rund

sätz

liche

Com

pute

rken

ntni

sse

sollt

envo

rhan

den

sein

,Sie

sollt

enw

is-

sen,

was

Dat

eien

sind

,wie

Sie

eine

Text

date

iers

telle

nun

dw

ieSi

eei

neSh

ell

aufr

ufen

,um

die

Prog

ram

mbe

ispi

ele

zute

sten

.Ebe

nfal

lsso

llten

Sie

mit

Dat

ei-

rech

ten

vert

raut

sein

.Wen

nSi

esc

hon

Prog

ram

mie

rerf

ahru

ngen

habe

n,si

ndSi

eei

nop

timal

erK

andi

datf

ürdi

eses

Buc

h.W

irer

klär

enni

chtj

edes

klei

neD

etai

l.M

anch

eD

inge

blei

ben

offe

n.A

nder

eD

inge

mag

der

Aut

orsc

hlic

htal

szu

triv

ial–

oder

zusc

hwie

rig

–an

gese

hen

habe

n,um

eszu

erkl

ären

.Su-

chen

Sie

dann

eine

Erk

läru

ngan

ande

ren

Stel

len

und

erw

ägen

Sie,

uns

dara

nte

ilhab

enzu

lass

en.Z

uT

hem

en,d

iein

dies

emB

uch

beha

ndel

twur

den,

gibt

esau

chau

ßerh

alb

von

Wik

iboo

ksIn

form

atio

nen.

Die

sew

erde

nim

Kap

itel

Wei

terf

ühre

nde

Info

rmat

ione

n1ge

sam

mel

t.

1K

apite

l20

aufS

eite

463

Page 16: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Wen

nei

nB

uch

wie

dies

esbe

nutz

twir

d,so

verm

uten

wir,

möc

hte

derL

eser

hint

erhe

rin

Pyth

onpr

ogra

mm

iere

nkö

nnen

.Abe

rnic

htnu

rdas

Erl

erne

nvo

nSy

ntax

und

Sem

antik

eine

rPro

gram

mie

rspr

ache

istw

icht

ig,s

onde

rnau

chde

rre

chtli

che

Asp

ekt.

Inde

rE

Uda

rfm

an(t

eilw

eise

)no

chun

gest

raft

prog

ram

-m

iere

n.In

viel

enan

dere

nG

egen

den

wir

dm

anbe

droh

tvon

Soft

war

epat

ente

n.Si

ekö

nnen

sich

aufe

iner

Proj

ekts

eite

2da

rübe

rinf

orm

iere

n.

Zur

Ben

utzu

ngdi

eses

Buc

hes

ein

Spru

ch,d

erL

aots

efa

lsch

zuge

schr

iebe

n3

wir

d:„S

ages

mir

-und

ich

wer

dees

verg

esse

n.Ze

ige

esm

ir–

und

ich

wer

dem

ich

dara

ner

inne

rn.B

etei

lige

mic

h–

und

ich

wer

dees

vers

tehe

n.“

Wir

wün

sche

nIh

nen

viel

Spaß

mit

dem

Buc

hun

dm

itPy

thon

.

Das

Aut

oren

team

2http://patinfo.ffii.org/

3http://de.wikiquote.org/wiki/Laotse

Page 17: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 18: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

2E

rste

Schr

itte

2.1

Hal

lo,W

elt!

Ein

einf

ache

sH

allo

,Wel

t!-P

rogr

amm

sieh

tin

Pyth

onfo

lgen

derm

aßen

aus:

#!/usr/bin/python

print

"Hallo,

Welt!"

Spei

cher

nSi

edi

ese

Dat

eiun

terz

umB

eisp

ielerstes.py

und

gebe

nSi

ede

rD

atei

Aus

führ

ungs

rech

teüb

erchmodu+x

erstes.py

.Ans

chlie

-ße

ndkö

nnen

Sie

das

Prog

ram

mm

it./erstes.py

inei

nerL

inux

-She

ll

7

Page 19: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ausf

ühre

n:A

usga

beuserlocalhost:$̃./erstes.py

Hallo,

Welt!

Die

erst

eZ

eile

enth

ältd

enso

genn

ante

nSh

eban

g1 ,ein

eZ

eile

,die

inde

rShe

llde

npa

ssen

den

Inte

rpre

ter

für

das

folg

ende

Skri

ptau

fruf

t.D

iezw

eite

Zei

leen

thäl

tdie

erst

ePy

thon

-Anw

eisu

ng.D

erTe

xtin

nerh

alb

der

Hoc

hkom

mat

aw

ird

ausg

egeb

en.print

fügt

ein

New

-Lin

e-Z

eich

enan

.

#!/usr/bin/python

print

"Hallo,",

print

"Welt!"

Die

ses

Skrip

terz

eugt

die

glei

che

Aus

gabe

,jed

och

sorg

tdas

Kom

ma

dafü

r,da

ßst

atte

ines

New

-Lin

e-Z

eich

ens

ein

Lee

rzei

chen

eing

efüg

twir

d.

1http://de.wikipedia.org/wiki/Shebang

Page 20: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./erstes1.py

Hallo,

Welt!

Pyth

onkö

nnen

Sie

auch

imin

tera

ktiv

enM

odus

benu

tzen

.Die

seA

rt,P

ytho

nau

fzur

ufen

eign

etsi

chbe

sond

ers

dann

,w

enn

Sie

klei

neTe

sts

vorn

ehm

enw

olle

n:

Aus

gabe

userlocalhost:$̃python

Python

2.5.3

(r251:54863,

Oct

52007,

13:50:07)

[GCC

4.1.3

20070929

(prerelease)

(Ubuntu

4.1.2-16ubuntu2)]

on

linux2

Type

"help",

"copyright",

"credits"

or

"license"

for

more

information.

>>>

print

"Hallo,

Welt"

Hallo,

Welt

>>>

Page 21: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

>>

>is

tdie

Ein

gabe

auff

orde

rung

.Wen

nSi

edi

ese

sehe

n,da

nnkö

nnen

Sie

dire

ktlo

sleg

en.D

rück

enSi

eam

End

ede

rE

inga

beReturn

,so

wir

ddi

ePr

ogra

mm

zeile

ausg

efüh

rt.

2.2

Um

laut

e

Falls

Sie

jetz

tsch

onm

itde

mC

ode

expe

rim

entie

rtha

ben,

wir

dIh

nen

unte

rU

mst

ände

nau

fgef

alle

nse

in,

dass

die

Aus

gabe

der

Um

laut

eni

cht

korr

ekt

war

:Sie

beka

men

eine

Fehl

erm

eldu

ngzu

sehe

n.Fo

lgen

derC

ode

behe

btda

sPr

oble

m:

#!/usr/bin/python

#-*-

coding:

iso-8859-1

-*-

print

"Über

Sieben

Brücken..."

Page 22: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./umlaute.py

Über

Sieben

Brücken...

Die

Zeilecoding:iso-8859-1

enth

ältd

ieZe

iche

nsat

zkod

ieru

ng,d

ieSi

eim

gesa

mte

nQ

uellc

ode

verw

ende

ndü

rfen

.Wel

che

Kod

ieru

ngSi

eve

rwen

den,

häng

tvo

nde

nvo

nIh

nen

benu

tzte

nPr

ogra

mm

enab

.Sta

ttis

o-88

59-1

kön-

nen

Sie

selb

stve

rstä

ndlic

hau

chut

f-8

oder

eine

ande

revo

nIh

nen

bevo

rzug

teC

odie

rung

verw

ende

n.

2.3

Ein

gabe

n

Ein

gabe

nau

fder

Shel

lwer

den

mit

dem

Bef

ehlraw_input()

entg

egen

ge-

nom

men

:

#!/usr/bin/python

print

"Wie

ist

Ihr

Name?",

Page 23: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Name

=raw_input()

print

"Ihr

Name

ist",

Name

Aus

gabe

userlocalhost:$̃./eingabe1.py

Wie

ist

Ihr

Name?

Rumpelstilzchen

Ihr

Name

ist

Rumpelstilzchen

Name

ist

hier

bei

eine

Var

iabl

evo

nTy

pString

.Si

em

uss

nich

tex

pliz

itve

rein

bart

wer

den,

sond

ern

wir

der

zeug

t,w

enn

sie

gebr

auch

twir

d.

Man

kann

raw_input()

ein

Arg

umen

tmitg

eben

.Dad

urch

ersp

artm

ansi

chdi

eer

steprint

-Anw

eisu

ng.D

ieA

usga

beis

tdie

selb

ew

ieim

erst

enB

eisp

iel.

#!/usr/bin/python

Name

=raw_input("Wie

ist

Ihr

Name?

")

print

"Ihr

Name

ist",

Name

Page 24: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

2.4

Wei

tere

Aus

gabe

n

Neb

enZ

eich

enke

tten

könn

enSi

eau

chZ

ahle

nei

ngeb

en,d

iese

Zah

len

wer

den

vonraw_input()

jedo

chal

sZ

eich

enke

tten

beha

ndel

t,ei

neK

onve

rsio

nm

acht

aus

ihne

nga

nze

Zah

len:

#!/usr/bin/python

Alter

=int(raw_input("Wie

alt

sind

Sie?

"))

print

"Sie

sind",

Alter,

"Jahre

alt."

Aus

gabe

userlocalhost:$̃./ausgabe1.py

Wie

alt

sind

Sie?

100

Sie

sind

100

Jahre

alt.

Alter

soll

eine

ganz

eZa

hlw

erde

n,de

sweg

ensc

hrei

ben

wir

umda

sEr

gebn

isde

rE

inga

beei

neK

onve

rtie

rung

sauf

ford

erun

g.int(String)

erze

ugta

usei

nem

Stri

ngei

neZ

ahl,

wen

nde

rStr

ing

nura

usZ

iffer

nbe

steh

t.

Page 25: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Bei

mE

xper

imen

tiere

nm

itdi

esem

Prog

ram

mfä

lltau

f,da

ßes

beid

erE

inga

bevo

nni

cht-

Ziff

ern

abst

ürzt

:

Aus

gabe

userlocalhost:$̃./ausgabe1.py

Wie

alt

sind

Sie?

abc

Traceback

(most

recent

call

last):

File

"ausgabe1.py",

line

2,

in

<module>

Alter

=int(raw_input("Wie

alt

sind

Sie?

"))

ValueError:

invalid

literal

for

int()

with

base

10:

'abc'

Die

sem

Prob

lem

wol

len

wir

inei

nem

spät

eren

Kap

itela

ufdi

eSp

urko

mm

en,

wen

nes

umA

usna

hmeb

ehan

dlun

gge

ht.K

onve

rtie

rung

envo

nD

aten

type

nbe

spre

chen

wir

imnä

chst

enK

apite

l.

Ein

ean

dere

Art

,die

Aus

gabe

dies

esPr

ogra

mm

eszu

form

atie

ren

sind

For-

mat

stri

ngs:

#!/usr/bin/python

Page 26: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#-*-

coding:

utf-8

-*-

Name

=raw_input("Wie

heißen

Sie?

")

Alter

=int(raw_input("Wie

alt

sind

Sie?

"))

print

"Sie

heißen

%s

und

sind

%d

Jahre

alt."

%(Name,

Alter)

Aus

gabe

userlocalhost:$̃./ausgabe2.py

Wie

heißen

Sie?

Rumpelstilzchen

Wie

alt

sind

Sie?

109

Sie

heißen

Rumpelstilzchen

und

sind

109

Jahre

alt.

Hie

rbed

eute

tein%s

eine

nSt

ring

,%d

eine

ganz

eZ

ahl.

Die

Var

iabl

en,w

elch

edi

eso

erze

ugte

nL

ücke

nfü

llen,

wer

den

amE

nde

des

Stri

ngs

nach

gelie

fert

,w

obei

das

Proz

entz

eich

endi

eA

rgum

ente

nlis

teei

nlei

tet.

Die

dem

Stri

ngüb

er-

gebe

nen

Arg

umen

tew

erde

nin

Kla

mm

ern

als

soge

nann

tes

Tupe

l,da

rauf

kom

men

wir

noch

zusp

rech

en,a

ngef

ührt

.

Das

Proz

entz

eich

enha

tins

gesa

mtd

reiB

edeu

tung

en:A

lsm

athe

mat

isch

eO

pe-

ratio

nis

tes

ein

Mod

ulo-

Ope

rato

r,al

sTr

ennz

eich

enin

Form

atst

ring

sle

itete

s

Page 27: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

die

Arg

umen

tenl

iste

ein

und

als

Form

atie

rung

ssym

bolz

eigt

esan

,das

snu

nei

nA

rgum

entf

olgt

.

2.5

Ele

men

tare

Dat

enty

pen

Stri

ngs

könn

enex

pliz

itdu

rch

ein

vorr

ange

stel

ltesu

als

UT

F-8-

Stri

ngs

erkl

ärt

wer

den,

Strin

gs,i

nde

nen

Steu

erze

iche

nvo

rkom

men

,die

als

Text

ausg

edru

ckt

wer

den

solle

n,m

uss

hing

egen

einr

vorr

ange

stel

ltw

erde

n:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

UTFText

=u'Dies\u0020ist\u0020UTF-8'

RoherText

=r'Noch\tein\tText\nMit\u0020Steuerzeichen!'

NormalerText

='Ein\tText\nMit

Steuerzeichen!'

print

UTFText

print

RoherText

print

NormalerText

Page 28: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./ed1.py

Dies

ist

UTF-8

Noch\tein\tText\nMit\u0020Steuerzeichen!

Ein

Text

Mit

Steuerzeichen!

Inne

rhal

bvo

nUTFText

wer

den

UT

F-8-

Zei

chen

,in

dies

emFa

llda

sL

eerz

ei-

chen

,ein

gefü

gt.D

erTe

xtRoherText

wir

dm

itsam

tSte

uerz

eich

enau

sgeg

e-be

n,w

ähre

ndbe

iNormalerText

die

Steu

erze

iche

nin

terp

retie

rtw

erde

n.Es

wer

den

hier

ein

Tab

und

eine

Neu

eZ

eile

eing

efüg

t.

Zah

len

wer

den

sobe

hand

elt,

wie

man

essi

chna

ivvo

rste

llt:

#!/usr/bin/python

a=

3b

=7

print

a+

b,

a-

b,

b%

a,

b/

a

Page 29: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

c=

3.14

print

"%f**2

=%f"

%(c,

c**2)

Aus

gabe

userlocalhost:$̃./ed2.py

10

-4

12

3.140000**2

=9.859600

Der

Aus

druc

kb%a

istd

ieM

odul

o-O

pera

tion,

derA

usdr

uckc**2

hing

egen

bere

chne

tdas

Qua

drat

vonc

.

2.6

Funk

tione

nun

dM

odul

e

Funk

tione

ndi

enen

dazu

,wie

derk

ehre

nden

Cod

ezu

glie

dern

und

sodi

ePr

o-gr

amm

ieru

ngzu

vere

infa

chen

.Mei

stw

erde

nin

Funk

tione

nD

inge

bere

chne

t,of

tgeb

enFu

nktio

nen

das

Rec

hnun

gser

gebn

isw

iede

rpre

is.E

ine

solc

heR

ech-

nung

ists

=sin(3,14)

:

Page 30: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

import

math

s=

math.sin(3.14)

print

s

Aus

gabe

userlocalhost:$̃./fumu.py

0.00159265291649

Hie

rw

ird

das

gesa

mte

Mod

ulmath

impo

rtie

rt.

Ein

zig

die

Sinu

sfun

ktio

nw

ird

gebr

auch

t,da

sE

rgeb

nis

der

Rec

hnun

gw

ird

zuer

stin

die

Var

iabl

es

über

nom

men

und

ansc

hlie

ßend

aufd

emB

ildsc

hirm

darg

este

llt.A

ufM

odul

ew

erde

nw

irno

chde

taill

iert

inei

nem

eige

nen

Kap

itelz

usp

rech

enko

mm

en.

Page 31: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

2.7

Kom

men

tare

Kom

men

tare

helfe

nda

bei,

den

Que

llcod

ele

icht

erzu

vers

tehe

n.A

lsFa

ustre

gel

soll

sovi

elw

ienö

tig,s

ow

enig

wie

mög

lich

imQ

uellc

ode

doku

men

tiert

wer

den.

Wie

ein

Prog

ram

mfu

nktio

nier

t,so

llte

ersi

chtli

chse

in,w

asab

erei

nA

bsch

nitt

war

umtu

t,so

lldo

kum

entie

rtw

erde

n.

#!/usr/bin/python

"""Das

folgende

Programm

berechnet

die

Summe

zweier

Zahlen"""

#Zahlen

eingeben

a=

raw_input("Bitte

eine

Zahl

eingeben:

")

b=

raw_input("Bitte

noch

eine

Zahl

eingeben:

")

#in

ganze

Zahlen

konvertieren

aZahl

=int(a)

bZahl

=int(b)

#Summe

berechnen

und

ausgeben

Page 32: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

summeZahl

=aZahl

+bZahl

print

summeZahl

Der

erst

eK

omm

enta

rwir

dm

it"""

eing

elei

tetu

ndge

htso

lang

e,au

chüb

erm

ehre

reZ

eile

n,bi

sw

iede

r"""

vork

omm

t.K

omm

enta

re,d

iem

it#

begi

nnen

gehe

nbi

szu

mE

nde

derZ

eile

.

2.8

Ein

rück

unge

n

Eine

Bes

onde

rhei

tvon

Pyth

onis

t,da

sszu

sam

men

gehö

riger

Cod

egl

eich

grup

-pi

ertw

ird.

Blö

cke

wer

den

ande

rsal

sin

ande

ren

Prog

ram

mie

rspr

ache

nni

cht

etw

adu

rch

Schl

üsse

lwör

ter2

oder

durc

hsp

ezie

lleK

lam

mer

n3ge

kenn

zeic

hnet

,so

nder

ndu

rch

Ein

rück

ung.

2z.

B.b

egin

und

end

inPa

scal

3D

iege

schw

eift

enK

lam

mer

nin

C,C

++un

dJa

vasi

ndty

pisc

hfü

rvie

leSp

rach

en

Page 33: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Als

Vor

griff

aufd

asK

apite

lKon

trol

lstr

uktu

ren4

zeig

enw

irih

nen,

wie

zwei

print

-Anw

eisu

ngen

grup

pier

twer

den.

#!/usr/bin/python

a=

0if

a<

1:

print"a

ist

kleiner

als

1"

print"noch

eine

Ausgabe"

Die

beid

enprint

-Anw

eisu

ngen

gehö

ren

zusa

mm

en,w

eil

sie

die

glei

che

Ein

rück

ung

habe

n.B

eide

wer

den

nura

usge

führ

t,w

enn

derz

uif

gehö

rend

eA

usdr

uck

wah

ris

t.

4K

apite

l4au

fSei

te69

Page 34: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

2.9

Zus

amm

enfa

ssun

g

Sie

habe

nnu

ndi

egr

undl

egen

den

Mer

kmal

evo

nPy

thon

kenn

enge

lern

tund

könn

enbe

reits

einf

ache

Prog

ram

me

schr

eibe

n.In

den

folg

ende

nK

apite

lwer

-de

nw

icht

ige

Gru

ndla

gen

für

die

näch

sten

Schr

itte

beha

ndel

t,zu

mB

eisp

iel

Dat

enty

pen

und

Kon

trol

lstr

uktu

ren,

Funk

tione

n,M

odul

eun

dO

bjek

te.D

amit

wird

esm

öglic

h,ko

mpl

exer

ePr

ogra

mm

ezu

schr

eibe

n,di

eei

neSt

rukt

urie

rung

insi

nnvo

lleA

bsch

nitte

,Wie

derh

olun

gen

und

Ents

chei

dung

ener

mög

liche

n.Es

folg

enZu

griff

aufD

atei

enun

dre

gulä

reA

usdr

ücke

,mit

dene

nm

anse

inLi

nux

scho

nsi

nnvo

ller

wei

tern

kann

.Dan

ach

sehe

nw

irw

eite

r...

;-)

2.10

Anm

erku

ngen

Page 35: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 36: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3D

aten

type

n

Indi

esem

Kap

itel

bele

ucht

enw

irdi

eD

aten

type

nvo

nPy

thon

und

gebe

nty

pisc

heO

pera

tione

nan

,mit

dene

nV

aria

blen

dies

esTy

psm

odifi

zier

twer

den

könn

en.E

inw

icht

iges

Prin

zip

inPy

thon

istd

asD

uck-

Typi

ng1 .S

olan

geei

neV

aria

ble

jede

Ope

ratio

nun

ters

tütz

t,di

evo

nih

rge

ford

ert

wir

d,is

tPy

thon

der

Typ

der

Var

iabl

eneg

al.R

echt

nütz

lich

istd

ieE

igen

scha

ft,e

ine

Ent

ein

eine

nFr

osch

zuve

rwan

deln

,so

fern

das

mög

lich

ist.

Die

seZ

aube

rei

wir

dK

onve

rtie

rung

gena

nnt.

Kom

men

wir

aber

erst

zude

nD

aten

type

n.

1W

enn

etw

asso

auss

ieht

wie

eine

Ent

e(o

dere

inD

aten

typ)

,so

geht

wie

eine

Ent

eun

dso

quak

twie

eine

Ent

e,w

arum

soll

esda

nnke

ine

sein

?

25

Page 37: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.1

Boo

lean

Die

ser

Dat

enty

pre

präs

entie

rtW

ahrh

eits

wer

teau

sde

rM

enge

True

und

False

.Wer

tedi

eses

Dat

enty

psw

erde

nzu

mei

stbe

iAnf

rage

nzu

rück

gege

ben,

wie

zum

Bei

spie

l:E

nthä

ltfo

lgen

deZe

iche

nket

teau

ssch

ließl

ich

Ziffe

rn?.

Die

pass

ende

Stri

ng-M

etho

dehi

erzu

laut

etüb

rige

nsisdigit()

.E

rgeb

niss

ew

erde

nzu

mei

stim

Zus

amm

enha

ngm

itK

ontr

olls

truk

ture

n,üb

erdi

eSi

eim

näch

sten

Kap

itelm

ehr

erfa

hren

,ver

wen

det.

Wah

rhei

tsw

erte

kann

man

mit

Ope

rato

ren

verk

nüpf

en.

Die

logi

sche

nVe

rknü

pfun

gen

habe

nw

irin

folg

ende

rTab

elle

zusa

mm

enge

fass

t,w

obei

aun

db

Boo

l'sch

eV

aria

blen

sind

,die

nurd

ieW

erteFalse

undTrue

anne

hmen

könn

en:

ab

nota

aan

db

aor

ba

ˆb(x

or)

Fals

eFa

lse

True

Fals

eFa

lse

Fals

eFa

lse

True

True

Fals

eTr

ueTr

ueTr

ueFa

lse

Fals

eFa

lse

True

True

Page 38: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ab

nota

aan

db

aor

ba

ˆb(x

or)

True

True

Fals

eTr

ueTr

ueFa

lse

Ein

Aus

druc

kw

ird

sosc

hnel

lw

iees

geht

ausg

ewer

tet.

Ist

amA

nfan

gei

-ne

sko

mpl

izie

rten

Aus

druc

kssc

hon

klar

,das

sde

rAus

druc

kei

nen

best

imm

-te

nW

ahrh

eits

wer

terh

ält,

dann

wir

dni

chtw

eite

raus

gew

erte

t.Z

umB

eisp

iel

wird

Trueor(AandB)

zuTrue

ausg

ewer

tet,

ohne

dass

derA

usdr

uck

(AandB)

berü

cksi

chtig

tw

ird.

Die

ses

Vor

gehe

nis

tin

sbes

onde

rew

ich-

tigim

Zus

amm

enha

ngm

itFu

nktio

nen,

denn

Aun

dB

könn

enau

chFu

nk-

tione

nse

in,

die

indi

esem

Fall

nich

tau

fger

ufen

wer

den.

Gle

iche

sgi

ltfü

rFalseand(Ausdruck)

.Hie

rw

ird(Ausdruck)

eben

falls

nich

tbe

-rü

cksi

chtig

t.

Page 39: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.2

Zah

len

Zah

len

sind

Gru

ndty

pen

inPy

thon

.Es

gibt

vers

chie

dene

Sort

enZ

ahle

nun

-te

rsch

iedl

iche

rGen

auig

keit.

Hie

rfol

gtal

sVo

rgri

ffau

fdie

Erl

äute

rung

enei

nge

mei

nsam

esB

eisp

iel:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

#Int

a=

3print

a

#Long

b=

2**65

print

b

#Fließkommazahl

c=

2.7

d=

1.3

print

c//

d

Page 40: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#komplexe

Zahl

d=

5.0

+2.0j

print

d**2.0

Die

Aus

gabe

:

Aus

gabe

userlocalhost:$̃./zahlen1.py

3 36893488147419103232

2.0

(21+20j)

3.2.

1In

t

Gan

zeZ

ahle

nha

ben

Sie

scho

nin

den

erst

enSc

hritt

enke

nnen

gele

rnt.

Hie

rfo

lgtn

ochm

alei

neZ

usam

men

fass

ung

derD

inge

,die

Sie

mit

ganz

enZ

ahle

ntu

nkö

nnen

:

Page 41: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ope

ratio

nB

edeu

tung

abs(

Zah

l)be

rech

netd

enA

bsol

utbe

trag

derZ

ahl

bin(

Zah

l)(A

bPy

thon

2.6)

Lie

fert

die

binä

reD

arst

ellu

ngde

rZah

ldi

vmod

(Zah

l1,

Zah

l2)

bere

chne

tein

2-Tu

pel,

wob

eide

rers

teTe

ildi

ega

nzza

hlig

eD

ivis

ion

und

derz

wei

teTe

ildi

eM

odul

o-O

pera

tion

aus

den

beid

enZ

ahle

nis

t.he

x(Z

ahl)

Lie

fert

die

hexa

dezi

mal

eD

arst

ellu

ngde

rZah

loc

t(Z

ahl)

Okt

ale

Dar

stel

lung

derZ

ahl

chr(

Zah

l)lie

fert

das

Zei

chen

mit

dem

"ASC

II"-

Cod

eZa

hl,

z.B

.chr

(97)

liefe

rt'a

'./,

//G

anzz

ahlig

eD

ivis

ion

%M

odul

o-O

pera

tion

+,-,

*,**

Add

iere

n,Su

btra

hier

en,M

ultip

lizie

ren

und

Pote

nzie

ren

Page 42: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.2.

2L

ong

Die

serT

ypw

ird

verw

ende

t,w

enn

essi

chum

sehr

groß

eZ

ahle

nha

ndel

t.So

könn

enSi

ein

Pyth

onpr

oble

mlo

sa=2**65

bere

chne

n,da

sE

rgeb

nis

wir

din

eine

Zahl

vom

Typ

long

konv

ertie

rt.Za

hlen

dies

esTy

psw

irdm

anch

mal

ein

Lna

chge

stel

lt.D

ieO

pera

tione

nau

fsol

che

Zah

len

sind

die

glei

chen

wie

oben

besc

hrie

ben.

3.2.

3Fl

oat

Die

ser

Typ

repr

äsen

tiert

Flie

ßkom

maz

ahle

n.D

iese

Zah

len

wer

den

mit

ei-

nem

Dez

imal

punk

tnot

iert.

Folg

ende

Ope

ratio

nen

sind

aufF

ließk

omm

azah

len

defin

iert

:

Ope

ratio

nB

edeu

tung

Page 43: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ope

ratio

nB

edeu

tung

roun

d(Z

ahl)

rund

etdi

eZ

ahlk

aufm

änni

sch

zurn

ächs

tgrö

ße-

ren/

klei

nere

nga

nzen

Zah

l.D

asE

rgeb

nis

wir

dal

sFl

ießk

omm

azah

ldar

gest

ellt.

/N

orm

ale

Div

isio

n//

ents

pric

htde

rgan

zzah

ligen

Div

isio

n%

Mod

ulo-

Ope

ratio

n+,

-,*,

**A

ddie

ren,

Subt

rahi

eren

,Mul

tipliz

iere

nun

dPo

tenz

iere

n

3.2.

4C

ompl

ex

Kom

plex

eZ

ahle

n2be

steh

enau

sei

nem

2-Tu

pel,

wob

eisi

chei

nTe

ilR

ealte

ilun

dei

nan

dere

rIm

agin

ärte

ilne

nnt.

Man

kann

kom

plex

eZ

ahle

nni

chta

ufzä

h-

2U

mm

ehr

Hin

terg

rund

info

rmat

ione

nüb

erko

mpl

exe

Zah

len

zube

kom

men

,em

pfeh

len

wir

ihne

nda

sW

ikib

uch

Kom

plex

eZ

ahle

nˆ{http://de.wikibooks.org/wiki/

Komplexe%20Zahlen%20}

.

Page 44: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

len

oder

ents

chei

den,

wel

che

von

zwei

gege

bene

nZ

ahle

ngr

ößer

ista

lsdi

ean

dere

.Dar

gest

ellt

wer

den

solc

heZa

hlen

inPy

thon

als

Sum

me

von

Rea

l-un

dIm

agin

ärte

il,be

ispi

elsw

eiseC=5.0+2.0j

.

Folg

ende

Din

geka

nnm

anm

itko

mpl

exen

Zah

len

tun:

Ope

ratio

nB

edeu

tung

abs(

C)

Ber

echn

etde

nA

bsol

utbe

trag

derk

ompl

exen

Zah

lCC

.real

,C.im

aglie

fert

den

Rea

lteil,

Imag

inär

teil

derZ

ahlC

zurü

ck.

+,-,

*,/,

**A

ddie

ren,

Subt

rahi

eren

,Mul

tipliz

iere

n,D

ivid

ie-

ren

und

Pote

nzie

ren

Page 45: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.3

Stri

ngs

Ein

Stri

ngis

tein

eFo

lge

von

Zei

chen

.And

ers

als

inan

dere

nSp

rach

enka

nnm

anei

nen

Strin

gni

chtm

ehrv

erän

dern

.Man

mus

sda

zune

ueSt

rings

erze

ugen

,w

elch

ede

nU

rspr

ungs

stri

ngbe

inha

lten:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

#Gibt

den

String

aus

print

"Hallo,

Welt!"

#Fuegt

beide

Strings

zusammen,

ohne

Leerzeichen...

print

"Hallo"

+"Ballo"

#...

selbiges

mit

Leerzeichen

print

"Hallo",

"Ballo"

#Viermal

"Hallo"

print

"Hallo"*4

s=

"""

Page 46: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Dieses

ist

ein

langer

String,

er

geht

über

mehrere

Zeilen.

Es

steht

zwar

nichts

interessantes

darin,

aber

darauf

kommt

es

auch

nicht

an."""

print

s

Aus

gabe

userlocalhost:$̃./string1.py

Hallo,

Welt!

HalloBallo

Hallo

Ballo

HalloHalloHalloHallo

Dieses

ist

ein

langer

String,

er

geht

über

mehrere

Zeilen.

Es

steht

zwar

nichts

interessantes

darin,

aber

darauf

kommt

es

auch

nicht

an.

Page 47: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Stri

ngs

könn

enal

sozu

sam

men

gese

tzt

wer

den,

wob

eige

rade

die

Var

iant

e"Hallo"

*4

,ein

enne

uen

Stri

ngzu

erze

ugen

,ung

ewoh

ntab

erdi

rekt

er-

sche

int.

Lan

geSt

ring

sw

erde

neb

enso

gebi

ldet

wie

ein

Kom

men

tar,

mit

dem

Unt

ersc

hied

,das

ser

eine

rVar

iabl

ezu

gew

iese

nw

ird.

Tats

ächl

ich

sind

Kom

-m

enta

re,d

iem

it"""

gebi

ldet

wer

den

nich

tsan

dere

s,al

san

onym

eSt

ring

s.

Auf

Stri

ng-O

bjek

teka

nnm

anM

etho

den

anw

ende

n.D

iese

gebe

nof

tein

enE

rgeb

nis-

Stri

ngzu

rück

und

lass

enda

sO

rigi

nalu

nver

ände

rt:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

s=

"dies

ist

mein

kleiner

String"

print

s.capitalize()

print

s.replace("kleiner",

"kurzer")

print

s.upper()

Aus

gabe

userlocalhost:$̃./string2.py

Dies

ist

mein

kleiner

string

Page 48: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

dies

ist

mein

kurzer

String

DIES

IST

MEIN

KLEINER

STRING

Eini

gede

rMet

hode

n,di

eau

fein

Strin

g-O

bjek

tanw

endb

arsi

nd,fi

nden

sich

info

lgen

derT

abel

le:

Funk

tion

Bes

chre

ibun

gca

pita

lize(

)E

rzeu

gtei

nen

neue

nSt

ring

,des

sen

erst

erB

uch-

stab

egr

oßge

schr

iebe

nis

t.co

unt(

Subs

trin

g,A

nfan

g,E

nde)

Zäh

ltdi

eV

orko

mm

envo

nSu

bstr

ing

imO

bjek

t.A

nfan

gun

dE

nde

sind

optio

nal

find(

Subs

trin

g,A

n-fa

ng,E

nde)

Find

etda

ser

ste

Vor

kom

men

von

Subs

trin

g,gi

btde

nIn

dex

inne

rhal

bde

sSt

ring

sod

er-1

zurü

ck.

Anf

ang

und

End

esi

ndop

tiona

l.lo

wer

()G

ibte

inen

Stri

ngzu

rück

,der

nura

usK

lein

buch

-st

aben

best

eht

Page 49: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bes

chre

ibun

gre

plac

e(A

lt,N

eu,

Anz

ahl)

Ers

etzt

imSt

ring

Alt

gege

nN

eu.N

urdi

eer

sten

Anz

ahlV

orko

mm

enw

erde

ner

setz

t.A

nzah

list

optio

nal.

stri

p(Ze

iche

n)E

ntfe

rntd

ieV

orko

mm

envo

nZe

iche

nam

An-

fang

und

amE

nde

vom

Stri

ng.W

enn

Zeic

hen

nich

tang

egeb

enw

ird,

sow

ird

Lee

rzei

chen

ange

-no

mm

en.

uppe

r()

Gib

tein

enSt

ring

zurü

ck,d

ernu

raus

Gro

ßbuc

h-st

aben

best

eht.

isal

num

()Tr

ue,w

enn

derS

trin

gau

sZ

iffer

nun

dB

uchs

ta-

ben

best

eht

isal

pha(

)Tr

ue,w

enn

derS

trin

gau

sB

uchs

tabe

nbe

steh

t.is

digi

t()

True

,wen

nde

rStr

ing

aus

Ziff

ern

best

eht.

star

tsw

ith(P

refix

,A

nfan

g,E

nde)

True

,wen

nam

Anf

ang

des

Stri

ngs

Pre

fixvo

r-ko

mm

t.D

ieO

ptio

nale

nPa

ram

eter

Anf

ang

und

End

ebe

gren

zen

den

Such

bere

ich.

Page 50: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bes

chre

ibun

gsp

lit(T

renn

er)

Zer

legt

eine

nSt

ring

inei

nzel

neW

orte

.Tre

nner

isto

ptio

nal.

Ohn

eA

ngab

ew

ird

beiL

eerz

eich

en,

Tabu

lato

ren

und

Zei

lenu

mbr

uech

enge

tren

nt.

join

(Lis

te)

Fügt

eine

Lis

tevo

nSt

ring

sm

itdi

esem

Stri

ngw

iede

rzus

amm

en.T

renn

er.jo

in(s

.spl

it(Tr

enne

r))

sollt

ege

nau

den

Stri

ngs

wie

derg

eben

.

Meh

rübe

rStr

ings

erfa

hren

Sie

imA

bsch

nitt

Sequ

enze

n3 .

3.3.

1U

nico

de-S

trin

gsun

dZ

eich

enko

dier

ung

Stri

ngs

inPy

thon

wer

den

inte

rnim

mer

als

Uni

code

-Cod

epoi

nts4

vera

rbei

tet.

Ein

Cod

epoi

ntis

tein

efe

stge

legt

eZ

ahl,

die

gena

uei

nem

Zei

chen

zuge

ordn

et

3K

apite

l3.7

aufS

eite

504

http://de.wikipedia.org/wiki/Unicode

Page 51: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ist.

Der

Uni

code

-Sta

ndar

dse

lbst

defin

iert

zude

mTr

ansf

orm

atio

nsfo

rmat

ew

iezu

mB

eisp

iel

UT

F-8,

die

wie

deru

mdi

eta

tsäc

hlic

heB

yte-

Dar

stel

lung

für

die

Spei

cher

ung

fest

lege

n.W

icht

igzu

vers

tehe

nis

t,da

ssei

nU

nico

de-

Cod

epoi

ntni

cht

mit

eine

rU

TF-

8-B

yte-

Dar

stel

lung

glei

chzu

setz

enis

t.Si

eha

ben

norm

aler

wei

seun

ters

chie

dlic

heW

erte

füre

inbe

stim

mte

sZ

eich

en.

Stri

ngs

wer

den

inzw

eiSc

hritt

enve

rarb

eite

t.E

sgi

btei

nen

Dek

odie

rung

s-bz

w.e

inen

Kod

ieru

ngss

chrit

t.Fü

rbei

deSc

hritt

est

ehen

anal

ogdi

eFu

nktio

nen

decode()

undencode()

zur

Ver

fügu

ng.B

eide

Funk

tione

nsi

ndin

der

Kla

sseunicode

undstr

zufin

den.

Imer

sten

Schr

ittw

ird

die

Byt

efol

gen-

Dek

odie

rung

derP

ytho

n-Q

uelld

atei

indi

eU

nico

de-C

odep

oint

-Dar

stel

lung

durc

hgef

ührt

.Übe

rdie

inde

rQue

lldat

eian

gege

bene

Kom

men

tarz

eile#-*-coding:UTF-8-*-

wir

dau

fdie

Stan

dard

zeic

hend

ekod

ieru

nghi

ngew

iese

n,di

ezu

raut

omat

isch

enD

ekod

ieru

nghi

nzu

rint

erne

nU

nico

de-C

odep

oint

-Dar

stel

lung

benu

tztw

erde

nso

ll.D

azu

istv

omPr

ogra

mm

iere

rsi

cher

zust

elle

n,da

ssdi

eD

atei

auch

inde

rgl

eich

enB

yte-

Kod

ieru

ng(h

ierU

TF-

8)ab

gesp

eich

erti

st,w

iein

derK

omm

enta

rzei

lean

gege

ben.

Page 52: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Imzw

eite

nSc

hritt

istd

ieU

nico

de-C

odep

oint

-Dar

stel

lung

indi

eZ

ielk

odie

-ru

ngfü

rden

Stri

ngzu

brin

gen.

Das

gesc

hieh

tübe

rdieencode()

-Fun

ktio

nun

dis

tnur

dann

notw

endi

g,w

enn

eine

abw

eich

ende

Ziel

kodi

erun

gzu

rCod

ing-

Kom

men

tarz

eile

ange

stre

btw

ird.

Die

folg

ende

Bei

spie

ldat

eizeichenkodierung.py

dem

onst

rier

tdi

eB

ytef

olge

ndar

stel

lung

deru

nter

schi

edlic

hen

Zei

chen

kodi

erun

gen:

#!/usr/bin/python

#-*-

coding:

UTF-8

-*-

UnicodeText=u'ÄÜÖC'

UTF_8Text='ÄÜÖC'

ISO_8859_1TextIgnore=u'ÄÜÖC'.encode('iso-8859-1',

'ignore')

ISO_8859_1TextReplace='ÄÜÖC'.decode('UTF-8').encode('iso-8859-1',

'replace')

def

bytefolge(kommentar,

zeichenkette):

forzeichen

in

zeichenkette:

print"%x"

%ord(zeichen),

print"(%s)"

%kommentar

Page 53: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

bytefolge("Unicode-Codepoint-Folge",

UnicodeText)

bytefolge("UTF-8-Bytefolge",

UTF_8Text)

bytefolge("ISO-8859-1-Bytefolge

(C

ignoriert)",

ISO_8859_1TextIgnore)

bytefolge("ISO-8859-1-Bytefolge

(C

ersetzt)",

ISO_8859_1TextReplace)

Aus

gabe

userlocalhost:$̃./zeichenkodierung.py

c4

dc

d6

20ac

(Unicode-Codepoint-Folge)

c3

84

c3

9c

c3

96

e2

82

ac

(UTF-8-Bytefolge)

c4

dc

d6

(ISO-8859-1-Bytefolge

(C

ignoriert))

c4

dc

d6

3f

(ISO-8859-1-Bytefolge

(C

ersetzt))

Esse

idar

aufh

inge

wie

sen,

dass

das

Euro

zeic

hen

(C)i

nde

rZei

chen

kodi

erun

gIS

O-8

859-

1ni

chtv

orha

nden

ist.

Des

halb

wer

den

imB

eisp

ielz

wei

vers

chie

-de

neSt

rate

gien

zurB

ehan

dlun

gdi

eser

Situ

atio

nge

zeig

t.Im

erst

enFa

llw

ird

das

C-Z

eich

enig

nori

ertu

nder

hält

som

itau

chke

ine

Byt

erep

räse

ntat

ion

inde

raus

gege

bene

nB

ytef

olge

.Im

Zw

eite

nw

ird

eser

setz

tdur

chda

sSt

anda

rd-

Ers

atzz

eich

enfü

rISO

-885

9-1,

das

Frag

ezei

chen

(0x3

f).

Page 54: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.4

Zei

chen

Zei

chen

kann

man

als

Spez

ialf

allv

onSt

ring

sau

ffas

sen.

Sie

sind

Stri

ngs

der

Län

geE

ins.

Wir

führ

ensi

ehi

erau

f,um

zwei

insp

äter

enK

apite

lnbe

nö-

tigte

Funk

tione

nau

fzuf

ühre

n,nä

mlic

hord(Zeichen)

undchr(Zahl)

.ord(Zeichen)

liefe

rtei

neZ

ahl,

die

deri

nter

nen

Dar

stel

lung

des

Zei

chen

sen

tspr

icht

,wäh

rend

chr(Zahl)

ein

Zei

chen

zurü

cklie

fert

,wel

ches

zura

n-ge

gebe

nen

Zah

lpas

st.

#!/usr/bin/python

print

"'A'

hat

den

numerischen

Wert",

ord('A')

print

"Das

Zeichen

mit

der

Nummer

100

ist

'"

+chr(100)

+"'"

Aus

gabe

userlocalhost:$̃./zeichen1.py

'A'

hat

den

numerischen

Wert

65

Das

Zeichen

mit

der

Nummer

100

ist

'd'

Page 55: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.5

Lis

ten

Lis

ten

sind

besc

hrei

bbar

eD

aten

type

n,di

eda

zudi

enen

,zur

selb

enZ

eitE

le-

men

tebe

liebi

gen

Typs

aufz

uneh

men

.

#!/usr/bin/python

Werte

=['Text',

'Noch

ein

Text',

42,

3.14]

print

Werte

print

"Anzahl

der

Elemente:

",

len(Werte)

Aus

gabe

userlocalhost:$̃./listen1.py

['Text',

'Noch

ein

Text',

42,

3.1400000000000001]

Anzahl

der

Elemente:

4

Die

Funk

tionlen()

best

imm

tdie

Anz

ahld

erE

lem

ente

derL

iste

,in

dies

emFa

ll4.

Lis

ten

könn

enau

chL

iste

nen

thal

ten,

auch

sich

selb

st.

Page 56: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Hin

zuge

fügt

wer

den

Wer

tem

itde

m+

-Ope

rato

run

dde

nFu

nktio

nen

append()

undinsert()

:

#!/usr/bin/python

Werte

=['Text',

42]

Werte

+=

['foo']

Werte.append(3)

Werte.insert(2,

111)

print

Werte

Aus

gabe

userlocalhost:$̃./listen2.py

['Text',

42,

111,

'foo',

3]

wob

eim

andi

ese

Funk

tione

nM

etho

den

nenn

t,da

sie

Bes

tand

teil

derL

iste

nobj

ekte

sind

.Die

Met

hode

insert(2,111)

fügt

andi

ezw

eite

Stel

ledi

eZ

ahl1

11ei

n.D

ieZ

ählu

ngbe

ginn

tmit

der0

,das

nullt

eE

lem

enti

stdi

eZ

eich

enke

tteTe

xt.

Lös

chen

lass

ensi

chL

iste

nele

men

teeb

enfa

lls:

Page 57: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

Werte

=[1,

2,

'Meier',

4,

5]

print

Werte.pop()

print

Werte.pop(0)

Werte.remove('Meier')

print

Werte

Aus

gabe

userlocalhost:$̃./listen3.py

5 1 [2,

4]

Die

Met

hodepop()

liefe

rtoh

neA

rgum

entd

asle

tzte

Ele

men

tder

Lis

teun

den

tfer

ntes

ansc

hlie

ßend

.Mit

Arg

umen

twir

dda

sN

-te

Ele

men

tgel

ösch

t.D

ieM

etho

deremove()

entf

ernt

das

Ele

men

tmit

dem

ange

gebe

nen

Schl

üsse

l.

Lis

ten

lass

ensi

chau

chpe

rFu

nktio

ner

zeug

en.

Ein

eso

lche

Funk

tion

ist

range(von,bis,step)

.Sie

erw

arte

tein

enSt

artw

erts

owie

eine

nEn

d-

Page 58: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

wer

tund

baut

dara

usei

neLi

ste,

wob

eide

rEnd

wer

tnic

htTe

ilde

rent

steh

ende

nLi

ste

ist.

Die

Para

met

ervo

nun

dst

epsi

ndop

tiona

lund

gebe

nde

nA

nfan

gsw

ert

wie

auch

die

Schr

ittw

eite

an,m

itde

rLis

tene

lem

ente

zwis

chen

dem

Star

t-un

dde

mE

ndw

erte

inge

fügt

wer

den.

#!/usr/bin/python

l1

=range(1,

10)

l2

=range(1,

10,

3)

print

l1

print

l2

Aus

gabe

userlocalhost:$̃./listen4.py

[1,

2,

3,

4,

5,

6,

7,

8,

9]

[1,

4,

7]

Inun

sere

mB

eisp

iele

nthä

ltl1

alle

Wer

tevo

n1

bis

9,l2

hing

egen

enth

ält

ledi

glic

h1,

4un

d7,

wei

lwir

eine

Schr

ittw

eite

von

3ve

rein

bart

habe

n.D

ierange()

-Fun

ktio

nle

gtüb

rigen

sdie

gesa

mte

List

eim

Spei

cher

an,w

esw

egen

Page 59: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

man

sich

vor

Geb

rauc

hun

bedi

ngts

iche

rse

inso

llte,

genu

gda

von

zuha

ben.

Ein

eL

iste

mit

meh

rere

nM

illio

nen

Ein

träg

enzu

erze

ugen

daue

rtei

neW

eile

,w

iede

rA

utor

dies

erZ

eile

nw

ähre

ndei

nes

rech

teng

term

inie

rten

Vor

trag

sfe

stst

elle

nm

usst

e,al

sers

tattxrange()

(daz

uko

mm

enw

irsp

äter

)range()

schr

ieb.

Meh

rübe

rLis

ten

erfa

hren

Sie

imA

bsch

nitt

Sequ

enze

n5 .

3.6

Tupe

l

Tupe

llas

sen

sich

,and

ers

als

List

en,n

icht

verä

nder

n.Si

esi

ndda

mit

beso

nder

sge

eign

et,u

mK

onst

ante

nzu

repr

äsen

tiere

n.A

nson

sten

ähne

lnsi

eL

iste

nab

erse

hr:

#!/usr/bin/python

5K

apite

l3.7

aufS

eite

50

Page 60: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Werte

=('Text',

'Noch

ein

Text',

42,

3.14)

print

min(Werte)

print

max(Werte)

print

"Anzahl

der

Elemente:

",

len(Werte)

Aus

gabe

userlocalhost:$̃./tupel1.py

3.14

Text

Anzahl

der

Elemente:

4

Ein

Tupe

lwir

din

rund

eK

lam

mer

nge

schr

iebe

n.min()

best

imm

tdas

Mi-

nim

umei

nes

Tupe

ls,max()

das

Max

imum

.Ent

hält

ein

Tupe

lTex

t,so

wir

ddi

eser

alph

abet

isch

verg

liche

n.

Meh

rübe

rTup

eler

fahr

enSi

eim

näch

sten

Abs

chni

ttSe

quen

zen6 .

6K

apite

l3.7

aufS

eite

50

Page 61: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.7

Sequ

enze

n

ZuSe

quen

zen

zähl

endi

ehi

erbe

hand

elte

nSt

rings

,Lis

ten

und

Tupe

l.Le

digl

ich

Lis

ten

lass

ensi

chän

dern

,alle

ande

ren

Sequ

enzt

ypen

sind

kons

tant

.Gru

ndge

nug,

eini

geD

etai

lszu

sam

men

zufa

ssen

.

Sequ

enze

nkö

nnen

aufg

ezäh

ltw

erde

n.D

aser

ste

Ele

men

that

den

Inde

x0,

das

letz

teE

lem

entd

enIn

dexlen(Sequenz)-1

.Seq

uenz

enkö

nnen

ihre

rsei

tsw

iede

rSeq

uenz

enau

fneh

men

.Ein

eB

eson

derh

eiti

st,d

ass

man

Teils

eque

nzen

,so

gena

nnte

Slic

es,b

ilden

kann

:

#!/usr/bin/python

text

="Dies

ist

mein

String"

print

"Grossbuchstaben:

",

text[0],

text[14]

print

"Verb:

",

text[5:8]

print

"Erstes

Wort:

",

text[:4]

print

"Letztes

Wort:

",

text[14:]

Page 62: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./seq1.py

Grossbuchstaben:

DS

Verb:

ist

Erstes

Wort:

Dies

Letztes

Wort:

String

An

dies

emB

eisp

iels

ieht

man

,das

sm

anei

nzel

neZ

eich

endi

rekt

adre

ssie

ren

kann

,wob

eim

ande

nIn

dex

inec

kige

Kla

mm

ern

setz

t,w

ieau

chei

nen

Ber

eich

derS

eque

nzan

spre

chen

kann

,ind

emA

nfan

gun

dE

nde

durc

hD

oppe

lpun

ktge

tren

ntw

erde

n.A

nfan

gun

dE

nde

vom

Slic

esi

ndop

tiona

l.St

ehtv

orde

mD

oppe

lpun

ktke

inW

ert,

sois

tder

Anf

ang

derS

eque

nzge

mei

nt.A

nalo

ges

gilt

fürd

asE

nde.

Wen

nSi

edi

ese

Art

derA

dres

sier

ung

vers

tand

enha

ben,

fällt

esIh

nen

sich

erle

icht

,die

nega

tive

Adr

essi

erun

geb

enfa

llszu

vers

tehe

n:

#!/usr/bin/python

Page 63: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

sequenz

=(1,

2,

'a',

'b',

'c')

print

"Buchstaben:

",

sequenz[-3:]

print

"Ziffern:

",

sequenz[:-3]

Aus

gabe

userlocalhost:$̃./seq2.py

Buchstaben:

('a',

'b',

'c')

Ziffern:

(1,

2)

Buc

hsta

beni

ndiz

esw

erde

nhi

ervo

mE

nde

gezä

hlt.

Der

Inde

x-1

istd

asc

,de

rInd

ex-2

istd

asb

und

sow

eite

r.D

ieB

uchs

tabe

nw

erde

nal

sovo

mdr

itt-

letz

ten

zum

letz

ten

hin

ausg

egeb

en.Z

iffer

nhi

ngeg

enw

erde

nvo

mN

ullte

nzu

meb

enfa

llsdr

ittle

tzte

nau

sgeg

eben

,wob

eieb

endi

eses

nich

tmit

ausg

egeb

enw

ird.

Auf

Sequ

enze

nsi

ndge

mei

nsam

eO

pera

tore

nun

dM

etho

den

defin

iert.

Folg

ende

Tabe

llegi

btei

nen

Übe

rblic

k:

Funk

tion

Bes

chre

ibun

gB

eisp

iel

Page 64: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bes

chre

ibun

gB

eisp

iel

S*

nE

rzeu

gtei

neSe

quen

z,di

eau

sde

rn-f

ache

nA

nein

an-

derr

eihu

ngvo

nS

best

eht.

(3,)

*10

,"H

allo

"*

2

min

(),m

ax()

Bes

timm

tdas

Min

imum

/-M

axim

umde

rSeq

uenz

min

((1,

2,3)

),m

ax([

'a',

'b',

'c'])

ain

STr

ue,w

enn

Ele

men

tain

derS

eque

nzS

vork

omm

t3

in[0

]*7

S+

TD

ieSe

quen

zen

Sun

dT

wer

den

anei

nand

erge

häng

t(1

,2,3

)+(2

,)

len(

S)L

änge

,Anz

ahld

erE

le-

men

tevo

nS

len(

"Hal

lo,W

elt!

")

Page 65: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.8

Set

Der

Typ

setb

esch

reib

tMen

gen.

Ele

men

teei

nerM

enge

sind

unge

ordn

etun

dei

nzig

artig

.Alle

Sets

unte

rstü

tzen

die

üblic

hen

Men

geno

pera

tione

n:

#!/usr/bin/python

s1

=set('abc')

s2

=set('bcd')

print

's1

=',

s1,

's2

=',

s2

#Differenzmenge

print

's1

-s2

=',

s1

-s2

#Vereinigungsmenge

print

's1

|s2

=',

s1

|s2

#Schnittmenge

print

's1

&s2

=',

s1

&s2

#Symmetrische

Differenz

print

's1

^s2

=',

s1

^s2

#Enthalten

print

"'a'

in

s1

=",

'a'

in

s1

#Maechtigkeit

der

Menge

print

"len(s1)

=",

len(s1)

Page 66: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./set1.py

s1

=set(['a',

'c',

'b'])

s2

=set(['c',

'b',

'd'])

s1

-s2

=set(['a'])

s1

|s2

=set(['a',

'c',

'b',

'd'])

s1

&s2

=set(['c',

'b'])

s1

ˆs2

=set(['a',

'd'])

'a'

in

s1

=True

len(s1)

=3

Die

Ope

ratio

nin

liefe

rtal

sE

rgeb

nisTrue

wen

nei

nE

lem

enti

nde

rMen

gevo

rkom

mt.

Folg

ende

Met

hode

nla

ssen

sich

von

eine

mSe

t-O

bjek

tans

prec

hen:

Met

hode

Bes

chre

ibun

gs1

.diff

eren

ce(s

2)D

iffer

enzm

enge

,s1

-s2

s1.in

ters

ectio

n(s2

)Sc

hnitt

men

ge,s

1&

s2s1

.issu

bset

(s2)

Teilm

enge

,s1

<=s2

Page 67: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Met

hode

Bes

chre

ibun

gs1

.issu

pers

et(s

2)O

berm

enge

,s1

>=s2

s1.u

nion

(s2)

Ver

eini

gung

smen

ge,s

1|s

2s1

.sym

met

ric_

-di

ffer

ence

(s2)

Sym

met

risc

heD

iffer

enz,

s1ˆs

2

s.ad

d(E

)Fü

gtde

mSe

tsda

sE

lem

entE

hinz

us.

rem

ove(

E)

Ent

fern

tdas

Ele

men

tEau

sde

mSe

t

3.9

Dic

tiona

rys

Der

Typ

Dic

tiona

ryst

ellt

eine

Zuor

dnun

gzw

isch

enSc

hlüs

seln

und

Wer

ten

her.

Eri

stge

nau

wie

ein

Wör

terb

uch

zuve

rste

hen,

wo

als

Schl

üsse

lzum

Bei

spie

lei

nen

glis

cher

Beg

riff

und

als

Wer

tein

deut

schs

prac

hige

rBeg

riff

aufg

efüh

rtis

t.Se

lbst

vers

tänd

lich

lass

ensi

chau

chTe

lefo

nnum

mer

nod

erG

ehäl

ter

auf

dies

eW

eise

ordn

en:

Page 68: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

personal

={'Tom'

:32000,

'Beate'

:44000,

'Peter'

:10000}

print

personal

print

"Tom

verdient

%d

Euro

pro

Jahr"

%(personal['Tom'])

Aus

gabe

userlocalhost:$̃./dict1.py

{'Peter':

10000,

'Beate':

44000,

'Tom':

32000}

Tom

verdient

32000

Euro

pro

Jahr

Dic

tiona

rys

könn

enm

odifi

zier

twer

den.

Dar

über

hina

usbi

etet

die

Met

hode

keys()

die

Mög

lichk

eit,

sich

alle

Schl

üsse

lanz

eige

nzu

lass

en.

#!/usr/bin/python

personal

={'Tom'

:32000,

'Beate'

:44000,

'Peter'

:10000}

print

personal

print

"Susi

kommt

dazu...",

personal['Susi']

=10000

print

personal.keys()

Page 69: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"Peter

hat

einen

anderen

Job

gefunden..."

del

personal['Peter']

print

personal.keys()

print

"Tom

bekommt

mehr

Geld:

",

personal['Tom']

=33000

print

personal

Aus

gabe

userlocalhost:$̃./dict2.py

{'Peter':

10000,

'Beate':

44000,

'Tom':

32000}

Susi

kommt

dazu...

['Susi',

'Peter',

'Beate',

'Tom']

Peter

hat

einen

anderen

Job

gefunden...

['Susi',

'Beate',

'Tom']

Tom

bekommt

mehr

Geld:

{'Susi':

10000,

'Beate':

44000,

'Tom':

33000}

Elem

ente

kann

man

hinz

ufüg

en,i

nde

mm

anei

nen

neue

nSc

hlüs

seli

nec

kige

nK

lam

mer

nan

spri

cht,

und

dies

emei

nen

Wer

tzuw

eist

.Mitdelete()

lass

ensi

chSc

hlüs

sel/W

ert-P

aare

lösc

hen.

Die

Met

hodekeys()

zeig

talle

Schl

üsse

lei

nes

Dic

tiona

rys

als

Lis

tean

.Fol

gend

eTa

belle

zeig

tda

rübe

rhin

aus

noch

eini

gege

bräu

chlic

heD

ictio

nary

-Met

hode

n:

Page 70: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bes

chre

ibun

gge

t(Sc

hlüs

sel)

Lie

fert

den

Wer

tfür

Schl

üsse

lha

s_ke

y(Sc

hlüs

sel)

True

,wen

nSc

hlüs

selv

orko

mm

tite

ms(

)G

ibtd

enIn

halt

als

Lis

tevo

nTu

peln

zurü

ckpo

p(Sc

hlüs

sel)

Gib

tden

Wer

tfür

Schl

üsse

lzur

ück,

entf

ernt

dann

Schl

üsse

l/Wer

tke

ys()

liefe

rtal

leSc

hlüs

sela

lsL

iste

valu

es()

anal

ogzu

keys

(),l

iefe

rtal

leW

erte

als

Lis

te

ImK

apite

lD

aten

bank

en7

lern

enSi

eei

neD

aten

bank

kenn

en,

die

wie

ein

Dic

tiona

ryfu

nktio

nier

t.

7K

apite

l13

aufS

eite

293

Page 71: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.10

Bes

onde

rhei

ten

beim

Kop

iere

n

Bei

mK

opie

ren

von

Varia

blen

gibt

esei

neB

eson

derh

eit.

Die

Kop

ien

verw

eise

nw

iede

rauf

die

Orig

inal

e.Ve

rsuc

htm

annu

n,ei

neK

opie

zuve

ränd

ern,

verä

nder

tm

angl

eich

zeiti

gda

sO

rigi

nal,

wie

folg

ende

sB

eisp

ielz

eigt

:

#!/usr/bin/python

liste1

=[1,

2,

3]

liste2

=liste1

liste2

+=

[5]

print

liste1

print

liste2

Stat

tzw

eier

unte

rsch

iedl

iche

rLis

ten

beko

mm

enw

irdi

eses

erst

aunl

iche

Erge

b-ni

s:

Aus

gabe

userlocalhost:$̃./kopieren1.py

Page 72: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

[1,

2,

3,

5]

[1,

2,

3,

5]

Wir

habe

nal

soga

rkei

neK

opie

bear

beite

t,so

nder

nnu

rdie

einz

igvo

rhan

dene

Lis

te,a

ufdi

eso

woh

llis

te1

als

auch

liste

2nu

rver

wei

sen.

Lös

ung

des

Prob

lem

s:lis

te2

=lis

te1[

:].E

inSl

ice

über

die

kom

plet

teL

iste

.Fü

rand

ere

Dat

enty

pen

(abe

rauc

hL

iste

n)gi

btes

aus

dem

Mod

ul8copy

die

Funk

tioncopy()

.Dic

tiona

ries

habe

nei

neei

gene

copy()

-Met

hode

.All

dies

eser

zeug

tabe

rnu

rei

neei

nefla

che

Kop

ie.S

olle

nau

chz.

B.L

iste

nm

itko

pier

twer

den,

die

inei

nerL

iste

enth

alte

nsi

nd,v

erw

ende

tman

die

Funk

tion

copy.deepcopy()

.Hie

rzu

noch

ein

Bei

spie

l:

#!/usr/bin/python

import

copy

tupel1

=(1,

2,

[3,

4],

5)

tupel2

=copy.deepcopy(tupel1)

8M

ehrü

berM

odul

eun

dde

ren

Anw

endu

ngen

finde

tsic

him

Kap

itelP

ytho

nun

terL

inux

:M

odul

eˆ{

Kap

itel6

aufS

eite

137}

Page 73: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#tupel2

=copy.copy(tupel1)

#zum

Testen

des

unterschiedlichen

Verhaltens

auskommentieren

tupel2[2].append("foo")

print

tupel1

print

tupel2

Die

beid

enTu

pels

ind

nun

also

eige

nstä

ndig

eK

opie

nin

klus

ive

dere

ntha

ltene

nL

iste

,wie

uns

die

Prog

ram

mau

sgab

ebe

wei

st:

Aus

gabe

userlocalhost:$̃./kopieren2.py

(1,

2,

[3,

4],

5)

(1,

2,

[3,

4,

'foo'],

5)

Das

Bei

spie

lzei

gtau

chno

chm

al,d

ass

zwar

Tupe

lunv

erän

derl

ich

sind

,abe

ren

thal

tene

verä

nder

liche

Dat

enty

pen

glei

chw

ohla

uch

verä

nder

lich

blei

ben.

Die

Prob

lem

atik

des

Kop

iere

nsis

tals

oni

chta

ufve

ränd

erlic

heD

aten

type

nbe

schr

änkt

.

Page 74: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.11

Kon

vert

ieru

ng

Wie

wir

inde

rEin

führ

ung

scho

nfe

stge

stel

ltha

ben,

kann

man

eini

geD

aten

ty-

pen

inei

nand

erum

wan

deln

.Aus

eine

mSt

ring

kann

zum

Bei

spie

lein

eZ

ahl

wer

den,

wen

nde

rSt

ring

nur

Ziff

ern

enth

ält.

And

ernf

alls

wir

dei

neFe

hler

-m

eldu

ngbe

imV

ersu

chde

rKon

vert

ieru

ngau

sgeg

eben

.Die

folg

ende

Tabe

lleen

thäl

tein

ige

Kon

vert

ieru

ngsf

unkt

ione

n:

Funk

tion

Kon

vert

iert

von

Kon

vert

iert

nach

Bei

spie

l

int(

)St

ring

,floa

tga

nze

Zah

lin

t("3

3")

float

()St

ring

,int

Flie

ßkom

ma-

zahl

float

(1)

unic

ode(

)St

ring

,Zah

lU

nico

deSt

ring

unic

ode(

3.14

)or

d()

Zei

chen

ganz

eZ

ahl

ord(

'A')

Page 75: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.12

Type

nabf

rage

Den

Typ

eine

rVar

iabl

enka

nnm

anm

itH

ilfe

derF

unkt

iontype()

abfr

agen

:

#!/usr/bin/python

print

type(3)

print

type('a')

print

type(u"Hallo,

Welt")

print

type(("Hallo",

"Welt"))

print

type(["Hallo",

"Welt"])

print

type({"Hallo"

:1,

"Welt"

:2})

Aus

gabe

userlocalhost:$̃./typenabfrage1.py

<type

'int'>

<type

'str'>

<type

'unicode'>

<type

'tuple'>

Page 76: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

<type

'list'>

<type

'dict'>

3.13

Kon

stan

ten

Kon

stan

ten

inPy

thon

sind

nich

tsal

ssp

ezie

lleV

erei

nbar

unge

n.M

ansc

hrei

btsi

egr

oß,d

ann

wis

sen

alle

anei

nem

Prog

ram

mbe

teili

gten

Pers

onen

,das

sdi

esei

neK

onst

ante

ist.

Das

folg

ende

Bei

spie

lzei

gt,w

ieda

sge

ht:

#!/usr/bin/python

KONSTANTE

=3

print

"Meine

Konstante

ist:",

KONSTANTE

Page 77: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ein

eA

usga

beka

nnhi

eren

tfalle

n,da

sPr

ogra

mm

ists

chlic

htzu

triv

ial.

Die

seA

rtde

rte

xtue

llen

Ver

einb

arun

gw

ird

uns

noch

imK

apite

lRun

dum

OO

P9

bege

gnen

.E

ine

Kon

stan

teis

tal

soni

cht

ande

res

als

eine

Var

iabl

e,be

ide

rPr

ogra

mm

iere

rver

einb

aren

,sie

groß

zusc

hrei

ben

und

nach

derI

nitia

lisie

rung

nich

tmeh

rzu

ände

rn.D

iese

sis

tein

Teil

des

Pyt

hon

way

ofco

ding

,der

oftv

onw

enig

erSt

reng

eun

dFo

rmal

ism

usge

präg

tist

.

3.14

Zus

amm

enfa

ssun

g

Sie

habe

nje

tzte

inen

Übe

rblic

küb

erda

sTyp

ensy

stem

von

Pyth

on.V

omPr

inzi

phe

rbra

ucht

man

sich

über

den

Typ

mei

sten

ske

ine

Ged

anke

nm

ache

n,so

llte

jedo

chin

Spez

ialf

älle

nda

rübe

rBes

chei

dw

isse

n.E

iner

Var

iabl

enw

eist

man

Wer

tezu

und

scho

nst

ehtd

erTy

pfe

st.D

enTy

pei

nerV

aria

blen

kann

man

zur

Lau

fzei

tänd

ern

und

abfr

agen

.

9K

apite

l7au

fSei

te15

3

Page 78: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3.15

Anm

erku

ngen

Page 79: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 80: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

4K

ontr

olls

truk

ture

n

Bis

jetz

tsi

ndSi

ein

der

Lag

e,ei

nfac

hePr

ogra

mm

em

itE

in-

und

Aus

gabe

und

einf

ache

nB

erec

hnun

gen

zusc

hrei

ben.

Fürg

röße

rePr

ogra

mm

ew

ird

aber

die

Mög

lichk

eitb

enöt

igt,

Funk

tione

nnu

runt

erge

wis

sen

Bed

ingu

ngen

oder

meh

rfac

hdu

rchz

ufüh

ren.

Für

dies

enZ

wec

kgi

btes

die

Kon

trol

lstr

uktu

ren,

näm

lich

bedi

ngte

Aus

führ

ung

und

Schl

eife

n.

69

Page 81: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

4.1

if

Dieif

-Anw

eisu

ngis

tdie

einf

achs

teA

nwei

sung

,mit

derm

anab

häng

igvo

nei

nerB

edin

gung

eine

Akt

ion

ausl

ösen

kann

:

#!/usr/bin/python

a=

0if

a<

1:

print"a

ist

kleiner

als

1"

Aus

gabe

userlocalhost:$̃./if1.py

aist

kleiner

als

1

Hie

rwir

d,w

iein

den

erst

enSc

hritt

ener

läut

ert,

eine

Bes

onde

rhei

tvon

Pyth

onde

utlic

h,nä

mlic

hdi

eE

inrü

ckun

g.A

llegl

eich

eing

erüc

kten

Cod

ezei

len

gehö

-re

nzu

mse

lben

Blo

ck.A

lsE

inrü

ckun

gsze

iche

nka

nnm

anTa

bula

tore

nun

d

Page 82: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Lee

rzei

chen

verw

ende

n,w

obei

man

niem

als

mis

chen

sollt

e.V

erw

ende

nSi

evi

erL

eerz

eich

en,w

enn

Sie

konf

orm

zum

Stan

dard

sein

wol

len.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

a=

0if

a<

1:

print"a

ist

kleiner

als

1"

print"Dies

gehört

auch

noch

zum

Block"

print

"Dies

gehört

nicht

mehr

zur

IF-Anweisung"

Aus

gabe

userlocalhost:$̃./if2.py

aist

kleiner

als

1

Dies

gehört

auch

noch

zum

Block

Dies

gehört

nicht

mehr

zur

IF-Anweisung

Selb

stve

rstä

ndlic

hkö

nnen

Bed

ingu

ngin

derif

-Anw

eisu

ngau

chzu

sam

men

-ge

setz

twer

den:

Page 83: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

print

"Bitte

geben

Sie

eine

Zahl

ein:",

zahl

=int(raw_input())

if

zahl

>0

and

zahl

%2

==

0:

print"Gerade

Zahl."

if(90

<=

zahl

<=

100)

or

zahl

==

50:

print"Zahl

ist

zwischen

90

und

100

(inklusive),

oder

die

Zahl

ist

50"

Aus

gabe

userlocalhost:$̃./if3.py

Bitte

geben

Sie

eine

Zahl

ein:

22

Gerade

Zahl.

Zus

amm

enge

setz

teA

nwei

sung

enm

üsse

nna

chlo

gisc

hen

Reg

eln

gekl

amm

ert

wer

den,

die

Ein

rück

ung

mus

san

gepa

sstw

erde

n.

Page 84: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Det

ails

Ein

ige

Aus

drüc

kew

erde

nau

tom

atis

chzufalse

ausg

ewer

tet,

ohne

dass

wir

extr

ada

rauf

test

enm

üsse

n.D

ies

betr

ifft:

•da

s"N

icht

s-O

bjek

t"None

•di

eK

onst

anteFalse

•di

eN

ullw

erte

alle

rnum

mer

isch

enTy

pen,

also

z.B

.0,0

L,0

.0,0

j•

den

leer

enSt

ring

•da

sle

ere

Tupe

l()

•di

ele

ere

Lis

te[]

•da

sle

ere

Dic

tiona

ry{}

•di

ele

eren

Men

gen

set(

)und

froz

ense

t()E

ntsp

rech

end

wer

den

Var

iabl

en"m

itIn

halt"

zutrue

ausg

ewer

tet.

Page 85: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

4.2

if-el

if-el

se

Ent

sche

idun

gen

sind

oftg

eprä

gtvo

nm

ehre

ren

Wah

lmög

lichk

eite

n,di

em

anal

lesa

mta

bfan

gen

kann

.Mit

eine

rein

fach

enFa

llunt

ersc

heid

ung

wol

len

wir

begi

nnen

:

#!/usr/bin/python

print

"Bitte

geben

Sie

eine

Zahl

ein:",

a=

int(raw_input())

if

a%

2==

0:

print"%d

ist

gerade"

%a

else:

print"%d

ist

ungerade"

%a

Aus

gabe

userlocalhost:$̃./iee1.py

Bitte

geben

Sie

eine

Zahl

ein:

12

12

ist

gerade

Page 86: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Das

Schl

üsse

lwor

telse

leite

tden

Cod

eblo

ckei

n,w

elch

erA

usge

führ

twir

d,w

enn

die

Bed

ingu

ngin

derif

-Anw

eisu

ngni

chtz

utri

fft.

Wäh

ltm

annu

nau

svi

elen

vers

chie

dene

nD

inge

nau

s,w

iebe

iein

erM

ahlz

eit

imR

esta

uran

t,ko

mm

tman

mit

dies

erre

chtt

rivia

len

Fallu

nter

sche

idun

gni

cht

wei

ter,

esse

iden

n,m

ansc

hach

telt

sie.

Pyth

onbi

etet

mitelif

eine

wei

tere

Mög

lichk

eita

n:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

print

"Menü

ala

Carte:"

print

"1

für

Suppe"

print

"2

für

Hähnchenschnitzel

mit

Pommes"

print

"3

Ich

möchte

nun

zahlen"

print

"Ihre

Auswahl>",

auswahl

=int(raw_input())

if

auswahl

==

1:

print"Bitte

sehr,

Ihre

Suppe"

elif

auswahl

==

2:

print"Hähnchenschnitzel

mit

Pommes...

bitte

sehr."

Page 87: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

elif

auswahl

==

3:

print"Ihre

Rechnung

kommt

sofort"

else:

print"Das

ist

aber

keine

gute

Wahl!"

Aus

gabe

userlocalhost:$̃./iee2.py

Menü

ala

Carte:

1für

Suppe

2für

Hähnchenschnitzel

mit

Pommes

3Ich

möchte

nun

zahlen

Ihre

Auswahl>

2

Hähnchenschnitzel

mit

Pommes...

bitte

sehr.

elif

istd

ieK

urzs

chre

ibw

eise

von

else

if.D

iean

gehä

ngteelse

-Anw

eisu

ngw

ird

nurd

ann

ausg

efüh

rt,w

enn

kein

evo

rher

ige

Bed

ingu

ngzu

triff

t.

Page 88: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

4.3

if--

ganz

kurz

Es

gibt

eine

einz

eilig

eV

aria

nte

deri

f-el

se-K

ontr

olls

truk

tur.

Die

Synt

axis

tge-

dach

tfür

Fälle

,in

dene

nin

beid

enEn

tsch

eidu

ngsz

wei

gen

ders

elbe

nVa

riabl

enet

was

zuge

wie

sen

wer

den

soll,

wie

folg

t:

#!/usr/bin/python

a=

22

text

=""

if

a%

2==

0:

text

="gerade"

else: text

="ungerade"

print

text

Die

Synt

axde

rKur

zsch

reib

wei

se1

ista

nder

sal

sge

woh

nt,d

ieA

bfra

gew

irdso

zusa

gen

inde

rMitt

evo

rgen

omm

en:

1D

iese

Not

atio

nis

tei

nzig

artig

und

insb

eson

dere

vers

chie

den

von

dem

inde

rPr

ogra

mm

iers

prac

heC

ˆ{http://de.wikipedia.org/wiki/C_

Page 90: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

a=

22

text

=("gerade",

"ungerade")[a

%2]

print

text

4.4

Verg

leic

hsop

erat

oren

inde

bers

icht

Die

folg

ende

Tabe

lleze

igtd

ievo

nPy

thon

unte

rstü

tzte

nV

ergl

eich

sope

rato

ren.

Ope

rato

rB

esch

reib

ung

Bei

spie

lB

eisp

iela

usga

-be

==Te

stet

aufW

erte

-G

leic

hhei

t

"Hal

lo"

=="W

elt"

Fals

e

Page 91: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ope

rato

rB

esch

reib

ung

Bei

spie

lB

eisp

iela

usga

-be

!=Te

stet

aufW

erte

-U

ngle

ichh

eit

"Hal

lo"

!="W

elt"

True

isTe

stet

auf

Obj

ekt-

Gle

ichh

eit

type

("H

allo

")is

str

True

isno

tTe

stet

auf

Obj

ekt-

Ung

leic

hhei

t

type

("H

allo

")is

noti

ntTr

ue

<Te

stet

aufk

lei-

nere

nW

ert

4<

4Fa

lse

<=Te

stet

aufk

lei-

nere

nod

ergl

ei-

chen

Wer

t

4<=

4Tr

ue

Page 92: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ope

rato

rB

esch

reib

ung

Bei

spie

lB

eisp

iela

usga

-be

>Te

stet

aufg

rö-

ßere

nW

ert

"b"

>"a

"Tr

ue

>=Te

stet

aufg

rö-

ßere

nod

ergl

ei-

chen

Wer

t

5.9

>=6

Fals

e

Die

seVe

rgle

ichs

oper

ator

enkö

nnen

Sie

mit

Hilf

ede

rlog

isch

enO

pera

tore

nau

sde

mK

apite

lDat

enty

pen,

Boo

lean

2m

itein

ande

rver

knüp

fen,

umko

mpl

exer

eA

usdr

ücke

zufo

rmen

.

Möc

hte

man

eine

Varia

ble

dara

ufte

sten

,ob

sie

inne

rhal

bei

nes

Inte

rval

les

liegt

,ka

nnm

andi

esau

fein

fach

eW

eise

hins

chre

iben

:

#!/usr

bin/python

#-*-

coding:

utf-8

-*-

2K

apite

l3.1

aufS

eite

26

Page 93: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

x=

4

if

10

>x

>=

2:

print"x

ist

kleiner

als

10

und

größer/gleich

2"

Aus

gabe

userlocalhost:$̃./ifdoppelt.py

xist

kleiner

als

10

und

größer/gleich

2

Die

seSy

ntax

iste

ine

Kur

zsch

reib

wei

sevo

nifx<10andx>=2

.

4.5

for-

Schl

eife

for

-Sch

leif

endi

enen

dazu

,ei

nen

Cod

eblo

ckei

nebe

stim

mte

Anz

ahl

mal

wie

derh

olen

zula

ssen

,wob

eidi

ese

Anz

ahlz

ube

ginn

der

Schl

eife

fest

steh

t.H

ierb

eiw

ird

über

Sequ

enze

nite

rier

t,es

wer

den

kein

eV

aria

blen

hoch

gezä

hlt.

Die

Sequ

enz,

über

die

iteri

ertw

ird,

darf

sich

nich

tzur

Lau

fzei

tänd

ern.

Page 94: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

for

person

in

["Herr

Müller",

"Frau

Meier",

"Tina

Schulze"]:

printperson,

"lernt

Python!"

Aus

gabe

userlocalhost:$̃./for1.py

Herr

Müller

lernt

Python!

Frau

Meier

lernt

Python!

Tina

Schulze

lernt

Python!

Die

Sequ

enz

isth

iere

ine

Lis

te,e

skö

nnte

aber

auch

ein

Tupe

lode

rein

Stri

ngse

in.

Man

chm

alm

öcht

em

anei

nen

Inde

xm

itlau

fen

lass

en,

der

die

Num

-m

erei

nes

Ein

trag

esde

rSe

quen

zan

gibt

.Die

ser

mög

licht

uns

die

Funk

tion

enumerate()

:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

Page 95: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

for

nummer,

person

in

enumerate(["Herr

Müller",

"Frau

Meier",

"Tina

Schulze"]):

print"%s

lernt

als

%d.

Person

Python!"

%(person,

nummer

+1)

Aus

gabe

userlocalhost:$̃./for2.py

Herr

Müller

lernt

als

1.

Person

Python!

Frau

Meier

lernt

als

2.

Person

Python!

Tina

Schulze

lernt

als

3.

Person

Python!

enumerate()

liefe

rtde

nIn

dex

wie

auch

den

Ein

trag

beij

edem

Schl

eife

n-du

rchl

auf.

Da

wir

die

Pers

onen

von

1du

rchz

ähle

nw

olle

n,de

rInd

exje

doch

bei0

begi

nnt,

habe

nw

irdi

eA

usga

beet

was

ange

pass

t.

Selb

stve

rstä

ndlic

hfu

nktio

nier

enSc

hlei

fen

auch

mit

der

scho

nbe

kann

-te

nFu

nktio

nrange()

.E

ine

Var

iant

edi

eser

Funk

tion

nenn

tsi

chxrange(Von,Bis,Step)

,wob

eidi

eA

rgum

enteVon

undStep

optio

-na

lsin

d.D

erVo

rteil

dies

erFu

nktio

nlie

gtda

rin,d

ass

ein

solc

herW

erte

bere

ich

nich

tals

Lis

teim

Spei

cher

ange

legt

wer

den

mus

s,Si

ekö

nnen

also

belie

big

Page 96: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

groß

eW

erte

verw

ende

noh

neN

acht

eile

imSp

eich

erve

rbra

uch

befü

rcht

enzu

müs

sen:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

for

zahl

in

xrange(0,

10,

2):

printzahl,

"ist

eine

gerade

Zahl"

Aus

gabe

userlocalhost:$̃./for3.py

0ist

eine

gerade

Zahl

2ist

eine

gerade

Zahl

4ist

eine

gerade

Zahl

6ist

eine

gerade

Zahl

8ist

eine

gerade

Zahl

Mit

Hilf

ede

rfor

-Sch

leif

eun

dei

nem

Dic

tiona

ryka

nnm

andi

eH

äufig

keit

von

Zei

chen

eine

rEin

gabe

erm

ittel

n:

Page 97: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

#Texteingabe

text

=raw_input("Bitte

geben

Sie

einen

Text

ein:

")

ergebnis

={}

#Anzahl

der

jeweiligen

Zeichen

bestimmen

for

zeichen

in

text:

ergebnis[zeichen]

=ergebnis.get(zeichen,

0)

+1

#Anzahl

der

Zeichen

insgesamt

anzahl_zeichen

=len(text)

print

"Es

wurden",

anzahl_zeichen,

"Zeichen

eingegeben,

davon

sind",

#Anzahl

verschiedener

Zeichen

anzahl

=len(ergebnis)

print

anzahl,

"verschieden."

#Statistik

der

Zeichen

ausdrucken

for

key

in

ergebnis.keys():

haeufigkeit

=float(ergebnis[key])

/anzahl_zeichen*

100.0

print"Das

Zeichen

'%s'

kam

%d

mal

vor.

Häufigkeit:

%4.1f%%"

%\

(key,

ergebnis[key],

haeufigkeit)

Page 98: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./for4.py

Bitte

geben

Sie

einen

Text

ein:

Hallo,Welt

Es

wurden

11

Zeichen

eingegeben,

davon

sind

9verschieden.

Das

Zeichen

'a'

kam

1mal

vor.

Häufigkeit:

9.1%

Das

Zeichen

''

kam

1mal

vor.

Häufigkeit:

9.1%

Das

Zeichen

'e'

kam

1mal

vor.

Häufigkeit:

9.1%

Das

Zeichen

'H'

kam

1mal

vor.

Häufigkeit:

9.1%

Das

Zeichen

'l'

kam

3mal

vor.

Häufigkeit:

27.3%

Das

Zeichen

'o'

kam

1mal

vor.

Häufigkeit:

9.1%

Das

Zeichen

','

kam

1mal

vor.

Häufigkeit:

9.1%

Das

Zeichen

't'

kam

1mal

vor.

Häufigkeit:

9.1%

Das

Zeichen

'W'

kam

1mal

vor.

Häufigkeit:

9.1%

ergebnis

defin

iere

nw

iral

sei

nan

fang

sle

eres

Dic

tiona

ry.A

nsch

ließe

ndbe

stim

men

wir,

wie

ofte

inbe

stim

mte

sZ

eich

enei

ngeg

eben

wur

de.H

ierz

ube

dien

enw

irun

sde

rM

etho

deget()

,wel

che

uns

entw

eder

die

bish

erig

eA

nzah

lein

esei

ngeg

eben

enZ

eich

ens

ausg

ibto

der0

als

vore

inge

stel

lten

Wer

t,

Page 99: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

wen

nda

sZ

eich

enbi

sher

nich

tvo

rkom

mt.

Die

Häu

figke

itei

nes

Zei

chen

sis

tdie

Anz

ahle

ines

best

imm

tes

Zei

chen

sge

teilt

durc

hdi

eG

esam

tzah

lder

Zei

chen

.Die

Form

atie

rung

derprint

-Aus

gabe

isth

ierb

eino

chun

gew

ohnt

.D

ieFo

rmat

anw

eisu

ng%4.1f

besa

gt,d

ass

wir

4St

elle

nde

rZah

lins

gesa

mt

ausg

eben

wol

len,

davo

nei

neN

achk

omm

aste

lle.D

asdo

ppel

tePr

ozen

tzei

chen

hing

egen

bew

irkt

die

Aus

gabe

eine

sei

nzel

nen

Proz

entz

eich

ens.

4.6

whi

le-S

chle

ife

Istd

ieA

nzah

lder

Schl

eife

ndur

chlä

ufe

nich

tvon

vorn

eher

ein

fest

,so

biet

etsi

chei

newhile

-Sch

leif

ean

.Mit

dies

erlä

ssts

ich

das

obig

eR

esta

uran

t-B

eisp

iel

soum

schr

eibe

n,da

ssG

äste

best

elle

nkö

nnen

,bis

sie

satt

sind

:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

satt

=False

Page 100: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

rechnung

=0

while

not

satt:

print"Menü

ala

Carte:"

print"1

für

Suppe

(2

Euro)"

print"2

für

Hähnchenschnitzel

mit

Pommes

(4

Euro)"

print"3

Ich

möchte

nun

Zahlen"

print"Ihre

Auswahl>",

auswahl

=int(raw_input())

ifauswahl

==

1:

print"Bitte

sehr,

Ihre

Suppe"

rechnung

+=

2elifauswahl

==

2:

print"Hähnchenschnitzel

mit

Pommes...

bitte

sehr."

rechnung

+=

4elifauswahl

==

3:

print"Ihre

Rechnung

beträgt

%d

Euro"

%rechnung

satt

=True

else: print"Das

ist

aber

keine

gute

Wahl!"

Aus

gabe

userlocalhost:$̃./while1.py

Menü

ala

Carte:

Page 101: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

1für

Suppe

(2

Euro)

2für

Hähnchenschnitzel

mit

Pommes

(4

Euro)

3Ich

möchte

nun

Zahlen

Ihre

Auswahl>

1

Bitte

sehr,

Ihre

Suppe

Menü

ala

Carte:

1für

Suppe

(2

Euro)

2für

Hähnchenschnitzel

mit

Pommes

(4

Euro)

3Ich

möchte

nun

Zahlen

Ihre

Auswahl>

2

Hähnchenschnitzel

mit

Pommes...

bitte

sehr.

Menü

ala

Carte:

1für

Suppe

(2

Euro)

2für

Hähnchenschnitzel

mit

Pommes

(4

Euro)

3Ich

möchte

nun

Zahlen

Ihre

Auswahl>

3

Ihre

Rechnung

beträgt

6Euro

Page 102: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Selb

stve

rstä

ndlic

hkö

nnen

Sie

den

Schl

eife

nkop

fauf

die

glei

che

Wei

sew

ieif

-A

nwei

sung

enm

itB

edin

gung

enbe

stüc

ken.

Wic

htig

istn

ur,d

ass

die

Schl

eife

läuf

t,so

lang

edi

eB

edin

gung

imSc

hlei

fenk

opfz

uTrue

ausg

ewer

tetw

ird.

4.7

brea

kun

dco

ntin

ue

Die

beid

enSc

hlüs

selw

örte

rbreak

undcontinue

brec

hen

Schl

eife

nab

oder

führ

enan

den

Schl

eife

nkop

fzur

ück.

Sie

wer

den

üblic

herw

eise

beis

ehr

groß

enSc

hlei

fenk

örpe

rnei

nges

etzt

,wen

nan

eine

rSte

llede

utlic

hw

ird,

dass

die

aktu

elle

Itera

tion

entw

eder

die

letz

teis

tode

rder

Res

tdes

Schl

eife

nkör

pers

unnö

tigis

tund

über

spru

ngen

wer

den

soll.

Man

kann

jede

Schl

eife

,die

dies

eSc

hlüs

selw

örte

ren

thäl

tau

chso

umfo

rmul

iere

n,da

ssdi

ese

nich

tbe

nötig

tw

erde

n,je

doch

führ

tih

rm

aßvo

ller

Ein

satz

oft

zuei

nem

über

sich

tlich

eren

Cod

e.

#!/usr/bin/python

Page 103: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

while

True:

antwort

=raw_input("Soll

ich

fortfahren?

(J/N)

")

ifantwort

in

('n',

'N'):

break

Aus

gabe

userlocalhost:$̃./break1.py

Soll

ich

fortfahren?

(J/N)

j

Soll

ich

fortfahren?

(J/N)

j

Soll

ich

fortfahren?

(J/N)

n

Hie

rwir

dde

rSch

leif

enkö

rper

min

dest

ens

einm

alau

sgef

ührt

.Man

spri

chti

ndi

esem

Zusa

mm

enha

ngvo

nei

nern

icht

-abw

eise

nden

Schl

eife

,da

die

Abb

ruch

-be

ding

ung

amSc

hlei

fene

nde3

erfo

lgt.break

kann

aber

selb

stve

rstä

ndlic

hau

chan

jede

rand

eren

Stel

lein

nerh

alb

des

Schl

eife

nkör

pers

steh

en.

#!/usr/bin/python

3In

C/C

++/J

ava

istd

ies

anal

ogzu

eine

rdo.

..whi

le(b

edin

gung

)-Sc

hlei

fe

Page 104: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

for

buchstabe,

zahl

in

[('a',

1),

('b',

2),

(3,

3),

('d',

4)]:

iftype(buchstabe)

is

not

str:

continue

else: print"Der

Buchstabe",

buchstabe,

"hat

den

Zahlenwert",

zahl

Aus

gabe

userlocalhost:$̃./continue1.py

Der

Buchstabe

ahat

den

Zahlenwert

1

Der

Buchstabe

bhat

den

Zahlenwert

2

Der

Buchstabe

dhat

den

Zahlenwert

4

Das

Tupe

l (3,3)

soll

hier

nich

taus

gege

ben

wer

den.

Der

Ver

glei

chau

fTy-

peng

leic

hhei

tfüh

rtda

zu,d

ass

nurZ

eich

enke

tten

und

dere

nW

erte

ausg

egeb

enw

erde

n.continue

führ

thie

rwie

derz

urüc

kan

den

Schl

eife

nanf

ang,

wen

nda

ser

ste

Tupe

lele

men

tkei

neZ

eich

enke

tteis

t.

Page 105: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

4.8

Schl

eife

n-E

lse

Schl

eife

nkö

nnen

,wie

Ver

zwei

gung

enau

ch,e

inelse

enth

alte

n.D

iese

sw

ird

beifor

-Sch

leif

enau

sgef

ührt

,wen

nke

ine

wei

tere

nIt

erat

ione

nm

ehrd

urch

ge-

führ

twer

den

könn

en,b

eisp

iels

wei

sew

eild

iezu

iterie

rend

enLi

ste

abge

arbe

itet

ist.

Beiwhile

-Sch

leif

enw

ird

derelse

-Blo

ckau

sgef

ührt

,wen

ndi

eSc

hlei

-fe

nbed

ingu

ngzuFalse

ausg

ewer

tetw

ird.break

führ

tbei

Schl

eife

nni

cht(!

)zu

eine

berg

ang

inde

nelse

-Blo

ck.F

olge

ndes

Bei

spie

lzei

gtei

nen

Ein

-sa

tzzw

eck

vonelse

beie

iner

-Sch

leif

e:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

#user-UID-dict

users

={'anne'

:500,

'paul'

:501,

'martina'

:502}

print

"Sucht

nach

einem

Benutzernamen

zu

einer

angegebenen

UID."

uid

=int(raw_input('Bitte

geben

Sie

die

UID

ein:

'))

Page 106: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

for

name

in

users.keys():

ifuid

==

users[name]:

print"Die

UID",

uid,

"gehört

zu

",

name

break

else: print"Tut

mir

leid,

es

wurde

kein

passender

Benutzername

zu

dieser

UID

gefunden."

Aus

gabe

userlocalhost:$̃./forelse1.py

Sucht

nach

einem

Benutzernamen

zu

einer

angegebenen

UID.

Bitte

geben

Sie

die

UID

ein:

501

Die

UID

501

gehört

zu

paul

...weiterer

Aufruf...

Bitte

geben

Sie

die

UID

ein:

1000

Tut

mir

leid,

es

wurde

kein

passender

Benutzername

zu

dieser

UID

gefunden.

Page 107: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Das

Prog

ram

msu

cht

nach

eine

mU

ser,

dess

enU

ser-

IDan

gege

ben

wur

de.

Find

etes

dies

en,s

ogi

btes

den

Nam

enau

s.Fa

llses

kein

enB

enut

zerm

itdi

eser

Use

r-Id

gibt

,so

wir

dde

relse

-Blo

ckau

sgef

ührt

.

Das

folg

ende

Prog

ram

mgi

btde

nH

exdu

mp

eine

rE

inga

beau

s.E

ine

leer

eEi

ngab

ebe

ende

tdas

Prog

ram

mpe

rbreak

,das

Wor

tEnde

hing

egen

nutz

tde

nelse

-Tei

lder

Schl

eife

:

#!/usr/bin/python

eingabe

=""

while

eingabe

!=

"Ende":

eingabe

=raw_input("Geben

Sie

etwas

ein:

")

ifeingabe

==

"":

break

else: forc

in

eingabe:

print

hex(ord(c)),

print

else: print"Das

war

es,

vielen

Dank"

Page 108: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./whileelse1.py

Geben

Sie

etwas

ein:

Test

0x54

0x65

0x73

0x74

Geben

Sie

etwas

ein:

Ende

0x45

0x6e

0x64

0x65

Das

war

es,

vielen

Dank

4.9

Try-

Exc

ept

ImZ

usam

men

hang

mit

Kon

vert

ieru

ngen

iste

sun

ssc

hon

beid

ener

sten

Pro-

gram

men

aufg

efal

len,

daß

mal

etw

assc

hief

gehe

nka

nn.D

erN

utze

rei

nes

Prog

ram

mes

soll

eine

Zah

lein

gebe

n,gi

btab

erst

attd

esse

nse

inen

Nam

enei

n.Sc

hon

bric

htPy

thon

die

Ver

arbe

itung

ab:

#!/usr/bin/python

Page 109: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

x=

int(raw_input("Bitte

geben

Sie

eine

Zahl

ein:

"))

print

x

Aus

gabe

userlocalhost:$̃./except1.py

Bitte

geben

Sie

eine

Zahl

ein:

Zehn

Traceback

(most

recent

call

last):

File

"./except1.py",

line

3,

in

<module>

x=

int(raw_input("Bitte

geben

Sie

eine

Zahl

ein:

"))

ValueError:

invalid

literal

for

int()

with

base

10:

'Zehn'

Pyth

onke

nnth

iere

ine

Mög

lichk

eit,

eine

nC

odeb

lock

prob

ewei

seau

szuf

ühre

nun

dzu

scha

uen,

obdi

eA

barb

eitu

nger

folg

reic

his

t.Is

tsie

esni

cht,

wir

dei

neso

gena

nnte

Exc

eptio

nau

sgel

öst,

die

Bea

rbei

tung

des

Cod

eblo

ckes

wir

dab

-ge

broc

hen

und

zuei

nerS

telle

imC

ode

gesp

rung

en,d

iedi

esen

Fehl

erab

fäng

t:

#!/usr/bin/python

try:x

=int(raw_input("Bitte

geben

Sie

eine

Zahl

ein:

"))

Page 110: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

printx

except:

print"Ein

Fehler

ist

aufgetreten,

macht

aber

nichts!"

print

"Hier

geht

es

weiter"

Aus

gabe

userlocalhost:$̃./except2.py

Bitte

geben

Sie

eine

Zahl

ein:

Zehn

Ein

Fehler

ist

aufgetreten,

macht

aber

nichts!

Hier

geht

es

weiter

Was

imm

ernu

nde

rNut

zere

ingi

bt,e

rbek

omm

tauf

jede

nFa

llei

neA

usga

be.

Die

Anw

eisu

ng,w

elch

edi

eZ

ahla

usge

ben

soll

wir

dje

doch

nur

ausg

efüh

rt,

wen

ndi

eK

onve

rtie

rung

erfo

lgre

ich

war

.War

sie

esni

cht,

wir

dde

rCod

eblo

ckun

terh

alb

vonexcept

abge

arbe

itet.

Inje

dem

Fall

wir

ddi

ele

tzteprint

-A

nwei

sung

ausg

efüh

rt.

Wir

dst

atte

iner

Zah

lein

Buc

hsta

beve

rsuc

hsw

eise

konv

ertie

rt,g

ibte

sei

nen

soge

nann

tenValueError

,den

Sie

gese

hen

habe

n,al

sSi

eda

ser

ste

Bei

-

Page 111: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

spie

ldi

eses

Abs

chni

ttsm

itB

uchs

tabe

ndat

enau

sgef

ührt

habe

n.ei

nige

der

Exc

eptio

nska

nnm

ange

ziel

tabf

ange

n,w

iefo

lgen

des

Bei

spie

ldem

onst

rier

t:

#!/usr/bin/python

try:x

=int(raw_input("Bitte

geben

Sie

eine

Zahl

ein:

"))

printx

except

ValueError:

print"Das

war

keine

Zahl!"

except:

print"Irgendein

anderer

Fehler"

Aus

gabe

userlocalhost:$̃./except3.py

Bitte

geben

Sie

eine

Zahl

ein:

Zehn

Das

war

keine

Zahl!

Geb

enSi

enu

nei

neB

uchs

tabe

nfol

geei

n,w

ird

der

Blo

ckun

terh

alb

exceptValueError

ausg

efüh

rt.U

mei

nen

ande

ren

Fehl

erzu

prov

ozie

-

Page 112: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ren,

gebe

nSi

eSTRG+C

ein,

esw

ird

dann

der

Blo

ckau

sgef

ührt

,der

die

allg

emei

neE

xcep

tion

bear

beite

t.

4.10

Try-

Fina

lly

Fürm

anch

esc

hwer

enFe

hler

reic

htexcept

nich

taus

,das

Prog

ram

mm

uss

abge

broc

hen

wer

den.

Indi

esem

Fall

erm

öglic

htun

sfinally

,noc

hle

tzte

Auf

räum

arbe

iten

durc

hzuf

ühre

n,w

iezu

mB

eisp

iele

ine

Dat

eizu

schl

ieße

nod

ersc

hlic

htei

nen

Gru

ndfü

rdas

Sche

itern

anzu

gebe

n:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

try:x

=1

/0

printx

finally:

print"Oh,

eine

Division

durch

Null!

Ich

räume

noch

eben

auf..."

print

"Hierhin

komme

ich

nicht

mehr!"

Page 113: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./finally1.py

Oh,

eine

Division

durch

Null!

Ich

räume

noch

eben

auf...

Traceback

(most

recent

call

last):

File

"./finally1.py",

line

5,

in

<module>

x=

1/

0

ZeroDivisionError:

integer

division

or

modulo

by

zero

Die

letz

teZe

ilede

sCod

esw

irdni

eer

reic

ht.N

ach

derD

ivis

ion

durc

hN

ullw

irdei

neE

xcep

tion

gew

orfe

n,di

eM

eldu

ngau

sgeg

eben

und

der

Prog

ram

mla

ufab

gebr

oche

n.finally

wird

imm

erau

sgef

ührt,

auch

dann

,wen

nke

inFe

hler

auft

rat.

Dar

auf

könn

enw

irun

sve

rlas

sen.

Seit

Pyth

on2.

5ka

nnm

antry

-except

undtry

-finally

gem

eins

amve

rwen

den,

wie

folg

ende

sB

eisp

iel

zeig

t:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

print

"Berechnet

die

Zahl

1/x

"

Page 114: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

wert

=0

try:x

=raw_input("Geben

Sie

eine

Zahl

ein:

");

wert

=1.0

/float(x)

except

ValueError:

print"Fehler:

Das

war

keine

Zahl"

except

KeyboardInterrupt:

print"Fehler:

Steuerung-C

gedrückt"

finally:

print"Danke

für

die

Zahl"

print

wert

Hie

rkön

nen

Sie

Fehl

erpr

oduz

iere

n,in

dem

Sie

STRG+C

,Buc

hsta

ben

oder

0ei

ngeb

en.I

nje

dem

Fall

wir

dde

rPro

gram

mte

ilabfinally

ausg

efüh

rt.

4.11

Ass

ert

Mitassert(Bedingung)

mac

hen

Sie

Zus

iche

rung

en,

die

imw

eite

ren

Ver

lauf

des

Prog

ram

mes

gelte

n.So

llten

dies

eZ

usic

heru

ngen

nich

ter

füllt

Page 115: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

sein

,die

Bed

ingu

ngal

sozuFalse

ausg

ewer

tetw

erde

n,w

ird

eine

Exc

eptio

nge

wor

fen

und

das

Prog

ram

mbr

icht

ab,w

iefo

lgen

des

Bei

spie

lzei

gt:

#!/usr/bin/python

text

=raw_input("Bitte

geben

Sie

Text

ein:

")

assert(text

!=

"")

print

text

Wen

nSi

ebe

imPr

ogra

mm

lauf

kein

eE

inga

bem

ache

n,so

nder

nnu

rm

itReturn

best

ätig

en,e

rhal

ten

Sie

folg

ende

Aus

gabe

:

Aus

gabe

userlocalhost:$̃./assert1.py

Bitte

geben

Sie

Text

ein:

Traceback

(most

recent

call

last):

File

"./a.py",

line

5,

in

<module>

assert(text

!=

"")

AssertionError

Page 116: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Hie

rwir

dei

neE

xcep

tion

gew

orfe

n,da

sPr

ogra

mm

bric

htab

.Sol

che

Zus

iche

-ru

ngen

baut

man

über

alld

orti

nPr

ogra

mm

eei

n,w

oes

unsi

nnig

wär

e,oh

nedi

ese

Zus

iche

rung

fort

zufa

hren

.

4.12

Zus

amm

enfa

ssun

g

Indi

esem

Kap

itelh

aben

Sie

gele

rnt,

wie

Sie

den

Abl

auf

von

Prog

ram

men

steu

ern

und

beei

nflus

sen

könn

en.S

teue

rung

smög

lichk

eite

nsi

ndda

sV

erzw

ei-

gen

und

wie

derh

olte

Aus

führ

envo

nPr

ogra

mm

teile

n.E

benf

alls

könn

enSi

enu

nFe

hler

abfa

ngen

und

notw

endi

geA

rbei

ten

kurz

vord

emun

verm

eidl

iche

nE

nde

ihre

sPr

ogra

mm

esdu

rchf

ühre

nla

ssen

.

4.13

Anm

erku

ngen

Page 117: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 118: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

5Fu

nktio

nen

Funk

tione

ngl

iede

rnde

nPr

ogra

mm

text

,ges

talte

nde

nC

ode

über

sich

tlich

und

ersp

aren

dem

Prog

ram

mie

rerw

ertv

olle

Ent

wic

klun

gsze

it.E

benf

alls

sind

sie

eine

sehr

gute

Schn

ittst

elle

,um

imTe

amge

mei

nsam

anA

ufga

ben

zuar

beite

n.

5.1

Funk

tione

n

Funk

tione

nw

erde

nw

iefo

lgtd

efini

ertu

ndau

fger

ufen

:

#!/usr/bin/python

107

Page 119: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def

HalloWelt():

print"Hallo,

Welt!"

HalloWelt()

HalloWelt()

Aus

gabe

userlocalhost:$̃./funk1.py

Hallo,

Welt!

Hallo,

Welt!

Dem

Schl

üsse

lwor

tdef

folg

tde

rFu

nktio

nsna

me.

Die

Anw

eisu

ngen

der

Funk

tion

folg

tal

sB

lock

.Fu

nktio

nen

könn

enPa

ram

eter

habe

nun

ddi

ese

nutz

en:

#!/usr/bin/python

def

HalloWelt(anzahl):

ifanzahl

>0:

fori

in

xrange(0,

anzahl):

Page 120: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"Hallo,

Welt!"

HalloWelt(3)

Aus

gabe

userlocalhost:$̃./funk2.py

Hallo,

Welt!

Hallo,

Welt!

Hallo,

Welt!

Ein

ede

rAuf

gabe

nvo

nFu

nktio

nen

iste

s,W

erte

zurü

ckzu

liefe

rn,w

obei

jede

rTy

pzu

rück

gege

ben

wer

den

kann

.Wir

besc

hrän

ken

uns

inde

nB

eisp

iele

nau

fZ

ahle

n:

#!/usr/bin/python

def

summe(a,

b,

c):

wert

=a

+b

+c

returnwert

print

summe(1,

7,

3)

Page 121: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./funk3.py

11 Etw

asnü

tzlic

heri

stda

sfo

lgen

deB

eisp

iel,

wel

ches

eine

Funk

tion

impl

emen

-tie

rt,d

ieau

sje

dem

über

gebe

nen

Stri

ngdi

eB

uchs

tabe

nsum

me

bild

et,w

obei

ein

Afü

r1st

eht,

Bfü

r2un

dso

fort.

Die

Sum

me

dies

erB

uchs

tabe

nwer

tew

irdvo

nfo

lgen

dem

Prog

ram

mer

mitt

elt,

wob

einu

rdi

eB

uchs

tabe

nA

-Zge

zähl

tw

erde

n:

#!/usr/bin/python

def

StringWert(s):

s=

s.upper()

summe

=0

forzeichen

in

s:

wert

=ord(zeichen)

-ord('A')

+1

ifwert

>0

and

wert

<=

26:

summe

+=

wert

returnsumme

Page 122: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

StringWert("ABBA")

print

StringWert("Hallo,

Welt!")

Aus

gabe

userlocalhost:$̃./funk4.py

6 108

Die

Met

hode

upper()

kenn

enSi

esc

hon,

sie

liefe

rtei

nen

Stri

ngzu

rück

,w

elch

ernu

raus

Gro

ßbuc

hsta

ben

best

eht.

Übe

rdie

sen

Stri

ngw

ird

iteri

ert.

Mit

ord()

erha

lten

wir

eine

nZ

ahle

nwer

tfü

rde

nak

tuel

len

Buc

hsta

ben.

Von

dies

emZ

ahle

nwer

tzi

ehen

wir

den

Zah

lenw

ert

des

erst

enB

uchs

tabe

ns(A

)ab

,und

daw

irni

chtv

on0,

sond

ern

von

1be

ginn

enw

olle

n,m

üsse

nw

irzu

rW

erte

bere

chnu

ngno

ch1

hinz

uad

dier

en.

Funk

tione

nka

nnm

anau

chin

eina

nder

scha

chte

ln,

wie

folg

ende

sB

eisp

iel

zeig

t:

#!/usr/bin/python

Page 123: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def

Hypothenuse(Kathete1,

Kathete2):

defQuadriere(x):

returnx

*x

defSummiere(a,

b):

return

a+

b

Hyp

=Summiere(Quadriere(Kathete1),

Quadriere(Kathete2))

returnHyp

print

"Das

Hypothenusenquadrat

lautet:",

Hypothenuse(1,

2)

Aus

gabe

userlocalhost:$̃./funk5.py

Das

Hypothenusenquadrat

lautet:

5

Auß

erha

lbde

rFu

nktio

nHypothenuse()

sind

die

Funk

tione

nQuadriere()

undSummiere()

unbe

kann

t.

Page 124: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

5.2

Funk

tions

doku

men

tatio

n

Funk

tione

nkö

nnen

und

sollt

endo

kum

entie

rtw

erde

n.Sc

hrei

btm

anm

itpa

ssen

-de

rEin

rück

ung

eine

nD

oc-S

trin

g,al

soei

nen

anon

ymen

meh

rzei

ligen

Stri

ng,

indi

eFu

nktio

n,so

kann

man

anan

dere

rSt

elle

auf

ihn

Bez

ugne

hmen

.Es

wer

den

fürj

edes

ange

legt

eO

bjek

tein

ige

Zus

atzi

nfor

mat

ione

nge

neri

ertu

ndab

gesp

eich

ert.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

def

Collatz(parm):

"""Bestimmt

das

nächste

Collatz-Folgeelement

vom

Parameter

parm.

Das

nächste

Folgeelement

ist

3*parm

+1,

wenn

parm

ungerade

ist,

sonst

parm/2

"""

ifparm

%2

!=

0:

return

3*parm

+1

else: return

parm

/2

printCollatz.__doc__

Page 125: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./fdoc1.py

Bestimmt

das

nächste

Collatz-Folgeelement

vom

Parameter

parm.

Das

nächste

Folgeelement

ist

3*parm

+1,

wenn

parm

ungerade

ist,

sonst

parm/2

Mit__doc__

wir

dau

fein

eau

tom

atis

cher

stel

lteun

dbe

legt

eV

aria

ble

zuge

-gr

iffen

.Die

seV

aria

ble

wir

der

zeug

t,w

enn

die

Funk

tion

ange

legt

wir

d.Fa

llske

ine

Dok

umen

tatio

nan

gege

ben

wur

de,e

nthä

lt__doc__

eine

nle

eren

Strin

g.

5.3

Para

met

er

Nac

hdem

wir

nun

die

Gru

ndla

gen

derF

unkt

ione

nbe

hand

etha

ben,

wol

len

wir

uns

deta

illie

rtm

itPa

ram

eter

nbe

schä

ftig

en.

Para

met

erka

nnm

anm

itW

erte

nvo

rbel

egen

:

Page 126: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

def

HalloWelt(anzahl

=3):

print

ifanzahl

>0:

fori

in

xrange(0,

anzahl):

print

"Hallo,

Welt!"

HalloWelt(1)

HalloWelt()

Aus

gabe

userlocalhost:$̃./param1.py

Hallo,

Welt!

Hallo,

Welt!

Hallo,

Welt!

Hallo,

Welt!

Page 127: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Man

gibt

hier

beii

nde

rPar

amet

erlis

teei

nen

vore

inge

stel

lten

Wer

tan,

den

man

beim

Funk

tions

aufr

ufau

chüb

ersc

hrei

ben

kann

.Hat

man

meh

rere

Para

me-

ter,

kann

man

einz

elne

von

ihne

nvo

rbel

egen

und

imko

nkre

ten

Auf

rufa

uch

vert

ausc

hen:

#!/usr/bin/python

def

summe(a

=3,

b=

2):

returna

+b

print

summe()

print

summe(a

=4)

print

summe(b

=4)

print

summe(b

=2,

a=

1)

Aus

gabe

userlocalhost:$̃./param2.py

5 6

Page 128: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

7 3 5.4

Vari

able

Para

met

er

Ger

ade

bei

Funk

tione

nw

iede

rSu

mm

enbe

rech

nung

ist

espr

aktis

ch,

eine

vari

able

Anz

ahla

nPa

ram

eter

nzu

habe

n.D

adur

chw

erde

nre

chtp

rakt

isch

eFu

nktio

nen

mög

lich,

und

das

schr

eibe

nne

uerF

unkt

ione

nfü

rjed

eA

nzah

lan

Para

met

ern

entf

ällt:

#!/usr/bin/python

def

summe(*list):

s=

0forelement

in

list:

s=

s+

element

returns

print

summe()

Page 129: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

summe(1)

print

summe(1,

2,

3,

4,

5,

6,

7,

8,

9)

Aus

gabe

userlocalhost:$̃./varparam1.py

0 1 45 Der

Para

met

er*list

isth

ierb

eiei

nTu

pel,

das

abhä

ngig

von

derA

nzah

lder

imA

ufru

fer

folg

ten

Arg

umen

teen

twed

erle

er(()

)is

t,od

erdi

eA

rgum

ente

(1)

und(1,2,3,4,5,6,7,8,9)

enth

ält.

Ans

chlie

ßend

brau

-ch

enw

irzu

rSum

men

bere

chnu

ngnu

rnoc

hüb

erdi

eses

Tupe

lzu

iteri

eren

.

Neb

ende

rTup

el-F

orm

varia

bler

Arg

umen

tegi

btes

noch

die

Dic

tiona

ry-F

orm

:

#!/usr/bin/python

def

ZeigeListe(**liste):

printliste

Page 130: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ZeigeListe(a1

=1,

a2

=2,

a3

=3)

ZeigeListe(Name

="Schmitz",

Vorname

="Elke",

Postleitzahl

=44444)

Aus

gabe

userlocalhost:$̃./varparam2.py

{'a1':

1,

'a3':

3,

'a2':

2}

{'Name':

'Schmitz',

'Vorname':

'Elke',

'Postleitzahl':

44444}

Hie

rwir

dle

digl

ich

ein

Dic

tiona

ryau

fgeb

aut,

wel

ches

jew

eils

aus

dem

Arg

u-m

ente

nwor

tund

-wer

tbes

teht

.

5.5

Glo

bale

und

loka

leVa

riab

len

Hab

enfu

nktio

nslo

kale

Var

iabl

ende

ngl

eich

enN

amen

wie

Var

iabl

en,

die

auße

rhal

bde

rFun

ktio

nde

finie

rtw

urde

n,so

wer

den

glob

aler

eV

aria

blen

wer

tew

eder

lese

ndno

chsc

hrei

bend

beim

Zug

riff

berü

hrt:

Page 131: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

wert

=42

print

wert

def

wertetest():

wert

=12

printwert

wertetest()

print

wert

Aus

gabe

userlocalhost:$̃./global1.py

42

12

42 Neu

eV

aria

blen

wer

den

solo

kale

sge

hter

zeug

t.H

atei

nene

ueV

aria

ble

inne

r-ha

lbei

nerF

unkt

ion

den

glei

chen

Nam

enw

ieei

nean

dere

Var

iabl

eau

ßerh

alb,

sow

ird

nurd

iein

nere

Var

iabl

ege

nutz

t.

Page 132: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Möc

hte

man

esan

ders

habe

n,m

uss

man

expl

izit

den

Zug

riff

aufd

iegl

obal

eV

aria

ble

anfo

rder

n:

#!/usr/bin/python

wert

=42

print

wert

def

wertetest():

globalwert

wert

=12

printwert

wertetest()

print

wert

Aus

gabe

userlocalhost:$̃./global2.py

42

12

12

Page 133: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Das

Schl

üsse

lwor

tglobal

sorg

thie

rfür

den

Zug

riff

aufd

ieau

ßerh

alb

der

Funk

tion

defin

iert

egl

obal

eV

aria

ble.

Bitt

ebe

acht

enSi

e,da

ssZ

ugri

ffe

auf

glob

ale

Var

iabl

endi

eL

esba

rkei

tdes

Cod

esve

rmin

dern

.

5.6

Funk

tione

nau

fWer

tem

enge

n

Hat

man

eine

Funk

tion

gesc

hrie

ben,

die

ein

einz

elne

sA

rgum

entv

erar

beite

tun

dm

öcht

edi

ese

Funk

tion

nun

aufe

ine

ganz

eL

iste

von

Wer

ten

anw

ende

n,so

biet

etsi

chdi

eFu

nktio

nmap

an.D

iese

nim

mte

inFu

nktio

nsar

gum

entw

ieau

chei

neLi

ste

auf,

wen

detd

ieFu

nktio

nau

fjed

esEl

emen

tdie

serL

iste

anun

dgi

btei

neL

iste

als

Erg

ebni

szu

rück

.Fol

gend

esB

eisp

ielv

erde

utlic

htdi

es:

#!/usr/bin/python

def

quadriere(x):

returnx*x

Page 134: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

quadratzahlen

=map(quadriere,

[1,

2,

3,

4,

5,

6])

print

quadratzahlen

Aus

gabe

userlocalhost:$̃./map1.py

[1,

4,

9,

16,

25,

36]

Die

Funk

tionquadriere()

bere

chne

tfür

jede

sE

lem

entd

erL

iste

von

1bi

s6

die

Qua

drat

zahl

und

gibt

eine

Lis

tem

itQ

uadr

atza

hlen

zurü

ck.S

elbs

t-ve

rstä

ndlic

hka

nndi

eses

konk

rete

Prob

lem

auch

mit

Hilf

eei

nerfor

-Sch

leif

ege

löst

wer

den,

was

man

benu

tzti

stm

eist

meh

rein

eG

esch

mac

ksfr

age.

5.7

lam

bda

Ein

em

itlambda

erze

ugte

Funk

tion

ista

nony

m,s

ieha

tkei

nen

Nam

enun

dw

ird

nuri

nei

nem

best

imm

ten

Kon

text

genu

tzt,

wie

zum

Bei

spie

lmitmap

:

Page 135: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

quadratzahlen

=map(lambdax:

x*x,

[1,

2,

3,

4,

5,

6])

print

quadratzahlen

Aus

gabe

userlocalhost:$̃./lambda1.py

[1,

4,

9,

16,

25,

36]

Nac

hde

mSc

hlüs

selw

ortlambda

folg

tbi

szu

mD

oppe

lpun

ktei

nedu

rch

Kom

mat

age

tren

nte

Auf

zähl

ung

von

Arg

umen

ten,

hint

erde

mD

oppe

lpun

ktbe

ginn

tdi

eA

nwei

sung

.lambda

-Fun

ktio

nen

lass

ensi

chau

chnu

tzen

,um

wäh

rend

des

Prog

ram

mla

ufes

neue

Funk

tione

nzu

erze

ugen

.Das

folg

ende

Bei

spie

ldem

onst

riert,

wie

eine

Qua

drat

-und

eine

Wur

zelfu

nktio

nne

uer

zeug

tw

erde

n:

#!/usr/bin/python

def

Exponential(z):

return

lambda

x:

x**z

Page 136: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

quadriere

=Exponential(2)

wurzel

=Exponential(0.5)

a=

quadriere(2)

print

ab

=wurzel(a)

print

b

Aus

gabe

userlocalhost:$̃./lambda2.py

4 2.0

Die

Funk

tionExponential()

erw

arte

tei

nA

rgum

ent,

mit

dem

die

lambda

-Fun

ktio

ner

zeug

twir

d.D

ieFu

nktio

ngi

btni

chte

twa

den

Wer

tdie

-se

rne

uen

Funk

tion

zurü

ck,

sond

ern

die

neue

Funk

tion

selb

st.

Soer

zeug

tquadriere=Exponential(2)

eine

neue

Qua

drat

funk

tion,

die

man

auch

sogl

eich

anw

ende

nka

nn.

Page 137: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

5.8

Lis

ten

erze

ugen

sich

selb

st

Wo

wir

gera

deda

beiw

aren

,mitmap()

Lis

ten

zuer

zeug

en,w

ird

viel

leic

htau

chfo

lgen

deSy

ntax

1et

was

fürS

iese

in.L

ehne

nSi

esi

chzu

rück

und

geni

eßen

Sie

die

ungl

aubl

iche

Vors

tellu

ng,w

ieei

neL

iste

sich

selb

ster

zeug

t:

#!/usr/bin/python

liste

=[x

*xfor

xin

xrange(1,

10)]

print

liste

Aus

gabe

userlocalhost:$̃./comprehension1.py

[1,

4,

9,

16,

25,

36,

49,

64,

81]

Die

seLi

ste

wird

aufg

ebau

t,in

dem

alle

Wer

te,d

iexrange()

liefe

rt,qu

adrie

rtw

erde

n.W

irha

ben

eshi

eral

sow

iede

rmit

eine

rLis

tevo

nQ

uadr

atza

hlen

zutu

n.A

nder

sal

sbe

iderfor

-Sch

leif

est

ehth

ierd

erFu

nktio

nskö

rper

vord

em

1D

iese

Synt

axne

nntm

an"

Lis

tCom

preh

ensi

on"

Page 138: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Schl

eife

nite

rato

r.D

iese

Cod

eis

tabe

rnoc

hni

chta

lles,

was

wir

Ihne

nbi

eten

könn

en:

#!/usr/bin/python

liste

=[x

*xfor

xin

xrange(1,

10)ifx

%2

==

0]

print

liste

Aus

gabe

userlocalhost:$̃./comprehension2.py

[4,

16,

36,

64]

Nun

habe

nw

ires

mit

eine

rL

iste

von

Qua

drat

zahl

enzu

tun,

die

aus

der

Men

gede

rger

aden

Zahl

enge

bild

etw

urde

n.D

asin

derL

iste

nach

gest

ellte

if

sorg

thie

rfür

eine

Aus

wah

lder

Wer

te,d

iein

die

Vors

chri

ftzu

rLis

tenb

ildun

güb

erno

mm

enw

erde

n.

Um

alle

3er-

Tupe

lei

ner

Lis

teau

szug

eben

,al

soal

leK

ombi

natio

nen

eine

r3-

Ele

men

tigen

Lis

teau

fzuz

ähle

n,di

entf

olge

ndes

Prog

ram

m:

Page 139: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

Liste

=['1',

'2',

'+']

Kreuz

=[(a,

b,

c)

fora

in

Liste

forb

in

Liste

forc

in

Liste]

print

Kreuz

Aus

gabe

userlocalhost:$̃./comprehension3.py

[('1',

'1',

'1'),

('1',

'1',

'2'),

('1',

'1',

'+'),

('1',

'2',

'1'),

('1',

'2',

'2'),

('1',

'2',

'+'),

('1',

'+',

'1'),

('1',

'+',

'2'),

('1',

'+',

'+'),

('2',

'1',

'1'),

('2',

'1',

'2'),

('2',

'1',

'+'),

('2',

'2',

'1'),

('2',

'2',

'2'),

('2',

'2',

'+'),

('2',

'+',

'1'),

('2',

'+',

'2'),

('2',

'+',

'+'),

('+',

'1',

'1'),

('+',

'1',

'2'),

('+',

'1',

'+'),

('+',

'2',

'1'),

('+',

'2',

'2'),

('+',

'2',

'+'),

('+',

'+',

'1'),

('+',

'+',

'2'),

('+',

'+',

'+')]

Wie

wir

sehe

n,kö

nnen

wir

Lis

ten

aus

Tupe

laus

ande

ren

Lis

ten

erze

ugen

.

Solc

heL

iste

nkö

nnen

auch

mit

derF

unkt

ionfilter

erze

ugtw

erde

n.D

iese

rüb

ergi

btm

anei

neFu

nktio

n,di

efü

rArg

umen

tebo

ol'sc

heW

erte

zurü

cklie

fert

Page 140: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

und

eine

Lis

te,ü

berd

ieite

rier

twer

den

soll.

Zur

ück

erhä

ltm

anei

neL

iste

mit

allj

enen

Wer

ten,

fürd

iedi

eFu

nktio

nTrue

liefe

rt:

#!/usr/bin/python

def

durch3teilbar(x):

returnx

%3

==

0

print

filter(durch3teilbar,

range(10))

Aus

gabe

userlocalhost:$̃./comprehension4.py

[0,

3,

6,

9]

Die

Funk

tiondurch3teilbar()

ergi

btTrue

füra

lleW

erte

,die

durc

h3

teilb

arsi

nd.N

urno

chdi

ese

Wer

teve

rble

iben

inde

rübe

rgeb

enen

Lis

te.

Page 141: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

5.9

Gen

erat

oren

Funk

tione

nw

ierange()

undxrange()

erze

ugen

Obj

ekte

,übe

rdie

sich

iterie

ren

läss

t,im

einf

achs

ten

Fall

List

enod

erTu

pel.

Eine

ande

reA

rtite

rierb

a-re

rObj

ekte

sind

Gen

erat

oren

,um

die

eshi

erge

ht.

5.9.

1G

ener

ator

enm

ityi

eld

Ein

Gen

erat

orw

ird

wie

eine

Funk

tion

erze

ugt

und

erst

ellt

eine

Folg

evo

nW

erte

n.E

inen

Gen

erat

orke

nnen

Sie

bere

its,n

ämlic

hxrange()

.Die

Folg

ew

ird

Ele

men

tew

eise

bere

itges

tellt

mityield()

:

#!/usr/bin/python

def

MeinGenerator():

yield(1)

yield(2)

yield(3)

Page 142: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

for

iin

MeinGenerator():

printi

Aus

gabe

userlocalhost:$̃./yield1.py

1 2 3 yield()

liefe

rtbe

imer

sten

Auf

rufd

esG

ener

ator

sde

ner

sten

Wer

tzur

ück

und

stop

ptda

nndi

eA

usfü

hrun

g.E

sw

ird

hier

bei

also

kein

eL

iste

erze

ugt,

sond

ern

jede

rZ

ugri

ffau

fde

nG

ener

ator

liefe

rtde

nnä

chst

envo

nyield()

bere

itges

tellt

enW

ert.

Wer

tein

Gen

erat

oren

lass

ensi

chbe

quem

infor

-Sch

leif

ener

zeug

en:

#!/usr/bin/python

def

rueckwaerts(text):

Page 143: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

length

=len(text)

fori

in

xrange(length):

yield(text[length

-i

-1])

for

cin

rueckwaerts("Hallo,

Welt!"):

print"\b%c"

%c,

print

Aus

gabe

userlocalhost:$̃./yield2.py

!tleW

,ollaH

Hie

rwir

dde

rTex

trüc

kwär

tsau

sgeg

eben

,wob

eiyield()

ange

fang

envo

mle

tzte

nZe

iche

nje

des

Zeic

hen

des

Text

eszu

rück

liefe

rt.D

ada

sK

omm

abe

ider

print

-Anw

eisu

ngei

nLe

erze

iche

nei

nfüg

t,m

üsse

nw

irm

itei

nem

Bac

kspa

ce(\

b)da

fürs

orge

n,da

ssdi

eses

wie

dere

ntfe

rntw

ird.

Tipp

:

Page 144: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

oben

benu

tzte

Funk

tion

dien

tals

einf

ache

sB

eisp

ielz

urD

emon

stra

tion

von

Gen

erat

oren

.Wen

nSi

esi

chab

erfr

agen

,wie

eine

Zeic

henk

ette

einf

ach

rück

wär

tsda

rges

tellt

wer

den

kann

,dan

nhä

ngen

Sie

[::-1]

anei

neSt

ring

-Var

iabl

eod

eran

ein

Stri

ng-L

itera

l.D

asgl

eich

eE

rgeb

nis

wie

oben

wär

eüb

er"Hallo,Welt!"[::-1]

eben

falls

mög

lich.

5.9.

2G

ener

ator

expr

essi

ons

Auc

hfü

rGen

erat

oren

gibt

esw

iede

rein

eab

kürz

ende

Schr

eibw

eise

:

#!/usr/bin/python

genex

=(i

*ifor

iin

xrange(5))

for

wert

in

genex:

printwert

Page 145: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./genex1.py

0 1 4 9 16 Die

Synt

axis

tähn

lich

wie

beiL

istC

ompr

ehen

sion

s,je

doch

wer

den

rund

eK

lam

mer

nve

rwen

det.

5.10

Zus

amm

enfa

ssun

g

Wir

habe

nge

zeig

t,w

iem

anFu

nktio

nen

defin

iert

,Wer

tezu

rück

gibt

und

Funk

-tio

nen

mit

vari

able

nPa

ram

eter

liste

nsc

hrei

bt.D

erG

ebra

uch

von

loka

len

und

glob

alen

Var

iabl

enw

urde

erlä

uter

twie

auch

die

Anw

endu

ngde

rFun

ktio

nen

aufL

iste

nm

itH

ilfe

vonmap()

.Als

Synt

axzu

cker

gabe

nw

irei

nen

Ein

blic

k

Page 146: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

inan

onym

eFu

nktio

nen.

Lis

tCom

preh

ensi

ons

und

Gen

erat

oren

rund

eten

das

The

ma

ab.

5.11

Anm

erku

ngen

Page 147: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 148: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

6M

odul

e

Mod

ule

dien

enda

zu,z

usam

men

gehö

rige

Funk

tione

nun

dK

lass

enin

Dat

eien

zugr

uppi

eren

.A

ufdi

ese

Wei

sela

ssen

sich

größ

ere

Que

lltex

tsam

mlu

ngen

them

atis

chor

gani

sier

en.

6.1

Auf

bau

eine

sMod

ules

Ein

Mod

ulbe

steh

tau

sei

ner

Folg

evo

nQ

uellt

extz

eile

n.D

aM

odul

eni

cht

ausg

efüh

rtw

erde

nm

üsse

n,sp

aren

wir

uns

die

beid

enbi

sher

igen

Prog

ram

men

benu

tzte

Inte

rpre

terd

ekla

ratio

nin

dere

rste

nZ

eile

:

137

Page 149: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def

HalloWelt():

print"Hallo,

Welt!"

def

addiere(a,

b):

returna

+b

Ein

Prog

ram

m,w

elch

esdi

eses

Mod

ulnu

tztk

önnt

ew

iefo

lgta

usse

hen:

#!/usr/bin/python

import

modul1

print

modul1.addiere(1,

2)

Aus

gabe

userlocalhost:$̃./mod1.py

3 Der

Prefi

xvo

rden

Funk

tione

n,di

em

anau

sei

nem

Mod

ulau

sruf

tnen

ntm

anN

amen

srau

m.M

anka

nnbe

liebi

gvi

ele

Nam

ensr

äum

edu

rch

Mod

ule

erze

u-

Page 150: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

gen,

und

kom

mts

obe

ider

Ben

ennu

ngvo

nFu

nktio

nen

nich

tdur

chei

nand

er,

wen

nzw

eiFu

nktio

nen

den

selb

enN

amen

trag

en.

Eska

nnau

falle

vom

Mod

ulex

porti

erte

nEl

emen

tezu

gegr

iffen

wer

den,

esgi

btke

ine

priv

aten

oder

beso

nder

sge

schü

tzte

Funk

tione

nod

erV

aria

blen

.

6.2

Impo

rtie

ren

imD

etai

l

Folg

ende

sM

odul

kann

aufv

ersc

hied

ene

Wei

sen

eing

ebun

den

wer

den:

def

multipliziere(a,

b):

returna*b

def

print_mult(a,

b):

printmultipliziere(a,

b)

Page 151: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Es

kann

bei

läng

eren

Mod

ulna

men

umst

ändl

ich

ersc

hein

en,i

mm

erw

iede

rbe

ije

der

impo

rtie

rten

Funk

tion

den

Mod

ulna

men

davo

rzus

chre

iben

.E

ine

Abk

ürzu

ngbi

etet

das

loka

leU

mbe

nenn

en:

#!/usr/bin/python

import

modul2

as

X

X.print_mult(3,

3)

Aus

gabe

userlocalhost:$̃./mod2.py

9 Hie

rwir

dda

sM

odulmodul2

unte

rdem

Nam

enX

beka

nntg

emac

ht.A

ufal

leFu

nktio

nen

des

Mod

ules

kann

abso

fort

mit

dem

neue

nN

amen

zuge

griff

enw

erde

n.

Den

neue

nN

amen

srau

mka

nnm

anab

erau

chso

impo

rtier

en,d

ass

man

aufd

ieA

ngab

ede

sN

amen

srau

mes

verz

icht

enka

nn:

Page 152: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

from

modul2

import

*

print_mult(3,

3)

Aus

gabe

userlocalhost:$̃./mod3.py

9 Es

wer

den

alle

Funk

tione

nau

sde

mM

odul

impo

rtie

rt,a

lsw

ürde

nsi

elo

kal

vere

inba

rtw

orde

nse

in.D

erSt

ern

dien

tdab

eial

sPl

atzh

alte

rfür

alle

imM

odul

vorl

iege

nden

Dek

lara

tione

n.

Einz

elne

Funk

tione

nau

sde

mM

odul

lass

ensi

chüb

erdi

eex

pliz

iteA

ngab

ede

rFu

nktio

nen

inde

rimport

-Anw

eisu

ngei

nbet

ten,

alle

ande

ren

Dek

lara

tione

nsi

ndun

beka

nnt:

#!/usr/bin/python

from

modul2

import

print_mult

Page 153: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print_mult(3,

3)

Aus

gabe

userlocalhost:$̃./mod4.py

9 Bin

detm

anau

sein

emM

odul

meh

rere

Funk

tione

nei

n,so

sind

sie

mit

Kom

mat

azu

sepa

rier

en,b

eisp

iels

wei

se:

#!/usr/bin/python

from

modul2

import

print_mult,

multipliziere.

Nam

ensr

äum

eha

ben

den

Vort

eil,

dass

man

meh

rere

Funk

tione

nha

ben

kann

,di

ede

ngl

eich

enN

amen

trag

en.D

urch

die

Nen

nung

des

Nam

ensr

aum

esin

derimport

-Anw

eisu

ngis

tim

mer

klar

,wel

che

Funk

tion

man

mei

nt.D

iese

nVo

rtei

lver

liert

man

,wen

nm

ande

nSt

ernc

heni

mpo

rtbe

nutz

t.

Page 154: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

6.3

Inha

ltvo

nM

odul

en

Mod

ule

enth

alte

nvo

nsi

chau

ssc

hon

eine

Rei

hevo

rbel

egte

rV

aria

blen

,die

man

nutz

enka

nn.D

asfo

lgen

deB

eisp

ielz

eigt

den

Zugr

iffau

fzw

eiso

lche

rVa-

riabl

en,n

ämlic

h__name__

und__doc__

.Die

Varia

ble__name__

enth

ält

den

Nam

ende

rakt

uell

ausg

efüh

rten

Funk

tion,

dies

istb

eiM

odul

en__

mai

n__.

__doc__

hing

egen

enth

ält

eine

nD

okum

enta

tions

stri

ng,s

ofer

ndi

eser

amA

nfan

gde

sM

odul

esfe

stge

legt

wur

de:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

"""Dieses

Modul

enthält

Funktionen

rund

um

erste

mathematische

Anweisungen.

"""

def

addiere(a,

b):

returna

+b

def

multipliziere(a,

b):

returna*b

Page 155: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

__name__

print

__doc__

Aus

gabe

userlocalhost:$̃./modinhalt1.py

__main__

Dieses

Modul

enthält

Funktionen

rund

um

erste

mathematische

Anweisungen.

Bea

chte

nSi

ebi

tte,d

ass

dies

esM

odul

Aus

führ

ungs

rech

tebe

nötig

t.N

utze

nka

nnm

andi

ese

Kon

stan

ten,

umei

neD

okum

enta

tion

ausg

eben

zula

ssen

oder

den

Inha

ltde

sM

odul

sm

itde

rFun

ktio

ndir()

anze

igen

zula

ssen

:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

"""Dieses

Modul

enthält

Funktionen

rund

um

erste

mathematische

Anweisungen.

"""

def

addiere(a,

b):

returna

+b

Page 156: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def

multipliziere(a,

b):

returna*b

if

__name__==

"__main__":

print__doc__

printdir()

Aus

gabe

userlocalhost:$̃./modinhalt2.py

Dieses

Modul

enthält

Funktionen

rund

um

erste

mathematische

Anweisungen.

['__builtins__',

'__doc__',

'__file__',

'__name__',

'addiere',

'multipliziere']

Wen

ndi

eses

Mod

ulau

fger

ufen

wir

d,da

nngi

btes

den

Doc

stri

ngau

s,ge

folg

tvo

nde

mIn

halt

des

Mod

uls.

Mit

dies

erTe

chni

kve

rhin

dert

man

,das

sve

rse-

hent

lich

das

fals

che

Mod

ulau

sgef

ührt

wir

dun

dm

anke

ine

Prog

ram

mau

sgab

eer

hält.

Auß

erde

mis

tes

bequ

em,s

oau

fse

ine

Mod

ule

zugr

eife

nzu

könn

en.

dir()

gibt

den

gesa

mte

nIn

halt

des

Mod

uls

aus.

Neb

ende

nN

amen

derF

unk-

Page 157: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

tione

nw

erde

nei

nige

Var

iabl

en,d

ieau

tom

atis

cher

zeug

twur

den,

aufg

efüh

rt.

dir()

könn

enSi

eau

fal

leO

bjek

te,a

lso

auch

Funk

tione

n,St

ring

s,Z

ahle

n,L

iste

nun

dso

fort

anw

ende

n.

Aus

serh

alb

des

Mod

uls,

kann

man

aufd

iese

Mod

ulva

riab

len

eben

falls

zugr

ei-

fen,

wob

eida

nnih

rInh

alta

nder

sla

utet

.Zum

Bei

spie

lgib

t:

#!/usr/bin/python

import

modul3b

print

modul3b.__name__

den

Stri

ngm

odul

3bau

s.D

ieA

nwei

sung

enau

sdi

esem

Mod

ulw

erde

nni

cht

berü

hrt,

dada

sM

odul

jani

chta

usge

führ

twir

d.

Page 158: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

6.4

Pake

te

Pake

tesi

nd(th

emat

isch

e)Zu

sam

men

fass

unge

nvo

nM

odul

enin

eine

rVer

zeic

h-ni

sstr

uktu

r.H

ierb

eiw

erde

nm

ehre

reM

odul

-Dat

eien

hier

arch

isch

gegl

iede

rtin

eine

mV

erze

ichn

isab

gele

gt.

Hin

zuko

mm

tpr

oV

erze

ichn

is-E

bene

eine

Initi

alis

ieru

ngsd

atei

.Die

seIn

itial

isie

rung

sdat

eien

thäl

tfür

dies

eE

bene

die

gem

eins

ame

Dok

umen

tatio

nun

düb

erni

mm

tIn

itial

isie

rung

sauf

gabe

n.D

erIn

halt

dies

erD

atei

wir

dbe

imIm

port

gele

sen

und

ausg

efüh

rt.E

sis

thie

rbei

nich

tno

twen

dig,

dies

erD

atei

Aus

führ

ungs

rech

tezu

gebe

n.E

inty

pisc

her

Pake

t-V

erze

ichn

isba

umka

nnfo

lgen

derm

aßen

auss

ehen

:

mathe/

mathe/__init__.py

mathe/addiere/

/mathe/addiere/addiere.py

/mathe/addiere/__init__.py

mathe/subtrahiere/

/mathe/subtrahiere/subtrahiere.py

Page 159: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

/mathe/subtrahiere/__init__.py

Die

Initi

alis

ieru

ngsd

atei

kann

leer

sein

oder

folg

ende

nA

ufba

uha

ben

(mathe/addiere/__init__.py

):

"""Die

hiesigen

Module

dienen

zum

Addieren

von

Zahlen"""

print

"Initialisierung

von

mathe/addiere/*"

Das

war

essc

hon.

Dieprint

-Anw

eisu

ngw

irdau

sgef

ührt,

wen

nM

odul

eau

sdi

eser

Ebe

neim

port

iert

wer

den.

Der

Auf

bau

von

Mod

ulen

unte

rsch

eide

tsi

chhi

erbe

ini

cht

von

dem

oben

gesa

gten

.D

erV

olls

tänd

igke

itfü

gen

wir

hier

noch

ein

Mod

ulei

n(

mathe/addiere/addiere.py

):

def

add(a,

b):

returna+b

Page 160: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ein

Prog

ram

m,w

elch

esM

odul

eau

sei

nem

Pake

tben

utzt

sieh

tso

aus:

#!/usr/bin/python

import

mathe.addiere.addiere

print

mathe.__doc__

print

"-"

print

mathe.addiere.__doc__

print

mathe.addiere.addiere.add(2,

2)

Aus

gabe

userlocalhost:$̃./paket1.py

Initialisierung

von

mathe/addiere/*

Dieses

Paket

enthält

einige

Mathematik-Module

- Die

hiesigen

Module

dienen

zum

Addieren

von

Zahlen

4

Page 161: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

ses

Prog

ram

mgi

btdi

eD

okum

enta

tion

derM

odul

eau

sun

dbe

nutz

tein

ein

eine

mPa

ketm

odul

defin

iert

eFu

nktio

n.B

each

ten

Sie

bitte

,das

sdi

eA

usga

bebe

imTe

sten

derh

ierv

orge

stel

lten

Dat

eien

von

unse

rerD

arst

ellu

ngab

wei

cht.

Der

Gru

ndis

t,da

ssw

irdi

eD

atei

mathe/__init__.py

nich

tvor

gest

ellt

habe

n.

Pake

tmod

ule

erke

nntm

anan

ihre

rPun

kt-D

arst

ellu

ngbe

imIm

port

.Es

wir

dhi

erau

sde

mm

athe

-Pak

etim

Ver

zeic

hnis

addiere/

das

Pyth

on-M

odul

addiere.py

impo

rtie

rtun

dda

raus

die

Funk

tionadd()

aufg

eruf

en.M

anka

nnpr

oV

erze

ichn

iseb

ene

meh

rere

Mod

ule

habe

n.

Pake

tew

erde

nih

nen

imw

eite

ren

Ver

lauf

des

Buc

hes

anvi

elen

Stel

len

bege

g-ne

n.

Page 162: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

6.5

Zus

amm

enfa

ssun

g

Mod

ule

unte

rsch

eide

nsi

chin

ihre

mA

ufba

uni

chtv

onan

dere

nPy

thon

-Dat

eien

.Si

egl

iede

rnzu

sam

men

gehö

rige

Cod

etei

leun

dkö

nnen

auf

meh

rere

Wei

sen

eing

ebun

den

wer

den.

Ein

ere

ineimport

-Anw

eisu

nger

zeug

tein

enne

uen

Nam

ensr

aum

,von

dene

nm

anni

ege

nug

habe

nka

nn.M

odul

eka

nnun

dso

llte

man

mit

eine

mD

ocst

ring

vers

ehen

.Es

gibt

viel

evo

rbel

egte

Varia

blen

rund

umM

odul

e,vo

nde

nen

wir

eini

gehi

erke

nnen

gele

rnth

aben

.Mod

ule

kann

man

zuPa

kete

ngr

uppi

eren

.

Page 163: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 164: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

7R

und

umO

OP

Obj

ekto

rien

tiert

ePr

ogra

mm

ieru

ngis

tdie

Ver

einh

eitli

chun

gde

rKon

zept

e

•K

apse

lung

:Ein

Obj

ektf

asst

alle

benö

tigte

nB

esta

ndte

ilezu

sam

men

,und

verb

irgtv

orde

mN

utze

rden

inte

rnen

Auf

bau.

Stat

tdes

sen

wer

den

öffe

ntlic

heSc

hnitt

stel

len

expo

rtie

rt,a

ufdi

ede

rNut

zerz

ugre

ifen

kann

.•

Vere

rbun

g:E

inO

bjek

tkan

nE

igen

scha

ften

eine

ran

dere

nK

lass

eim

defi-

nier

ten

Um

fang

erbe

n.E

inze

lne

Teile

könn

enda

beiü

bers

chri

eben

wer

den.

•Po

lym

orph

ie:B

ezei

chne

tdas

Übe

rlade

nvo

nO

pera

tore

nun

dM

etho

den

umei

neei

nhei

tlich

eSc

hnitt

stel

lefü

rver

schi

eden

eD

aten

type

nun

dPa

ram

eter

zuha

ben.

153

Page 165: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

typi

sche

Dar

stel

lung

eine

sO

bjek

tes

isti

nFo

rmei

nerK

lass

e.Fu

nktio

nen,

die

inne

rhal

bei

ner

Kla

sse

vere

inba

rtw

erde

n,ne

nnt

man

Met

hode

n,K

las-

senv

aria

blen

nenn

tman

Att

ribu

te.W

ird

ein

Obj

ekte

rzeu

gt,s

oka

nnes

unte

rU

mst

ände

nei

neA

ktio

nw

ieda

sIn

itial

isie

ren

alle

rDat

enau

sfüh

ren.

Soei

neM

etho

dene

nntm

anK

onst

rukt

or.K

lass

ensp

eich

ertm

anty

pisc

herw

eise

inei

gene

nM

odul

en.

7.1

Auf

bau

eine

rK

lass

e

Die

einf

achs

teK

lass

etu

tgar

nich

tsun

den

thäl

tkei

nerl

eiD

ekla

ratio

nen:

#!/usr/bin/python

class

TuNichts:

pass

objekt

=TuNichts()

Page 166: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

dir(objekt)

print

"Typ:",

type(objekt)

Aus

gabe

userlocalhost:$̃./klasse1.py

['__doc__',

'__module__']

Typ:

<type

'instance'>

Gef

olgt

vom

Schl

üsse

lwor

tclass

steh

tder

Nam

ede

rK

lass

e.E

inO

bjek

ter

zeug

tm

an,i

nde

mes

aufg

eruf

enw

ird.pass

steh

tfü

r:Tu

ew

irkl

ich

gar

nich

ts.D

erIn

halt

dies

esO

bjek

tes

kann

mitdir()

ange

zeig

twer

den.

Die

sen

Typ

Kla

sse

nenn

tm

anC

lass

icC

lass

es.S

iesi

ndm

ittle

rwei

leve

ralte

t,ab

erim

mer

noch

brau

chba

rund

vora

llem

aus

Grü

nden

derK

ompa

tibili

täts

tand

ard.

Um

ihne

nau

chso

glei

chdi

eN

ew-s

tyle

Cla

sses

vorz

ufüh

ren,

hier

noch

mal

das

glei

che

Bei

spie

lin

Neu

:

#!/usr/bin/python

class

TuNichts(object):

pass

Page 167: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

objekt

=TuNichts()

print

dir(objekt)

print

"Typ:",

type(objekt)

Aus

gabe

userlocalhost:$̃./klasse2.py

['__class__',

'__delattr__',

'__dict__',

'__doc__',

'__getattribute_-

_',

'__hash__',

'__init__',

'__module__',

'__new__',

'__reduce__',

'__reduce_ex__',

'__repr__',

'__setattr__',

'__str__',

'__weakref__']

Typ:

<class

'__main__.TuNichts'>

Gef

olgt

vom

Nam

ende

rK

lass

ew

erde

ndi

eE

ltern

klas

sen

notie

rt.W

enn

esm

ehre

reE

ltern

klas

sen

sind

,w

erde

nsi

edu

rch

Kom

mat

ase

pari

ert.

Uns

ere

Kla

sseTuNichts

erbt

nun

die

Eig

ensc

haft

envo

nobject

.Zur

Ver

erbu

ngko

mm

enw

irno

ch.K

lass

enne

uen

Typs

wur

den

inde

rVer

sion

2.2

von

Pyth

onei

ngef

ührt

und

wer

den

verm

utlic

hab

Ver

sion

3.0

zum

Stan

dard

gehö

ren.

Sie

habe

nei

nige

Vor

teile

gege

nübe

rKla

ssen

alte

nTy

ps,w

iezu

mB

eisp

iel,

dass

sie

sich

naht

los

ins

Type

nkon

zept

von

Pyth

onei

nfüg

enun

dei

nige

typi

sche

Page 168: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Met

hode

nm

itbri

ngen

.Alle

wei

tere

nB

eisp

iele

indi

esem

Kap

itelw

erde

nm

itN

ew-s

tyle

Kla

ssen

besp

roch

en,d

ieal

teV

aria

nte

sollt

enSi

eab

erw

enig

sten

ske

nnen

.

Etw

asm

ehrk

ann

scho

nfo

lgen

deK

lass

e:

#!/usr/bin/python

class

TuEtwas(object):

def__init__(self,

x):

self.x

=x

defprintX(self):

printself.x

objekt

=TuEtwas(42)

objekt.printX()

Aus

gabe

userlocalhost:$̃./klasse3.py

42

Page 169: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

seK

lass

een

thäl

tzw

eiM

etho

den,

näm

lich__init__()

undprintX()

.__init__()

wir

dau

fger

ufen

,wen

nei

nO

bjek

tder

Kla

sse

ange

legt

wir

d.D

iese

Met

hode

mus

sni

chte

xpliz

itau

fger

ufen

wer

den.

Das

Arg

umen

tself

bezi

ehts

ich

auf

die

Kla

sse

selb

st.self.x

ista

lso

eine

Var

iabl

e,di

ein

der

Kla

sse

ange

legt

ist(

Attr

ibut

),ni

chta

lslo

kale

Var

iabl

ein

den

Met

hode

n.R

uft

eine

Met

hode

eine

ande

reau

f,so

mus

seb

enfa

llsself

vord

enM

etho

dena

uf-

rufg

esch

rieb

enw

erde

n.

Die

folg

ende

Kla

sse

impl

emen

tiert

eine

phys

ikal

isch

eG

röße

,die

Tem

pera

tur.

Tem

pera

ture

nw

erde

nin

Gra

dFa

hren

heit,

Kel

vin

oder

Gra

dC

elsi

usge

mes

-se

n,w

obei

wir

nurd

iele

tzte

nbe

iden

Ein

heite

nbe

rück

sich

tigen

.Die

Kla

sse

spei

cher

talle

Tem

pera

ture

nin

Kel

vin.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Temperatur(object):

def__init__(self,

Wert,

Einheit

="K"):

ifEinheit

==

"K":

self.temperatur

=Wert

Page 170: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

self.einheit

=Einheit

elifEinheit

==

"°C":

self.temperatur

=Wert

+273

self.einheit

="K"

else: self.temperatur

=0

self.einheit

="K"

defumrechnen(self,

Einheit

="K"):

ifEinheit

==

"K":

return

self.temperatur

elifEinheit

==

"°C":

return

self.temperatur

-273

defausgeben(self,

Einheit

="K"):

ifEinheit

in

("K",

"°C"):

print

"Die

Temperatur

beträgt

%.2f

%s"

%(self.umrechnen(Einheit),

Einheit)

else: print

"unbekannte

Einheit"

T1

=Temperatur(273,

"K")

T1.ausgeben("°C")

Page 171: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

T1.ausgeben("K")

T1.ausgeben("°F")

Aus

gabe

userlocalhost:$̃./klasse4.py

Die

Temperatur

beträgt

0.00

°C

Die

Temperatur

beträgt

273.00

K

unbekannte

Einheit

Die

Kla

sse

enth

ältd

reiM

etho

den,

näm

lich__init__()

,den

Kon

stru

ktor

,umrechnen()

,ein

eM

etho

de,d

ievo

nK

elvi

nin

ande

reEi

nhei

ten

umre

chne

nka

nnun

ddi

eM

etho

deausgeben()

,wel

che

die

aktu

elle

Tem

pera

tur

als

Strin

gau

sgib

t.D

ieA

ttrib

ute

dies

erK

lass

esi

ndtemperatur

undeinheit

.In

dies

erK

lass

esi

ndal

leA

ttrib

ute

öffe

ntlic

hsi

chtb

arun

dve

ränd

erba

r.

Page 172: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

7.2

Priv

at-m

ehr

oder

wen

iger

Um

gege

nübe

rden

Nut

zern

eine

rKla

sse

anzu

deut

en,d

ass

best

imm

teM

etho

-de

nod

erA

ttrib

ute

priv

atsi

nd,a

lso

nich

tnac

hau

ßen

expo

rtie

rtw

erde

nso

llen,

stel

ltm

anih

nen

eine

nU

nter

stri

ch(_

)vor

ran.

Ech

tpriv

atsi

ndso

lche

rart

ge-

kenn

zeic

hnet

enA

ttrib

ute

nich

t,es

hand

elts

ich

hier

beim

ehru

mei

nete

xtue

lleV

erei

nbar

ung,

wie

folg

ende

sB

eisp

ielz

eigt

:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Quadrat(object):

def__init__(self,

kantenlaenge

=0.0):

ifkantenlaenge

<0.0:

self._kantenlaenge

=0.0

else: self._kantenlaenge

=kantenlaenge

defflaeche(self):

returnself._kantenlaenge

*self._kantenlaenge

Page 173: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Q1

=Quadrat(10)

print

Q1.flaeche()

Q1._kantenlaenge

=4

print

Q1.flaeche()

Aus

gabe

userlocalhost:$̃./privat1.py

100

16 Es

kann

hier

derK

ante

nlän

geei

nW

ertz

ugew

iese

nw

erde

n,w

asvo

mA

utor

derK

lass

esi

cher

nich

tbea

bsic

htig

twar

.Das

Attr

ibut_kantenlaenge

ist

nurd

urch

die

Vere

inba

rung

gesc

hütz

t,an

die

man

sich

als

Nut

zere

iner

Kla

sse

imA

llgem

eine

nha

lten

sollt

e.

Um

noch

stär

kera

nzud

eute

n,da

ssA

ttrib

ute

priv

atsi

nd,w

erde

nzw

eiU

nter

-st

riche

verw

ende

t.A

uch

hier

kann

man

derK

ante

nlän

geei

nen

Wer

tzuw

eise

n,er

wir

dje

doch

nich

tber

ücks

icht

igt:

#!/usr/bin/python

Page 174: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#-*-

coding:

utf-8

-*-

class

Quadrat(object):

def__init__(self,

kantenlaenge

=0.0):

ifkantenlaenge

<0.0:

self.__kantenlaenge

=0.0

else: self.__kantenlaenge

=kantenlaenge

defflaeche(self):

returnself.__kantenlaenge

*self.__kantenlaenge

Q1

=Quadrat(10)

print

Q1.flaeche()

Q1.__kantenlaenge

=4

print

Q1.flaeche()

Aus

gabe

userlocalhost:$̃./privat2.py

100

100

Page 175: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Inbe

iden

Fälle

nis

tdi

eFl

äche

imm

ergl

eich

,de

rW

ert

der

Kan

-te

nlän

geve

ränd

ert

sich

trot

zZ

uwei

sung

nich

t.D

aslie

gtda

ran,

dass

esQ1.__kantenlaenge

gar

nich

tgi

bt.

Bei

der

Zuw

eisu

ngQ1.__kantenlaenge=4

wir

dei

nne

ues

Kla

ssen

attr

ibut

erze

ugt.

Das

eige

ntlic

hal

spr

ivat

dekl

arie

rte

Attr

ibut__kantenlaenge

vers

teck

tsic

hnu

nhi

nter

dem

Aus

druc

k_Quadrat__kantenlaenge

.Die

skö

nnen

Sie

leic

htm

itH

ilfe

derdir()

-Fun

ktio

nse

lbst

über

prüf

en:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Quadrat(object):

def__init__(self,

kantenlaenge

=0.0):

ifkantenlaenge

<0.0:

self.__kantenlaenge

=0.0

else: self.__kantenlaenge

=kantenlaenge

defflaeche(self):

returnself.__kantenlaenge

*self.__kantenlaenge

Page 176: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Q1

=Quadrat(10)

print

"Die

Fläche

beträgt:

",

Q1.flaeche()

Q1.__kantenlaenge

=4

print

"Q1.__kantenlaenge:

",

Q1.__kantenlaenge

print

"Die

echte

Kantenlänge:

",

Q1._Quadrat__kantenlaenge

print

"Q1

hat

folgenden

Inhalt:\n",

dir(Q1)

Aus

gabe

userlocalhost:$̃./privat3.py

Die

Fläche

beträgt:

100

Q1.__kantenlaenge:

4

Die

echte

Kantenlänge:

10

Q1

hat

folgenden

Inhalt:

['_Quadrat__kantenlaenge',

'__class__',

'__delattr__',

'__dict__',

'_-

_doc__',

'__getattribute__',

'__hash__',

'__init__',

'__kantenlaenge',

'__module__',

'__new__',

'__reduce__',

'__reduce_ex__',

'__repr__',

'__setattr__',

'__str__',

'__weakref__',

'flaeche']

Page 177: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Wie

Sie

sehe

n,ha

ben

wir

mit

derZ

uwei

sung

Q1.__kantenlaenge=4

ein

neue

sA

ttrib

uter

zeug

t,de

nnof

fenb

arw

urde

dies

esja

nich

tfür

die

Fläc

hen-

bere

chnu

nghe

rang

ezog

en.

UN

KN

OW

NT

EM

PLA

TE

Pyth

on_u

nter

_Lin

ux:V

orla

gen:

Vorl

ageD

etai

ls

Mac

hen

Sie

sich

bitte

kein

eal

lzu

groß

enG

edan

ken

über

priv

ate

Attr

ibut

eun

dM

etho

den.

Der

Pyt

hon

way

ofco

ding

istd

aw

enig

erst

reng

,als

ande

reSp

rach

en.S

telle

nsi

eal

lem

,was

nich

tnac

hau

ßen

hin

sich

tbar

sein

soll,

eine

nU

nter

stri

chvo

ran,

dann

iste

spr

ivat

genu

g.D

iese

Vere

inba

rung

reic

htPy

thon

-Pr

ogra

mm

iere

rnim

allg

emei

nen

aus.

7.3

Get

ter

und

Sett

er

Inre

alen

Prog

ram

men

iste

sse

hrw

icht

ig,e

inen

kons

iste

nten

Zug

riff

aufd

ieK

lass

ezu

habe

n,so

dass

beid

erÄ

nder

ung

von

Attr

ibut

enau

chw

eite

rhin

alle

Kla

ssen

attr

ibut

eko

rrek

teW

erte

habe

n.Pr

oble

me

indi

esem

Ber

eich

ents

te-

Page 178: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

hen

oftd

adur

ch,d

ass

Nut

zer

eine

rK

lass

edi

eIm

plem

enta

tion

nich

tken

nen

oder

kenn

enso

llen.

Der

Zug

riff

auf

Attr

ibut

eer

folg

tda

nndu

rch

spez

ielle

Met

hode

n,di

ele

digl

ich

Attr

ibut

wer

tem

odifi

zier

enod

erzu

rück

gebe

n.D

iese

nenn

tman

gette

run

dse

tter,

sie

hole

nod

erse

tzen

Wer

te.I

nob

jekt

orie

ntie

r-te

nPr

ogra

mm

iers

prac

hen,

die

kein

endi

rekt

enZ

ugri

ffau

fK

lass

enat

trib

ute

erm

öglic

hen,

finde

tman

dahe

roft

triv

iale

Met

hode

nvo

r,di

ele

digl

ich

Wer

tese

tzen

oder

zurü

ckge

ben.

Auc

hin

folg

ende

mB

eisp

ielv

erw

ende

nw

irzw

eiso

lche

eige

ntlic

hüb

erflü

ssig

enge

tter.

Sie

dien

enda

zu,i

hnen

das

Kon

zept

vorz

ufüh

ren

und

aufw

eite

reD

etai

lssp

äter

einz

ugeh

en.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Quadrat(object):

def__init__(self,

kantenlaenge

=0.0):

self.set_kantenlaenge(kantenlaenge)

def_berechne_flaeche(self):

self.__flaeche

=self.__kantenlaenge

*self.__kantenlaenge

defget_kantenlaenge(self):

Page 179: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

returnself.__kantenlaenge

defset_kantenlaenge(self,

kantenlaenge):

ifkantenlaenge

<0.0:

self.__kantenlaenge

=0.0

else: self.__kantenlaenge

=kantenlaenge

self._berechne_flaeche()

defget_flaeche(self):

returnself.__flaeche

Q1

=Quadrat(10)

print

Q1.get_flaeche()

Q1.set_kantenlaenge(12)

print

Q1.get_flaeche()

Aus

gabe

userlocalhost:$̃./getset1.py

100

144

Page 180: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Hie

ris

tdi

eFl

äche

ein

wei

tere

sA

ttrib

ut,

wel

ches

durc

hdi

eM

etho

de_berechne_flaeche()

bere

chne

twir

d.B

eije

dem

Auf

ruf,

derd

ieK

an-

tenl

änge

ände

rt,w

ird

die

Fläc

hene

ube

stim

mt.

Indi

eser

Kla

sse

gibt

eszw

ardi

eM

öglic

hkei

t,di

eK

ante

nlän

gezu

mod

ifizi

eren

,nic

htje

doch

die

Fläc

he.

Ein

dire

kter

Zug

riff

aufd

ieA

ttrib

ute

sollt

edr

inge

ndun

terb

leib

en,d

esw

egen

wur

den

dies

eal

sst

ark

priv

atge

kenn

zeic

hnet

.Möc

hte

man

sich

erge

hen,

dass

jede

rZug

riff

aufA

ttrib

ute

über

die

get-

und

set-

Met

hode

nab

gew

icke

ltw

ird,

jedo

chtr

otzd

emau

fden

bequ

emen

Zug

riff

perO

bjek

tvar

iabl

enzu

grei

fen,

soka

nndi

eFu

nktio

nproperty()

helf

en.S

ieak

zept

iert

min

dest

ens

eine

get-

und

set-

Met

hode

und

liefe

rtei

nen

Nam

enfü

rden

Zug

riff

aufd

asA

ttrib

ut:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Quadrat(object):

def__init__(self,

kantenlaenge):

self.set_kantenlaenge(kantenlaenge)

def_berechne_flaeche(self):

self._flaeche

=self._kantenlaenge*

self._kantenlaenge

Page 181: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

defget_kantenlaenge(self):

returnself._kantenlaenge

defset_kantenlaenge(self,

kantenlaenge):

ifkantenlaenge

<0.0:

self._kantenlaenge

=0.0

else: self._kantenlaenge

=kantenlaenge

self._berechne_flaeche()

defget_flaeche(self):

returnself._flaeche

kantenlaenge

=property(get_kantenlaenge,

set_kantenlaenge)

flaeche

=property(get_flaeche)

Q1

=Quadrat(12)

print

"Kantenlänge

=",

Q1.kantenlaenge,

"Fläche

=",

Q1.flaeche

Q1.kantenlaenge

=9

print

"Kantenlänge

=",

Q1.kantenlaenge,

"Fläche

=",

Q1.flaeche

Page 182: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./getset2.py

Kantenlänge

=12

Fläche

=144

Kantenlänge

=9

Fläche

=81

Indi

esem

Cod

eha

ben

wir

alle

inte

ress

ante

nG

ette

rund

Sette

rein

gefü

gtun

dam

Ende

derK

lass

em

itein

ande

rver

web

t.Fü

rdas

Attr

ibutkantenlaenge

sind

also

die

Met

hode

nget_kantenlaenge()

undset_kantenlaenge()

vera

ntw

ortli

ch,d

ieih

rers

eits

aufA

ttrib

ute

wieself._kantenlaenge

zu-

grei

fen.

Das

Attr

ibutflaeche

hing

egen

kann

nur

gele

sen

wer

den,

dade

rSe

tterf

ürdi

eses

Attr

ibut

fehl

t.Pr

oper

ties

wer

den

inne

rhal

bde

rKla

sse,

jedo

chau

sser

halb

alle

rMet

hode

nde

klar

iert

.

7.4

Stat

isch

eM

etho

den

Mit

stat

isch

enM

etho

den

lass

ensi

chM

etho

dens

amm

lung

enan

lege

n,di

esi

chni

chta

ufda

sje

wei

lige

Obj

ektb

ezie

hen,

sond

ern

allg

emei

ngül

tigfo

rmul

iert

Page 183: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

sind

.Dam

itnu

tzen

sie

auch

Anw

ende

rnde

rK

lass

e,di

eke

inK

lass

enob

jekt

benö

tigen

.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Rechteck(object):

def__init__(self,

kante1,

kante2):

self._kante1

=kante1

self._kante2

=kante2

defberechne_flaeche(a,

b):

returna

*b

flaeche

=staticmethod(berechne_flaeche)

print

Rechteck.flaeche(3,

5)

Aus

gabe

userlocalhost:$̃./statisch1.py

15

Page 184: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Hie

rwir

dei

neso

lche

stat

isch

eM

etho

dena

men

sflaeche()

defin

iert

.Die

dahi

nter

liege

nde

Met

hodeberechne_flaeche

darf

keinself

-Arg

umen

tm

itfüh

ren,

denn

dies

esbe

zieh

tsic

hja

gera

deau

fdie

Inst

anz

derK

lass

ese

lbst

.E

sbr

auch

tebe

nfal

lske

inO

bjek

tvon

TypRechteck

dekl

arie

rtzu

wer

den.

Selb

iges

Bei

spie

lfu

nktio

nier

tau

chno

chet

was

einf

ache

r-

wer

hätte

das

geda

cht.

Hie

rbei

bedi

enen

wir

uns

eine

rso

gena

nnte

nFu

nktio

nsde

kora

tion1 .

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Rechteck(object):

def__init__(self,

kante1,

kante2):

self._kante1

=kante1

self._kante2

=kante2

@staticmethod

defberechne_flaeche(a,

b):

returna

*b

1en

gl.:

func

tion

deco

rato

r

Page 185: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

Rechteck.berechne_flaeche(3,

5)

Aus

gabe

userlocalhost:$̃./statisch2.py

15 @staticmethod

ists

oei

neFu

nktio

nsde

kora

tion.

Vor

eine

Met

hode

ge-

schr

iebe

nbe

wir

ktsi

e,da

ssdi

enu

nfo

lgen

deM

etho

deal

sst

atis

chan

zuse

hen

ist,

also

auch

unab

häng

igvo

mer

zeug

ten

Obj

ektn

utzb

aris

t.

7.5

Poly

mor

phie

Poly

mor

phie

-das

Übe

rlad

envo

nO

pera

tore

nun

dM

etho

den-

funk

tioni

erti

nei

nem

rech

tbeg

renz

ten

Um

fang

.Ein

ige

Bei

spie

leha

ben

Sie

dazu

scho

nim

Kap

itelü

berF

unkt

ione

n,V

aria

ble

Para

met

er2 ,k

enne

ngel

ernt

.In

dies

emA

b-

2K

apite

l5.4

aufS

eite

117

Page 186: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

schn

ittw

olle

nw

irun

sda

hera

ufda

berl

aden

von

Ope

rato

ren

besc

hrän

ken.

Das

folg

ende

Prog

ram

müb

erlä

dtdi

eO

pera

tore

nfü

rdi

eA

dditi

onun

ddi

eM

ultip

likat

ion.

Dar

über

hina

user

mög

licht

uns

das

Prog

ram

m,d

enA

bsol

ut-

betr

agei

nes

Obj

ekte

szu

best

imm

enw

ieau

chdi

eses

Obj

ekti

nei

nen

Stri

ngzu

verw

ande

ln.D

asPr

ogra

mm

beis

piel

impl

emen

tiert

dabe

idie

phys

ikal

isch

eG

röße

der

Kra

ft,

die

indi

esem

Fall

aus

zwei

Kom

pone

nten

best

eht,

eine

rho

rizo

ntal

enR

icht

ung

und

eine

rver

tikal

en.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

math

class

Kraft(object):

def__init__(self,

kx,

ky):

self._kx

=kx

self._ky

=ky

def__add__(self,

F):

x,

y=

F.get()

returnKraft(self._kx

+x,

self._ky

+y)

Page 187: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def__mul__(self,

zahl):

returnKraft(self._kx

*zahl,

self._ky

*zahl)

defget(self):

return

(self._kx,

self._ky)

def__abs__(self):

f2

=self._kx

**2

+self._ky

**2

returnmath.sqrt(f2)

def__str__(self):

return"Die

Kraft

ist

(%.2f,

%.2f),

die

Länge

ist

%.2f"

%(self._kx,

self._ky,

abs(self))

F1

=Kraft(3,

4)

F2

=F1

*3

print

F1

print

F2

print

F1

+F2

Aus

gabe

userlocalhost:$̃./poly11.py

Die

Kraft

ist

(3.00,

4.00),

die

Länge

ist

5.00

Page 188: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

Kraft

ist

(9.00,

12.00),

die

Länge

ist

15.00

Die

Kraft

ist

(12.00,

16.00),

die

Länge

ist

20.00

Wan

nim

mer

ein

Obj

ektm

itei

nem

ande

ren

mul

tipliz

iert

wer

den

soll,

wir

ddi

een

tspr

eche

nde__mult__()

-Met

hode

des

Obj

ekte

sau

fger

ufen

.D

ies

mac

hen

wir

uns

hier

zuN

utze

und

defin

iere

ndi

ese

Met

hode

einf

ach

um.

Selb

iges

gesc

hieh

tbei

derA

dditi

on,h

ierw

ird__add__()

umde

finie

rt.B

eide

Funk

tione

nge

ben

ein

neue

sK

raft

obje

ktzu

rück

.Die__str__()

-Met

hode

wird

imm

erau

fger

ufen

,wen

nei

nO

bjek

tin

eine

nSt

ring

umge

wan

delt

wer

den

soll,

die

Met

hode__abs__()

wird

aufg

eruf

en,w

enn

derA

bsol

utbe

trag

eine

sO

bjek

tes

ange

frag

twird

.Der

Abs

olut

betra

gun

sere

sO

bjek

tes

ists

chlic

htse

ine

Län

ge.E

sgi

btno

chm

ehr

Ope

rato

ren

und

sons

tige

Kla

ssen

met

hode

n,di

em

anin

divi

duel

lfür

Kla

ssen

defin

iere

nka

nn.H

ierz

ufin

den

Sie

imIn

tern

etA

nlei

tung

en.

Page 189: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

7.6

Vere

rbun

g

Mit

Ver

erbu

ngla

ssen

sich

aus

rech

tallg

emei

nen

Kla

sse

spez

ialis

iert

eK

lass

ener

zeug

en,d

ieal

leEi

gens

chaf

ten

derE

ltern

klas

sebe

sitz

en.F

olge

ndes

Bei

spie

lve

rdeu

tlich

tdas

Vorg

ehen

:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Rechteck(object):

def__init__(self,

seite1,

seite2):

self._seite1

=seite1

self._seite2

=seite2

defflaeche(self):

returnself._seite1

*self._seite2

class

Quadrat(Rechteck):

def__init__(self,

seite):

Rechteck.__init__(self,

seite,

seite)

Page 190: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Q1

=Quadrat(4)

print

Q1.flaeche()

Aus

gabe

userlocalhost:$̃./vererb1.py

16 Es

wir

dzu

näch

stei

neal

lgem

eineRechteck

-Kla

sse

impl

emen

tiert

,die

über

die

Fähi

gkei

tver

fügt

,ihr

enFl

äche

ninh

altz

ube

rech

nen.

Die

Spez

ialk

lass

eQuadrat

erbt

soda

nnal

leE

igen

scha

ften

vonRechteck

,ins

beso

nder

edi

eFä

higk

eit,

ihre

Fläc

hene

nnen

zukö

nnen

.Die

Elte

rnkl

asse

nw

erde

nbe

ider

De-

klar

atio

nei

nerK

lass

edu

rch

Kom

mat

age

tren

ntin

die

Kla

mm

ern

gesc

hrie

ben.

Fürj

ede

Bas

iskl

asse

mus

sda

nnde

rKon

stru

ktor

aufg

eruf

enw

erde

n,in

unse

-re

mFa

llRechteck.__init__(self,seite,seite)

.Ein

Kla

sse

kann

auch

von

meh

rere

nE

ltern

erbe

n.A

lsB

eisp

ield

ient

eine

stud

entis

che

Hilf

skra

ftin

eine

rFir

ma.

Die

seis

tsel

bstv

erst

ändl

ich

ein

echt

erSt

udie

rend

er,

hata

lso

eine

Mat

rike

lnum

mer

,jed

och

auch

ein

echt

erM

itarb

eite

rder

Firm

a,be

zieh

tals

oei

nG

ehal

t:

Page 191: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Student(object):

def__init__(self,

MatNummer):

self._matnummer

=MatNummer

def__str__(self):

return"Matrikelnummer:

%d"

%self._matnummer

class

Mitarbeiter(object):

def__init__(self,

Gehalt):

self._gehalt

=Gehalt

def__str__(self):

return"Gehalt:

%d"

%self._gehalt

class

Hilfskraft(Student,

Mitarbeiter):

def__init__(self,

Gehalt,

MatNummer):

Mitarbeiter.__init__(self,

Gehalt)

Student.__init__(self,

MatNummer)

Page 192: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

defgehalt(self):

returnself._gehalt

defmatnummer(self):

returnself._matnummer

Hans

=Hilfskraft(500,

12345)

print

Hans.gehalt(),

Hans.matnummer()

print

Hans

Aus

gabe

userlocalhost:$̃./vererb2.py

500

12345

Matrikelnummer:

12345

Die

Elte

rnkl

asse

nw

erde

ndu

rch

Kom

mat

age

trenn

tbei

derD

efini

tion

derK

las-

seau

fgef

ührt

.Wie

wir

beid

erA

usfü

hrun

gde

sC

odes

sehe

nkö

nnen

,ber

ück-

sich

tigtd

ieprintHans

-Anw

eisu

ngle

digl

ich

die__str__()

-Met

hode

der

Kla

sseStudent

.Ver

taus

chen

Sie

inde

rK

lass

ende

finiti

ondi

eR

eihe

n-fo

lge

vonStudent,Mitarbeiter

,da

nnst

elle

nSi

efe

st,

dass

imm

erdi

ejen

ige__str__()

-Met

hode

derz

uers

tgen

annt

enEl

tern

klas

seau

sgef

ührt

Page 193: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

wir

d.M

öcht

em

anbe

ide

oder

eine

best

imm

teM

etho

dede

rElte

rnau

sfüh

ren,

som

uss

man

eine

eige

neM

etho

desc

hrei

ben:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

class

Student(object):

def__init__(self,

MatNummer):

self._matnummer

=MatNummer

def__str__(self):

return"Matrikelnummer:

%d"

%self._matnummer

class

Mitarbeiter(object):

def__init__(self,

Gehalt):

self._gehalt

=Gehalt

def__str__(self):

return"Gehalt:

%d"

%self._gehalt

class

Hilfskraft(Student,

Mitarbeiter):

def__init__(self,

Gehalt,

MatNummer):

Page 194: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Mitarbeiter.__init__(self,

Gehalt)

Student.__init__(self,

MatNummer)

def__str__(self):

returnMitarbeiter.__str__(self)

+"

"+

Student.__str__(self)

Hans

=Hilfskraft(500,

12345)

print

Hans

Aus

gabe

userlocalhost:$̃./vererb3.py

Gehalt:

500

Matrikelnummer:

12345

Auf

Elte

rnkl

asse

ngr

eift

man

über

die

Kla

ssen

nam

en(Student

oder

Mitarbeiter

)zu,

nich

tübe

rObj

ekte

.

Page 195: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

7.7

Zus

amm

enfa

ssun

g

Indi

esem

Kap

itel

habe

nSi

eei

nen

Übe

rblic

küb

erdi

eFä

higk

eite

nde

rob

-je

ktor

ient

iert

enPr

ogra

mm

ieru

ngm

itPy

thon

gew

onne

n.Si

ew

isse

nnu

n,w

iem

anK

lass

enau

fbau

tund

kenn

enei

nige

typi

sche

Tech

nike

nim

Um

gang

mit

Met

hode

nun

dA

ttrib

uten

.Ebe

nso

habe

nw

irge

zeig

t,w

iein

Pyth

onVe

rerb

ung,

eine

wic

htig

eTe

chni

kde

rOO

P,fu

nktio

nier

t.

7.8

Anm

erku

ngen

Page 196: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

8D

atei

en

Dat

eien

dien

enzu

mda

uerh

afte

nSp

eich

ern

von

Info

rmat

ione

n.Si

ekö

nnen

erze

ugtu

ndge

lösc

htw

erde

n,ih

nen

kann

man

Dat

enan

häng

enod

ervo

rhan

dene

Dat

enüb

ersc

hrei

ben.

Selb

stve

rstä

ndlic

hsi

nddi

eD

aten

lesb

ar,s

iekö

nnen

auch

ausf

ührb

arse

in.E

skö

nnen

sow

ohlT

extd

atei

enw

ieau

chze

iche

n-od

erbl

ocko

rien

tiert

eD

atei

enbe

arbe

itetw

erde

n.

8.1

Öff

nen

und

Schl

ieße

nvo

nD

atei

en

Um

eine

Dat

eizu

erze

ugen

reic

htes

,sie

zum

Schr

eibe

nzu

öffe

n:

185

Page 197: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

datei

=open("hallo.dat",

"w")

datei.close()

Aus

gabe

userlocalhost:$̃./datei1.py

;ls

*.dat

hallo.dat

Indi

esem

Bei

spie

lw

ird

eine

leer

eD

atei

mit

dem

Nam

enhallo.dat

erze

ugt.

Gib

tes

eine

solc

heD

atei

,wir

dsi

eüb

ersc

hrie

ben,

dafü

rso

rgt

das

Dat

eiat

tribu

t"w"

.Ein

eD

atei

wird

zum

Lese

nge

öffn

et,w

enn

man

dasA

ttrib

ut"r"

benu

tzt.

Das

Attr

ibut"a"

hing

egen

wür

dedi

eD

atei

erze

ugen

,fal

lssi

eno

chni

chte

xist

iert

,son

sthi

ngeg

enöf

fnen

und

Dat

enan

das

End

ean

häng

en.

Page 198: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

8.2

Les

enun

dSc

hrei

ben

Übe

rvo

rhan

dene

Dat

eien

läss

tsic

hle

icht

iteri

eren

,wie

folg

ende

sB

eisp

iel

zeig

t.E

sw

erde

nnü

tzlic

heIn

form

atio

nen

aus

der

Dat

ei/etc/passwd

ange

zeig

t:

#!/usr/bin/env

python

#-*-

coding:

utf-8

-*-

datei

=open("/etc/passwd",

"r")

for

zeile

in

datei:

liste

=zeile[:-1].split(":")

print"Benutzer

'%s'

benutzt

die

Shell

%s"

%(liste[0],

liste[6])

datei.close()

Aus

gabe

userlocalhost:$̃./pw.py

Benutzer

'root'

benutzt

die

Shell

/bin/bash

Benutzer

'daemon'

benutzt

die

Shell

/bin/sh

Page 199: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Benutzer

'bin'

benutzt

die

Shell

/bin/sh

...

Es

wir

dbe

ide

mB

eisp

iel

über

jede

Zei

lein

der

Dat

eiite

rier

t.D

ieZ

eile

nw

erde

num

das

Zei

lene

nde

(New

line-

Zei

chen

)ver

kürz

t(zeile[:-1]

)und

dann

nach

Dop

pelp

unkt

enau

fget

eilt

(split(":")

).

Dat

eien

könn

enau

chm

itde

nM

etho

denwrite()

undread()

besc

hrie

ben

und

gele

sen

wer

den:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

datei

=open("hallo.dat",

"w")

datei.write("Hallo

Welt\n\n")

datei.write("Foo

Bar\n")

datei.close()

datei

=open("hallo.dat",

"r")

x=

datei.read()

datei.close()

print

x

Page 200: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./datei2.py

Hallo

Welt

Foo

Bar

Die

Met

hode

write()

schr

eibt

die

Dat

enna

chei

nand

erin

die

Dat

ei,Z

ei-

lenu

mbr

üche

müs

sen

expl

izit

ange

gebe

nw

erde

n.read()

hing

egen

liest

die

gesa

mte

Dat

eiei

nun

der

zeug

tdar

aus

eine

nei

nzel

nen

Stri

ng.

Um

ein

ande

res

Obj

ekta

lsei

nen

Stri

ngzu

spei

cher

nun

dzu

lese

n,m

uss

man

sich

scho

nse

hran

stre

ngen

.Das

folg

ende

Bei

spie

lsc

hrei

btei

neL

iste

von

Tupe

ln,d

ieau

sei

nem

Nam

enun

dei

ner

Zah

lbes

tehe

n.A

nsch

ließe

ndw

ird

dies

eD

atei

eing

eles

en:

#!/usr/bin/python

Page 201: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

studenten

=[('Peter',

123),

('Paula',

988),

('Freddi',

851)]

datei

=open("studenten.dat",

"w")

for

student

in

studenten:

s=

str(student)

+'\n'

datei.write(s)

datei.close()

datei

=open("studenten.dat",

"r")

for

zin

datei:

name,

matnum

=z.strip('()\n

').split(',')

name

=name.strip("\'

")

matnum

=matnum.strip()

print"Name:

%s

Matrikelnummer:

%s"

%(name,

matnum)

datei.close()

Aus

gabe

userlocalhost:$̃./datei4.py

Name:

Peter

Matrikelnummer:

123

Name:

Paula

Matrikelnummer:

988

Name:

Freddi

Matrikelnummer:

851

Page 202: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Tupe

lw

erde

nge

nau

soge

schr

iebe

n,w

iesi

eda

steh

en,

denn

sie

wer

den

auch

soin

eine

nSt

ring

umge

wan

delt.

JeTu

pel

wir

dei

neZ

eile

gesc

hrie

-be

n.L

iest

man

nun

eine

solc

heZ

eile

wie

der

ein,

erhä

ltm

anal

sSt

ring

den

Wer

t('Peter',123)

.D

iese

rw

ird

mit

der

Met

hode

strip()

verä

n-de

rt,u

ndzw

arw

erde

nal

leK

lam

mer

nam

Anf

ang

und

End

ede

sSt

ring

sw

ieau

chL

eerz

eich

enun

dZ

eile

num

brüc

heen

tfer

nt.M

aner

hält

also

den

Stri

ngPeter',123

.Die

serS

tring

wird

mit

derM

etho

desplit()

inzw

eiTe

ilege

teilt

,wob

eida

sK

omm

aal

sTr

ennz

eich

endi

ent.

Die

soen

tsta

nden

eL

iste

wir

dje

Teil

umfü

hren

deA

nfüh

rung

-un

dL

eerz

eich

enbe

rein

igt.strip()

ohne

Arg

umen

teen

tfer

ntL

eerz

eich

en.E

rstj

etzt

habe

nw

irzw

eiSt

ring

s,di

ede

nur

sprü

nglic

hen

Ele

men

ten

derT

upel

ähnl

ich

sehe

n.L

eich

terw

ird

esm

itPi

ckle

1ge

hen.

1K

apite

l8.3

aufS

eite

192

Page 203: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

8.3

Dat

eien

mit

Pick

le

Den

Funk

tione

n,di

ePi

ckle

anbi

etet

,kan

nm

anw

irkl

ich

nahe

zuje

des

Obj

ekt

anbi

eten

,Pic

kle

kann

essp

eich

ern.

Ob

essi

chum

Zah

len,

Lis

ten,

Tupe

lode

rga

nze

Kla

ssen

hand

elti

stPi

ckle

dabe

igle

ich.

Der

Auf

rufi

stre

chte

infa

ch,e

sgi

btei

neFu

nktio

nzu

mpi

ckel

nun

dei

nezu

men

tpic

keln

:

#!/usr/bin/python

import

pickle

studenten

=[('Peter',

123),

('Paula',

988),

('Freddi',

851)]

datei

=open("studenten.dat",

"w")

pickle.dump(studenten,

datei)

datei.close()

datei

=open("studenten.dat",

"r")

meine_studenten

=pickle.load(datei)

print

meine_studenten

datei.close()

Page 204: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./pickle1.py

[('Peter',

123),

('Paula',

988),

('Freddi',

851)]

Der

Funk

tiondump()

über

gibt

man

die

Dat

enso

wie

eine

nD

atei

hand

le.P

ickl

ekü

mm

erts

ich

dann

umda

sSc

hrei

ben.

Das

Lade

npa

ssie

rtm

itload()

.Die

seFu

nktio

nni

mm

tled

iglic

hda

sD

atei

obje

ktau

f.

8.4

Zei

chen

orie

ntie

rte

Dat

eien

Zei

chen

orie

ntie

rte

Dat

eien

sind

ein

Stro

mau

sei

nzel

nen

Byt

es,d

iesi

chni

cht

notw

endi

gerw

eise

als

Text

dars

telle

nla

ssen

.Um

einz

elne

Zei

chen

aus

eine

rD

atei

zule

sen,

über

gebe

nw

irde

rMet

hoderead()

die

Anz

ahld

erau

fein

mal

zule

send

enZ

eich

en.

Als

ein

Bei

spie

lzei

chen

orie

ntie

rter

Dat

eien

benu

tzen

wir

ein

Prog

ram

m,w

el-

ches

uns

Lot

toza

hlen

zufä

llig

vorh

ersa

gt.H

ierz

ule

sen

wir

unte

rL

inux

und

Page 205: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ande

ren

unix

ähnl

iche

nB

etri

ebss

yste

men

die

Dat

ei/dev/random

aus,

wel

che

rech

tgut

eZ

ufal

lsza

hlen

erze

ugt.

Die

sew

erde

nin

eine

mset

gesp

ei-

cher

t.W

irbe

nutz

enhi

erei

nset

,dam

itw

irei

ndeu

tige

vers

chie

dene

Wer

teau

fneh

men

könn

en.S

obal

dw

irse

chs

vers

chie

dene

Zahl

enim

Ber

eich

1bi

s49

habe

n,w

erde

ndi

ese

inei

neL

iste

konv

ertie

rt,s

ortie

rtun

dan

geze

igt:

#!/usr/bin/python

datei

=open("/dev/random",

"r")

lottozahlenSet

=set()

while

len(lottozahlenSet)

<6:

zahl

=ord(datei.read(1))

if0

<zahl

<50:

lottozahlenSet.add(zahl)

datei.close()

lottozahlen

=list(lottozahlenSet)

lottozahlen.sort()

Page 206: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

lottozahlen

Aus

gabe

userlocalhost:$̃./lottozahlen.py

[5,

6,

18,

19,

23,

41]

Esw

irdau

sder

zeic

heno

rient

ierte

nD

atei

/dev/random

jew

eils

ein

einz

el-

nes

Zei

chen

gele

sen,

inei

neZ

ahlv

erw

ande

ltun

din

daslottozahlenSet

eing

efüg

t.D

ieso

rtie

rte

Lis

tew

ird

ausg

egeb

en.

8.5

Blo

ckor

ient

iert

eD

atei

en

Man

che

Dat

eien

sind

soau

fgeb

aut,

dass

sie

meh

rfac

hde

ngl

eich

enD

aten

typ

spei

cher

n,w

iezu

mB

eisp

ielF

olge

nvo

nFl

ießk

omm

azah

len,

Soun

dinf

orm

a-tio

nen

eine

rW

ave-

Dat

ei,L

ogin

-Inf

orm

atio

nen

wie

in/var/log/wtmp

Page 207: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

oder

auch

fest

eD

atei

blöc

kew

iein

/dev/sda

.Sol

che

Dat

eien

nenn

tman

bloc

kori

entie

rt.

8.5.

1N

umer

isch

eB

löck

e

Dat

eien

,die

einf

ache

Folg

ennu

mer

isch

erW

erte

aufn

ehm

enkö

nnen

,wer

den

bequ

emm

itde

mM

odulArray

bear

beite

t.D

asfo

lgen

deB

eisp

iell

egte

ine

solc

heD

atei

anun

dsp

eich

ert

zwei

Flie

ßkom

maz

ahle

nin

ihr.

Die

seW

erte

wer

den

ansc

hlie

ßend

wie

derg

eles

enun

dau

sgeg

eben

.Bitt

ebe

acht

enSi

e,da

ssde

rInh

altd

erin

dies

emB

eisp

iela

ngel

egte

nD

atei

kein

eTe

xtda

rste

llung

der

gesp

eich

erte

nZ

ahle

nis

t.

/usr/bin/env

python

#-*-

coding:

utf-8

-*-

import

array

#Array

anlegen

fa

=array.array("f")

Page 208: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

fa.append(1.0)

fa.append(2.0)

#In

datei

schreiben

datei

=open("block1.dat",

"w")

fa.tofile(datei)

datei.close()

#Aus

Datei

lesen

datei

=open("block1.dat",

"r")

ra

=array.array("f")

ra.fromfile(datei,

2)

datei.close()

#Ausgeben

for

zahl

in

ra:

printzahl

Aus

gabe

userlocalhost:$̃./block1.py

1.0

2.0

Page 209: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ein

Arr

ayw

ird

mitarray(code)

ange

legt

.Ein

ekl

eine

Aus

wah

lan

Cod

esst

elle

nw

irih

nen

indi

eser

Tabe

llevo

r:

Typ

Cod

eZ

eich

enc

und

u(U

nico

de)

int

ilo

ngl

float

f

Es

könn

ennu

rW

erte

mit

dem

ange

gebe

nen

Typ,

inun

sere

mB

eisp

ielF

ließ-

kom

maz

ahle

n,ge

spei

cher

twer

den.

Die

Met

hodeappend()

fügt

dem

Arr

ayei

neZ

ahl

hinz

u,m

ittofile(dateihandle)

wir

dda

sge

sam

teA

rray

gesc

hrie

ben.

Lie

stm

anei

nso

lche

sA

rray

wie

der

ein,

benu

tzt

man

die

Met

hode

fromfile(dateihandle,anzahl)

.Hie

rmus

sm

anne

ben

derD

atei

noch

die

Anz

ahld

erW

erte

wis

sen,

die

man

ausl

esen

möc

hte.

Zur

Aus

gabe

könn

enw

irei

nfac

hin

beka

nnte

rWei

seüb

erda

sA

rray

iteri

eren

.

Page 210: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

8.5.

2St

rukt

urie

rte

Blö

cke

Wäh

rend

man

esbe

iLog

-Dat

eien

mei

sten

sm

itTe

xtda

teie

nzu

tun

hat,

gibt

eshi

nun

dw

iede

rSys

tem

date

ien,

die

eine

nbl

ocko

rien

tiert

enA

ufba

uha

ben.

Bei

spie

lsw

eise

istd

ieD

atei

/var/log/lastlog

eine

Folg

evo

nB

löck

enm

itfe

ster

Län

ge2 .J

eder

Blo

ckre

präs

entie

rtde

nZ

eitp

unkt

des

letz

ten

Log

ins,

das

zuge

höri

geTe

rmin

alun

dde

nH

ostn

amen

des

Rec

hner

s,vo

nde

mau

sm

ansi

chan

gem

elde

that

.Der

Ben

utze

rm

itde

rU

ser-

ID10

00ha

tden

1000

sten

Blo

ck.D

erB

enut

zerr

ootm

itde

rUse

r-ID

0de

n0t

enB

lock

.

Hat

man

einm

alhe

raus

gefu

nden

,w

iedi

eD

atei

aufg

ebau

tis

t,un

dw

elch

eD

aten

type

nhi

nter

den

einz

elne

nE

intr

ägen

stec

ken,

kann

man

sich

den

Blo

ck-

typ

mit

Pyth

ons

Mod

ulstruct

nach

baue

n.H

ierf

üris

tde

rFo

rmat

stri

ngge

dach

t,de

rim

folg

ende

nB

eisp

ieli

nko

mpa

kter

Form

den

Dat

enty

pei

nes

last

log-

Ein

trag

sna

chah

mt.

Wir

best

imm

ende

nle

tzte

nA

nmel

deze

itpun

ktde

sB

enut

zers

mit

derU

ser-

ID10

00un

dah

men

soei

nen

Teil

des

Uni

x-B

efeh

les

last

log

nach

:

2Si

ehe

last

log(

8)un

dut

mp.

hau

fihr

emC

ompu

ter

Page 211: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/env

python

#-*-

coding:

utf-8

-*-

import

struct

format

="i32s256s"

userID

=1000

blockgroesse

=struct.calcsize(format)

datei

=open("/var/log/lastlog",

"r")

datei.seek(userID

*blockgroesse)

eintrag

=datei.read(blockgroesse)

b=

struct.unpack_from(format,

eintrag)

datei.close()

print

"Zeitstempel:",

b[0]

print

"Terminal:",

str(b[1])

print

"Hostname:",

str(b[2])

Aus

gabe

userlocalhost:$̃./lastlog1.py

Zeitstempel:

1241421726

Page 212: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Terminal:

:0

Hostname:

Der

Form

atst

ring

isti32s256s

.Hin

ter

dies

erkr

yptis

chen

Abk

ürzu

ngve

r-bi

rgts

ich

ein

Dat

enty

p,de

rein

enIn

tege

rent

hält

(i),d

ann

eine

Zeic

henk

ette

(s)

von

32B

yte

Län

gege

folg

tvon

eine

rwei

tere

nZ

eich

enke

tte,d

ie25

6Z

eich

enla

ngis

t.

Wir

best

imm

endi

eB

lock

größ

em

itde

rM

etho

decalcsize(Formatstring)

.D

iese

Blo

ckgr

öße

wir

din

Byt

esge

-m

esse

n.A

nsch

ließe

ndw

ird

die

Dat

ei/var/log/lastlog

geöf

fnet

und

mitseek(Position)

bis

zuei

ner

best

imm

ten

Stel

lein

der

Dat

eivo

rges

pult.

Ein

Ein

trag

der

Dat

eiw

ird

gele

sen

und

mit

Hilf

ede

rM

etho

deunpack_from(Formatstring,String)

inei

n3-

Tupe

lko

nver

tiert

.St

ring

-Dat

enin

dies

emTu

pel

müs

sen

expl

izit

konv

ertie

rtw

erde

n,da

man

anso

nste

nan

gehä

ngte

NU

LL

-Byt

esm

itfüh

rt.

Page 213: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Der

Zei

tste

mpe

lal

sU

nix-

Zei

tw

ird

zusa

mm

enm

itde

nan

dere

nA

ngab

enau

sgeg

eben

.

8.6

Bin

ärda

teie

n

Unt

erB

inär

date

ien

vers

tehe

nw

irD

atei

en,d

ieni

chta

ussc

hlie

ßlic

hau

sTe

xtbe

steh

en,s

onde

rnin

sbes

onde

reau

chni

chtd

arst

ellb

are

Zeic

hen

enth

alte

n.So

l-ch

eD

atei

enha

ben

wir

inde

nvo

rgen

annt

enA

bsch

nitte

nzu

bloc

kori

entie

rten

Dat

eien

scho

nke

nnen

gele

rnt.

Ein

egr

unds

ätzl

iche

Unt

ersc

heid

ung

zwis

chen

Text

-und

Bin

ärda

teifi

ndet

aufB

etri

ebss

yste

meb

ene

ohne

hin

nich

tsta

tt.

Mit

den

uns

beka

nnte

nFu

nktio

nen

könn

enw

irle

icht

Info

rmat

ione

nau

sso

l-ch

enD

atei

enex

trah

iere

n.D

asfo

lgen

deB

eisp

ielz

eigt

,wie

wir

die

Anz

ahld

erK

anäl

eei

nerW

ave-

Dat

ei3

erm

ittel

n.

3D

asD

atei

form

atis

tun

ter

http://www.hib-wien.at/leute/wurban/

informatik/waveformat.pdf

gutd

okum

entie

rt.

Page 214: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

datei

=open("test.wav",

"r")

datei.seek(8)

text

=str(datei.read(4))

print

"Kennung:",

text

datei.seek(22)

#nur

das

höherwertige

Byte

auslesen

kanaele

=ord(datei.read(1))

print

"Die

WAV-Datei

hat",

kanaele,

"Kanäle"

datei.close()

Aus

gabe

userlocalhost:$̃./binary1.py

Kennung:

WAVE

Die

WAV-Datei

hat

1Kanäle

Page 215: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Das

Prog

ram

mze

igt,

wie

man

andi

eW

AVE

-Ken

nung

und

andi

eK

anäl

eko

mm

t.D

ieD

atei

wir

dga

nzno

rmal

zum

Les

enge

öffn

et4 .

Die

sest

ehen

anbe

stim

mte

nPo

sitio

nen

inde

rD

atei

,die

wir

mitseek()

ansp

ring

en.A

n-sc

hlie

ßend

wer

den

die

Ken

nung

wie

auch

die

Anz

ahld

erK

anäl

ege

lese

nun

dau

sgeg

eben

.

Bitt

ebe

acht

enSi

e,da

ssdi

ese

Art

auf

Med

ienf

orm

ate

zuzu

grei

fen

nur

das

Kon

zept

verd

eutli

chen

soll.

Zu

den

mei

sten

Med

ienf

orm

aten

gibt

esei

gene

Mod

ule,

die

den

Auf

bau

eine

sFo

rmat

eske

nnen

und

som

itei

nen

gutd

okum

en-

tierte

nZu

griff

aufd

ieIn

halte

biet

en.F

ürde

nhi

erda

rges

tellt

enZu

griff

aufd

asM

edie

nfor

mat

WAV

Ebi

etet

Pyth

onda

sM

odulwave

an.

4U

nter

man

chen

Bet

rieb

ssys

tem

enw

ird

beim

Öff

nen

eine

r"B

inär

date

i"ei

n"b

"an

den

Mod

usge

häng

t.D

ies

istu

nter

Lin

uxun

dan

dere

nun

ixar

tigen

Bet

rieb

ssys

tem

enni

cht

nötig

.

Page 216: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

8.7

Verz

eich

niss

e

Wen

nm

anvo

mU

mga

ngm

itD

atei

enre

det,

gehö

ren

Ver

zeic

hnis

seun

wei

-ge

rlic

hda

zu.D

iebe

iden

häufi

gste

nFu

nktio

nen

indi

esem

Zus

amm

enha

ngsi

ndw

ohl,

zuüb

erpr

üfen

obei

nV

erze

ichn

isex

istie

rtun

des

gege

bene

nfal

lsan

zule

gen.

Ein

Bei

spie

l:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

os

datei

="test.txt"

verzeichnis

="test"

pfad

=verzeichnis

+os.sep

+datei

if

not

os.path.exists(verzeichnis):

os.mkdir(verzeichnis)

offen

=open(pfad,

"w")

offen.write("hallo")

offen.close()

Page 217: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./folders1.py;

ls

test

test.txt

Das

Prog

ram

mer

zeug

tein

enPf

ad,d

erau

sei

nem

Ver

zeic

hnis

,ein

emTr

enn-

zeic

hen

und

eine

mD

atei

nam

enbe

steh

t.D

asTr

ennz

eich

ener

fähr

tman

mit

os.sep

,unt

erun

ixäh

nlic

hen

Bet

rieb

ssys

tem

enis

tdie

sm

eist

ens

derS

chrä

g-st

rich

(/).D

ieFu

nktio

nos.path.exists()

prüf

t,ob

eine

Dat

eiod

erei

nVe

rzei

chni

svor

hand

enis

t.W

enn

nich

t,da

nnw

irdm

itos.mkdir()

ein

neue

ser

zeug

tund

ansc

hlie

ßend

eine

Dat

eihi

nein

gesc

hrie

ben.

Ein

ean

dere

Anw

endu

ngis

ther

ausz

ufind

en,i

nw

elch

emVe

rzei

chni

sw

irak

tu-

ells

ind

und

dann

alle

enth

alte

nen

Ver

zeic

hnis

seun

dD

atei

enab

dem

über

ge-

ordn

eten

Ver

zeic

hnis

aufz

ulis

ten.

Die

ses

Prog

ram

mim

plem

entie

rtde

nB

efeh

lls

-R..:

#!/usr/bin/python

import

os

Page 218: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"Wir

sind

hier->",

os.getcwd()

os.chdir("..")

for

r,

d,

fin

os.walk(os.getcwd()):

printr,

d,

f

Aus

gabe

userlocalhost:$̃./folders2.py

Wir

sind

hier->

/home/tandar/x/y

/home/tandar/x

['y']

['datei1.txt']

/home/tandar/x/y

[]

['datei2.txt']

Mit

derF

unkt

iongetcwd()

finde

nw

irda

sak

tuel

leV

erze

ichn

ishe

raus

.An-

schl

ieße

ndkö

nnen

wir

mitchdir(Pfad)

inda

süb

erge

ordn

ete

oder

ein

ande

res

Verz

eich

nis

wec

hsel

n.Fü

rjen

esVe

rzei

chni

sru

fen

wirwalk(Pfad)

auf,

und

erha

lten

eine

Men

gevo

n3-

Tupe

ln,d

ieau

sei

nem

Bas

ispf

ad,e

iner

Lis

tem

iten

thal

tene

nV

erze

ichn

isse

nun

dei

nerL

iste

mit

enth

alte

nen

Dat

eien

best

eht.

Die

seA

ngab

enge

ben

wir

imPr

ogra

mm

schl

icht

aus.walk()

berü

ck-

sich

tigtü

brig

ens

kein

esy

mbo

lisch

enL

inks

aufV

erze

ichn

isse

.Sin

dso

lche

zu

Page 219: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

erw

arte

n,ka

nnab

Pyth

on2.

6walk(top=Pfad,followlinks=True)

benu

tztw

erde

n.

8.8

Zus

amm

enfa

ssun

g

Indi

esem

Kap

itelh

aben

Sie

eine

berb

lick

über

die

Verw

endu

ngvo

nD

atei

enun

dO

rdne

rnm

itPy

thon

beko

mm

en.T

extd

atei

enla

ssen

sich

unko

mpl

izie

rtle

sen

und

schr

eibe

n,be

iand

eren

Dat

enty

pen

als

Text

biet

etsi

chPi

ckle

an.

Blo

ck-u

ndze

iche

nori

entie

rte

Dat

eien

lass

ensi

cheb

enfa

llsbe

quem

lese

nun

dbe

schr

eibe

n,w

obei

imFa

llde

rblo

ckor

ient

iert

enD

atei

ende

rAuf

bau

beka

nnt

sein

mus

s.D

iem

eist

enda

teib

asie

rten

Ope

ratio

nen

lass

ensi

chm

itFu

nktio

nen

aus

dem

Mod

ulos

ansp

rech

en,d

esse

nIn

halt

wir

imK

apite

lÜbe

rblic

küb

ervo

rhan

dene

Mod

ule5

nähe

rbel

euch

ten.

5K

apite

l11

aufS

eite

237

Page 220: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

9R

egul

äre

Aus

drüc

ke

Reg

ulär

eA

usdr

ücke

helf

enbe

imFi

nden

von

Text

stel

len.

Sie

wer

den

ange

ge-

ben

inFo

rmvo

nM

uste

rnw

ie"I

chsu

che

eine

Folg

evo

nZi

ffern

amA

nfan

gei

ner

Text

zeile

".Fü

r"Z

iffer

nfol

ge"

und

"Zei

lena

nfan

g"gi

btes

Kur

zsch

reib

-w

eise

nun

dR

egel

n,w

iedi

ese

zuko

mbi

nier

ensi

nd.U

mdi

eFu

nktio

nen

und

Met

hode

nru

ndum

Reg

ulär

eA

usdr

ücke

benu

tzen

zukö

nnen

,müs

sen

wir

das

Mod

ulre

einb

inde

n.

209

Page 221: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

9.1

Find

eir

gend

wo

Hab

enw

irTe

xtze

ilen,

inde

nen

beis

piel

swei

seTe

lefo

nnum

mer

nun

dN

amen

aufg

elis

tets

ind,

sokö

nnen

wir

mit

Hilf

evo

nre

gulä

ren

Aus

drüc

ken

die

Nam

envo

nde

nTe

lefo

nnum

mer

ntr

enne

n-z

umB

eisp

ielu

mna

chei

nerb

estim

mte

nTe

lefo

nnum

mer

inei

nerl

ange

nTe

xtda

teiz

usu

chen

:

#!/usr/bin/python

import

re

s=

"Peter

030111"

m=

re.search(r"(\w+)

(\d+)",

s)

length

=len(m.groups())

for

iin

xrange(length

+1):

print"Group",

i,

":",

m.group(i)

Aus

gabe

userlocalhost:$̃./re1.py

Page 222: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Group

0:

Peter

030111

Group

1:

Peter

Group

2:

030111

Hab

enw

irei

neTe

xtze

ile,

die

das

Tupe

len

thäl

t,so

könn

enw

irm

itde

rsearch()

-Fun

ktio

nna

chde

nei

nzel

nen

Tupe

l-Ele

men

ten

such

en.H

ierb

eiis

t"\w

"ei

nei

nzel

nes

Zei

chen

aus

derM

enge

derB

uchs

tabe

n,de

rMod

ifizi

erer

"+"

bede

utet

"min

dest

ens

ein"

Zei

chen

zusu

chen

.Die

Kla

mm

ern

grup

pier

endi

ese

Aus

drüc

ke.D

erer

ste

Aus

druc

kin

Kla

mm

ern

bede

utet

also

:Fin

deei

neni

chtl

eere

Zei

chen

kette

aus

Buc

hsta

ben

und

nenn

ees

die

erst

eG

rupp

em

itG

rupp

enin

dex

1.(\d+)

such

tnac

hei

nern

icht

leer

enZ

iffer

nfol

geun

dgi

btdi

eser

Gru

ppe

den

Inde

x2,

dasi

ean

zwei

terS

telle

steh

t.search()

liefe

rtei

nso

gena

nnte

sM

atch

-Obj

ekt,

wen

net

was

gefu

nden

wur

de,s

onstNone

.groups()

liefe

rtei

nTu

pelm

ital

len

gefu

nden

enG

rupp

en,m

itgroup()

kann

man

aufe

inze

lne

Gru

ppen

zugr

eife

n,w

obei

derI

ndex

0ei

neZu

sam

men

-fa

ssun

gal

lerG

rupp

enal

sei

nzel

nen

Stri

ngan

biet

et.

Page 223: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Nun

mus

sm

anni

cht

alle

sgr

uppi

eren

,nac

hde

mm

ansu

cht.

Man

ches

Tei-

leei

nes

Aus

druc

kes

möc

hte

man

schl

icht

verw

erfe

n,um

andi

ere

leva

nten

Info

rmat

ione

nei

nes

Text

eszu

kom

men

:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

re

s="""Opa

hat

am

10.

12.

1903

Geburtstag.

Oma

wurde

am

14.

07.

geboren.

Mutti,

deren

Eltern

sich

am

10.02.1949

über

die

Geburt

freuten,

hat

heute

selber

Kinder.

Vater

hat

am

3.

4.

1947

Geburtstag"""

for

line

in

s.splitlines():

m=

re.search(r"^(\w+)\D*(\d*)\.\s?(\d*)\.\s?(\d*)",

line)

printline

printm.groups()

Aus

gabe

userlocalhost:$̃./re2.py

Page 224: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Opa

hat

am

10.

12.

1903

Geburtstag.

('Opa',

'10',

'12',

'1903')

Oma

wurde

am

14.

07.

geboren.

('Oma',

'14',

'07',

)

Mutti,

deren

Eltern

sich

am

10.02.1949

über

die

Geburt

freuten,

hat

heute

selber

Kinder.

('Mutti',

'10',

'02',

'1949')

Vater

hat

am

3.

4.

1947

Geburtstag

('Vater',

'3',

'4',

'1947')

Die

for

-Sch

leif

ew

ird

über

jede

Zei

leau

sgef

ührt

,w

obei

die

Met

hode

splitlines()

eine

nTe

xtin

einz

elne

Zei

len

zerl

egt.

Indi

esem

Bei

spie

lin

tere

ssie

rtun

sde

rN

ame,

der

dem

Zei

lena

nfan

gal

ser

stes

Wor

tfo

lgt,

der

Geb

urts

tag,

Geb

urts

mon

atun

dda

sG

ebur

tsja

hr,w

elch

esau

chfe

hlen

darf

.Der

Zeile

nanf

ang

wird

mit

eine

mD

ach

(ˆ)a

bgek

ürzt

.Die

erst

eG

rupp

ebe

inha

ltet

ein

Wor

t,in

dem

Fall

den

Nam

en.

Page 225: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

9.2

Aus

drüc

keim

Übe

rblic

k

Hie

rei

nA

ussc

hnitt

aus

der

Spra

che

der

regu

läre

nA

usdr

ücke

.Alte

rnat

iven

wer

den

durc

hK

omm

asge

tren

nt.

Aus

druc

kB

edeu

tung

.D

erPu

nktp

asst

aufj

edes

Zei

chen

ˆA

nfan

gei

nerZ

eich

enke

tteod

erZ

eile

$E

nde

eine

rZei

chen

kette

oder

Zei

le[a

bc]

Pass

tauf

eine

Zei

chen

aus

der

Men

ge"a

bc"

[abc

],[a

-z]

Pass

tauf

eine

Zei

chen

aus

der

Men

ge"a

bc",

"abi

sz"

A|B

Pass

tauf

den

regu

läre

nA

usdr

uck

Aod

erau

fB

Page 226: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

druc

kB

edeu

tung

\AA

nfan

gei

nerZ

eich

enke

tte\d

,[0-

9]E

ine

einz

elne

Ziff

er\D

,[ˆ0

-9]

Jede

sZ

eich

enau

ßer

derZ

iffer

\sL

eerz

eich

enw

ieTa

b,Sp

ace,

...\S

Jede

sZ

eich

enau

ßer

dem

Lee

rzei

-ch

en\w

Buc

hsta

ben,

Ziff

ern

und

derU

n-te

rstr

ich

\WA

lleZ

eich

enau

ßer

solc

hen,

die

in\w

defin

iert

sind

\ZD

asE

nde

eine

rZei

chen

kette

Neb

enei

nzel

nen

Zei

chen

kann

auch

die

Anz

ahld

ervo

rkom

men

den

Zei

chen

begr

enzt

wer

den.

Folg

ende

Tabe

llegi

btei

nen

Übe

rblic

k:

Aus

druc

kB

edeu

tung

Bei

spie

l

Page 227: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

druc

kB

edeu

tung

Bei

spie

l*

Der

Aus

druc

kko

mm

tm

inde

sten

s0-

mal

vor.

.*

+D

erA

usdr

uck

kom

mt

min

dest

ens

1-m

alvo

r.\d

+

?D

erA

usdr

uck

kom

mt

0-od

er1-

mal

vor.

(LO

TTO

GE

WIN

N)?

{n}

Der

Aus

druc

kko

mm

tn-

mal

vor

\w{3

}

{m,n

}D

erA

usdr

uck

kom

mt

min

dest

ens

m-m

al,

höch

sten

sn-

mal

vor

\w{3

,10}

*?,+

?,??

die

kürz

este

Var

iant

eei

nerF

unds

telle

wir

der

kann

t

.*?,

.+?,

.??

Page 228: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

9.3

Gie

rige

sSuc

hen

Um

den

Unt

ersc

hied

zwis

chen

den

vers

chie

dene

nQ

uant

oren

zuve

rdeu

tlich

en,

such

enw

irin

eine

man

gege

bene

nSt

ring

mit

vers

chie

dene

nK

ombi

natio

nen

von

Qua

ntor

enna

chA

usdr

ücke

n,di

eau

fbei

den

Seite

nvo

nei

nem

"e"

begr

enzt

wer

den.

Wir

bild

enda

zudr

eiG

rupp

en,d

ieun

ters

chie

dlic

hla

nge

Ber

eich

efin

den:

#!/usr/bin/python

import

re

zeile

="Dies

ist

eine

Zeile"

m=

re.search(r"(.*)(e.*e)(.*)",

zeile)

print

m.groups()

m=

re.search(r"(.*?)(e.*?e)(.*)",

zeile)

print

m.groups()

m=

re.search(r"(.*?)(e.*e)(.*?)",

zeile)

print

m.groups()

Page 229: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./gierig1

('Dies

ist

eine

Z',

'eile',

'')

('Di',

'es

ist

e',

'ine

Zeile')

('Di',

'es

ist

eine

Zeile',

'')

Wie

wir

sehe

nkö

nnen

,find

enal

ledr

eiA

usdr

ücke

Text

,jed

och

unte

rsch

iedl

ich

lang

.Die

Var

iant

e(.*?)

finde

tmög

lichs

twen

igTe

xt,w

ähre

nd(.*)

mög

-lic

hstl

ange

Fund

stel

len

finde

t.So

lche

Qua

ntor

enw

erde

nal

sgi

erig

beze

ichn

et.

9.4

Mat

chin

g

Wäh

rend

search()

imge

sam

ten

über

gebe

nen

Stri

ngna

chei

nem

Aus

druc

ksu

cht,

istmatch()

auf

den

Anf

ang

des

Stri

ngs

besc

hrän

kt.S

uche

nw

irin

eine

rD

atei

wie

/var/log/syslog

nach

Ere

igni

ssen

vom

26.J

anua

r,kö

nnen

wir

das

leic

htm

itmatch()

erle

dige

n:

Page 230: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

import

re

datei

=open("/var/log/syslog",

"r")

print

"Am

26.

Januar

passierte

folgendes:"

for

zeile

in

datei:

m=

re.match(r"Jan

26

(.*)",

zeile)

ifm

!=

None:

printm.group(1)

datei.close()

Aus

gabe

userlocalhost:$̃./match1

Am

26.

Januar

passierte

folgendes:

10:08:19

rechner

syslogd

1.5.0#2ubuntu6:

restart.

10:08:21

rechner

anacron[4640]:

Job

‘cron.daily'

terminated

10:12:42

rechner

anacron[4640]:

Job

‘cron.weekly'

started

...

Page 231: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Esw

irdhi

erna

chal

len

Zeic

hen

gesu

cht,

die

derZ

eich

enke

tte"J

an26

"fo

lgen

.D

ies

ist

der

Anf

ang

der

Zei

le.

Gib

tes

solc

heZ

eich

en,

wer

den

nur

dies

eau

sgeg

eben

.

9.5

Ich

will

meh

r!

Gru

ppen

mus

sm

anni

chta

ufzä

hlen

,man

kann

sie

auch

bene

nnen

,wie

folg

en-

des

Skri

ptze

igt:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

re

wunsch

="Chef,

ich

brauche

mehr

Geld.

1000

oder

2000

Euro

halte

ich

für

angebracht!"

m=

re.search(r"(?P<geld>\d{4})",

wunsch)

Page 232: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

m.groups()

print

m.group('geld')

Aus

gabe

userlocalhost:$̃./re3.py

('1000',)

1000

Die

Gru

ppe(?P<geld>A)

gibt

dem

eing

esch

loss

enen

regu

läre

nA

usdr

uck

eine

nN

amen

.E

sw

ird

nach

eine

rge

nau

4-st

ellig

enZ

ahl

gesu

cht,

und

auch

gefu

nden

.Die

ses

Bei

spie

loff

enba

rtab

ersc

hon

eine

Schw

ieri

gkei

tmit

search()

:Wir

finde

nnu

rdas

erst

eVo

rkom

men

des

Aus

druc

ks(1

000)

,nic

htje

doch

den

Zw

eite

n.

Hie

rdie

verb

esse

rte

Ver

sion

,die

wir

klic

hal

leW

unsc

hvor

stel

lung

enzu

finde

nin

derL

age

ist:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

Page 233: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

import

re

wunsch

="Chef,

ich

brauche

mehr

Geld.

1000

oder

2000

Euro

halte

ich

für

angebracht!"

liste

=re.findall(r"\d{4}",

wunsch)

print

liste

Aus

gabe

userlocalhost:$̃./re4.py

['1000',

'2000']

findall()

wir

dge

naus

oau

fger

ufen

wiesearch()

,find

etje

doch

auch

meh

rfac

heVo

rkom

men

derA

usdr

ücke

imTe

xt.

9.6

Mod

i

Sow

ohlsearch()

wie

auchmatch()

erla

uben

als

dritt

enPa

ram

eter

eine

nW

ert,

derd

ieB

edeu

tung

des

ange

gebe

nen

Reg

ulär

enA

usdr

ucks

spez

ifizi

ert.

Page 234: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

folg

ende

Tabe

llegi

btei

nen

Übe

rblic

küb

erdi

ese

Flag

s:

Flag

Bed

eutu

ngIG

NO

RE

CA

SEG

roß-

und

Kle

insc

hrei

bung

wir

dni

chtu

nter

schi

eden

LO

CA

LE

\w,\

W,\

b,\B

,\s

und

\Sw

erde

nab

-hä

ngig

von

derg

ewäh

lten

Spra

ch-

eins

tellu

ngbe

hand

elt

MU

LTIL

INE

Bee

influ

sstˆ

und

$.E

sw

erde

nde

rZei

lena

nfan

gun

dda

s-e

nde

beac

htet

.D

OTA

LL

Der

Punk

t(.)

soll

jede

sZ

eich

enfin

den,

auch

Zei

lenw

echs

elU

NIC

OD

E\w

,\W

,\b,

\B,\

d,\D

,\s

und

\Sw

erde

nal

sU

nico

de-Z

eich

enbe

-ha

ndel

t

Page 235: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Flag

Bed

eutu

ngV

ER

BO

SEE

rlau

btun

tera

nder

emK

omm

enta

-re

inR

egul

ären

Aus

drüc

ken,

Lee

r-ze

iche

nw

erde

nig

nori

ert.

Dam

itla

ssen

sich

schö

neA

usdr

ücke

mit

Kom

men

tare

nzu

sam

men

setz

en.

Hie

rei

nB

eisp

iel,

wie

man

dies

eFl

ags

anw

ende

t.E

sw

ird

nach

eine

rIP

-A

dres

sege

such

t,di

esi

chüb

erm

ehre

reZe

ilen

erst

reck

t.Zw

isch

enzw

eiZa

hlen

kann

sow

ohle

inPu

nkts

tehe

nw

ieau

chei

nPu

nktg

efol

gtvo

nei

nem

Neu

e-Z

eile

-Zei

chen

.Wir

benu

tzen

dahe

rda

sFl

agDOTALL

,um

den

Punk

tau

chdi

eses

Zei

chen

such

enzu

lass

en.N

eben

beiz

eige

nw

ir,w

iem

ande

nA

ufzä

h-lu

ngsq

uant

or({1,3}

)ben

utzt

.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

re

zeile

="""Dieses

sind

mehrere

Zeilen,

es

geht

Page 236: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

hier

um

die

Darstellung

einer

IP-Adresse

192.168.

10.1.

Diese

wird

über

mehrere

Zeilen

verteilt."""

m=

re.search(r"(\d{1,3}).+?(\d{1,3}).+?(\d{1,3}).+?(\d{1,3}).",

zeile,

re.DOTALL)

if

mis

None:

print"nicht

gefunden"

else: printm.groups()

Aus

gabe

userlocalhost:$̃./modi1.py

('192',

'168',

'10',

'1')

Wie

wir

sehe

n,w

ird

die

IP-A

dres

seko

rrek

tgef

unde

n.

9.7

Gru

ppen

Man

kann

inR

egul

ären

Aus

drüc

ken

Gru

ppen

bild

en.E

inig

evo

ndi

esen

Gru

p-pe

nha

ben

Sie

scho

nke

nnen

gele

rnt.

Indi

esem

Abs

chni

ttge

ben

wir

eine

n

Page 237: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Übe

rblic

küb

erM

öglic

hkei

ten,

Aus

drüc

kezu

grup

pier

en.F

olge

nde

Gru

ppen

wer

den

unte

rstü

tzt:

Gru

ppe

Bed

eutu

ng(?

:Aus

druc

k)D

iese

Gru

ppe

wir

dig

nori

ert.

Man

kann

sie

nich

tpergroups()

her-

ausl

ösen

,ebe

nfal

lska

nnm

ansi

eni

chti

nner

halb

derA

usdr

ücke

refe

renz

iere

n.(?

P<N

ame>

Ausd

ruck

)W

eist

eine

rGru

ppe

eine

nN

amen

zu.S

iehe

das

Bei

spie

lIc

hw

illm

ehr!

1

1K

apite

l9.9

aufS

eite

234

Page 238: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Gru

ppe

Bed

eutu

ng(?

P=N

ame)

Die

seG

rupp

ew

ird

erse

tztd

urch

den

Text

,der

von

derG

rupp

em

itde

man

gege

bene

nN

amen

gefu

n-de

nw

urde

.Dam

itla

ssen

sich

in-

nerh

alb

von

Aus

drüc

ken

Ref

eren

-ze

nau

fvor

heri

geSu

cher

gebn

isse

bild

en.

(?#I

nhal

t)In

halt

wir

dal

sK

omm

enta

rbeh

an-

delt.

A(?

=Aus

druc

k)A

pass

tnur

dann

,wen

nal

snä

chs-

tes

Aus

druc

kfo

lgt.

Sons

tnic

ht.

Die

ses

ista

lso

eine

Art

Vor

scha

uau

fkom

men

deSu

cher

gebn

isse

A(?

!Aus

druc

k)A

pass

tnur

dann

,wen

nA

usdr

uck

nich

tals

näch

stes

folg

t.

Page 239: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Gru

ppe

Bed

eutu

ng(?

<=Au

sdru

ck)A

Apa

sstn

urda

nn,w

enn

Aus

druc

kvo

rAko

mm

t.(?

<!Au

sdru

ck)A

Apa

sstn

icht

,wen

nA

usdr

uck

vor

Ako

mm

t.(?

(Nam

e)A

1|A

2)D

erA

usdr

uck

A1

wir

dnu

rdan

nal

sSu

chm

uste

rben

utzt

,wen

nei

neG

rupp

em

itN

amen

Nam

eex

is-

tiert

.Son

stw

ird

der(

optio

nale

)A

usdr

uck

A2

benu

tzt.

Wir

wol

len

nun

den

Geb

rauc

hei

nige

rreg

ulär

erA

usdr

ücke

dem

onst

rier

en:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

re

zeilen

=["Peter

sagt:

Peter,

gib

mir

den

Ball",

"Hans

sagt:

Peter,

sprichst

Du

mit

dir

selbst?"]

Page 240: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"Leute,

die

gerne

mit

sich

selbst

sprechen:"

for

zin

zeilen:

m=

re.match(r"(?P<Person>\w+)

sagt:

(?P=Person),\.*",

z)

ifm

is

not

None:

printm.group('Person')

Indi

esem

Bei

spie

lwir

dei

neG

rupp

ePerson

erze

ugt.

Inde

rers

ten

Zei

leis

tde

rInh

altd

iese

rGru

ppe

Pete

r,in

derz

wei

ten

Han

s.(?P=Person)

nim

mt

nun

Bez

ugau

fden

Inha

ltdi

eser

Gru

ppe.

Steh

tan

derS

telle

derb

etre

ffen

den

Zei

leeb

enfa

llsda

s,w

asde

rIn

halt

der

erst

enG

rupp

ew

ar(a

lso

Pete

rod

erH

ans)

,dan

npa

sstd

erge

sam

tere

gulä

reA

usdr

uck.

Sons

tnic

ht.I

ndi

esem

Fall

pass

tnur

die

erst

eZ

eile

,den

nes

kom

mtz

wei

mal

Pete

rvo

r.

Etw

asko

mpl

izie

rteri

stde

rAus

druc

kim

folg

ende

nB

eisp

iel.

Esw

irddi

eD

atei

/etc/group

unte

rsuc

ht.E

sso

llen

allj

ene

Gru

ppen

aufg

elis

tetw

erde

n,di

eSe

kund

ärgr

uppe

nfü

rUse

rsin

d.D

iese

Zei

len

erke

nntm

anan

:

cdrom:x:24:haldaemon,tandar

Page 241: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

floppy:x:25:haldaemon,tandar

Es

sind

jedo

chZ

eile

,die

kein

eU

serb

einh

alte

n,zu

igno

rier

en,w

iedi

efo

lgen

-de

n:

fax:x:21:

voice:x:22:

Ein

Prog

ram

m,d

asdi

ese

Zus

amm

enst

ellu

ngsc

haff

t,ka

nnm

itre

gulä

ren

Aus

-dr

ücke

nar

beite

n.N

urje

neZ

eile

n,di

ehi

nter

dem

letz

ten

Dop

pelp

unkt

Text

habe

n,so

llen

berü

cksi

chtig

twer

den.

Der

Gru

ppen

nam

ew

ieau

chdi

eB

enut

-ze

rnam

enso

llen

inei

nere

igen

enA

usdr

ucks

-Gru

ppe

gesp

eich

ertw

erde

n.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

re

datei

=open("/etc/group",

"r")

Page 242: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"User

mit

Sekundärgruppen"

for

zeile

in

datei:

m=

re.match(r"(?P<Group>\w+)(?=:x:\d+:\S+):x:\d+:(?P<Mitglieder>.*)",

zeile)

ifm

is

not

None:

print"User",

m.group('Mitglieder'),

"ist/sind

in

der

Gruppe",

m.group('Group')

datei.close()

Aus

gabe

userlocalhost:$̃./gruppen2.py

User

mit

Sekundärgruppen

User

haldaemon,tandar

ist/sind

in

der

Gruppe

cdrom

User

haldaemon,tandar

ist/sind

in

der

Gruppe

floppy

...

weitere

Ausgabe...

Der

Aus

druc

k(?P<Group>\w+)(?=:x:\d+:\S+)

besa

gt,

dass

nur

dann

wen

nna

chde

mle

tzte

nD

oppe

lpun

ktno

chTe

xtfo

lgt,

derG

rupp

em

itde

mN

amen

Gro

upde

rUni

x-G

rupp

enna

me

zuge

wie

sen

wer

den

soll.

Es

wir

dhi

er

Page 243: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

also

eine

Vors

chau

aufk

omm

ende

Such

erge

bnis

sebe

trieb

en.D

iese

Such

erge

b-ni

sse

wer

den

jedo

chni

chtg

espe

iche

rt.A

nsch

ließe

ndw

irdde

rZw

isch

enbe

reic

him

Aus

druc

k:x:\d+:

kons

umie

rtun

dm

it(?P<Mitglieder>.*)

die

Mitg

liede

rlis

teau

fgen

omm

en.

9.8

Wei

terf

ühre

nde

Hin

wei

se

Reg

ulär

eA

usdr

ücke

,w

iew

irsi

ein

dies

emK

apite

lbe

spro

chen

habe

n,si

ndre

cht

kurz

und

wur

den

nur

auf

wen

ige

Text

zeile

nan

gew

ende

t.H

atm

anab

erw

irkl

ich

die

Auf

gabe

,gr

oße

Log

date

ien

zuun

ters

uche

n,bi

e-te

tes

sich

an,

Aus

drüc

kevo

rzub

erei

ten.

Aus

drüc

kekö

nnen

mit

der

Me-

thod

ecompile(Ausdruck,Flags)

vorb

erei

tetw

erde

n,um

dann

mit

match()

undsearch()

abge

arbe

itetz

uw

erde

n.So

lche

kom

pilie

rten

Aus

-dr

ücke

sind

schn

elle

r.

Folg

ende

sB

eisp

iel

dem

onst

rier

tda

sV

orge

hen,

wob

eiw

irhi

er/var/log/messages

ausw

erte

n:

Page 244: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

re

datei

=open("/var/log/messages",

"r")

exp

=re.compile(r"Jan

27

(?P<Zeit>\d+:\d+:\d+)

.*?

(?P<Ereignis>.*)")

print

"Wann

passierte

heute

was?"

for

zeile

in

datei:

m=

exp.match(zeile)

ifm

is

not

None:

printm.group('Zeit'),

m.group('Ereignis')

datei.close()

And

ers

als

bei

invo

rher

igen

Abs

chni

tten

vorg

este

llten

Met

hode

nw

ird

hier

zuer

stei

nO

bjek

ter

zeug

t,w

elch

esde

mko

mpi

liert

enA

usdr

uck

ents

pric

ht.

Des

sen

Met

hode

nsi

ndeb

enfa

llsun

ter

ande

rem

match()

undsearch()

.exp.match(zeile)

ist

hier

anal

ogzu

sehe

nzu

re.match(Ausdruck,Zeile)

.

Page 245: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

9.9

Zus

amm

enfa

ssun

g

Indi

esem

Kap

itelw

urde

ndi

eM

öglic

hkei

ten

Reg

ulär

erA

usdr

ücke

inPy

thon

vorg

este

llt.I

mK

apite

lNet

zwer

k2le

rnen

Sie

wei

tere

nütz

liche

Anw

endu

ngen

kenn

en.

2K

apite

l14

aufS

eite

305

Page 246: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

10H

albz

eit

Wen

nSi

ees

bis

hier

hin

gesc

haff

thab

en,d

ann

habe

nSi

ePy

thon

kenn

enge

lern

t.L

ehne

nSi

esi

chal

sozu

rück

,gen

ieße

nSi

eei

neTa

sse

Kaf

fee

oder

Tee

und

freu

enSi

esi

chüb

erda

sE

rler

nte.

235

Page 247: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.1

Spät

erw

erde

nw

irIh

nen

eine

nA

usbl

ick

aufv

orha

nden

eM

odul

ege

ben,

aber

jetz

tnoc

hni

cht..

..;-

)

Page 248: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

11Ü

berb

lick

über

Mod

ule

Indi

esem

Kap

itelg

eben

wir

eine

berb

lick

über

Mod

ule,

die

mei

sten

sm

itin-

stal

liert

wer

den.

Ans

chlie

ßend

wir

dei

neM

etho

dege

zeig

t,m

itde

rman

selb

stm

ehrü

beru

nbek

annt

e(a

bera

uch

verm

eint

lich

beka

nnte

)Mod

ule

hera

usfin

den

kann

.

237

Page 249: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

11.1

Mod

ulcm

ath

Die

ses

Mod

ulbe

inha

ltetm

athe

mat

isch

eFu

nktio

nen

zurA

rbei

tmit

kom

plex

enZ

ahle

n.In

Pyth

onha

ben

kom

plex

eZ

ahle

nei

nen

eige

nen

Typ,complex

.A

ufge

schr

iebe

nw

erde

nsi

ezu

mB

eisp

iela

ls5+3j

1 .

Ein

Bei

spie

l:

#!/usr/bin/python

import

cmath

z=5+4j

print

zprint

cmath.sqrt(z)

Aus

gabe

userlocalhost:$̃./datei3.py

1In

derd

euts

chsp

rach

igen

Lite

ratu

rzu

kom

plex

enZ

ahle

nis

tdas

"i"

häufi

gan

zutr

effe

n.

Page 250: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

(5+4j)

(2.38779440462+0.837593050781j)

11.2

Mod

ulda

tetim

e

Das

Mod

ulda

tetim

eis

tfür

die

Ver

wal

tung

von

Dat

umun

dZ

eitz

ustä

ndig

.D

azu

wer

den

die

Kla

ssentime

,date

,datetime

(Zus

amm

enfa

ssun

gvo

ntim

eun

dda

te)

sow

ietimedelta

(Zei

tdiff

eren

zen)

undtzinfo

(Zei

tzo-

neni

nfor

mat

ione

n)de

finie

rt.D

ieV

erw

endu

ngvo

ndate

wir

din

folg

ende

mPr

ogra

mm

dem

onst

rier

t:

#!/usr/bin/python

from

datetime

import

date

t=date(2008,

4,

10)

print

"Datum

allgemein:

"+

str(t)

Page 251: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"Datum

auf

deutsch:

"+

str(t.day)

+"."

+str(t.month)

+"."

+str(t.year)

Aus

gabe

userlocalhost:$̃./date.py

Datum

allgemein:

2008-04-10

Datum

auf

deutsch:

10.4.2008

Hie

rfol

gtei

neku

rze

Übe

rsic

htüb

erei

nige

derv

orha

nden

enM

etho

den:

Dat

e-Fu

nktio

nen

Bed

eutu

ngfr

omtim

esta

mp(

times

tam

p)L

iefe

rtda

sD

atum

pass

end

zum

Uni

x-Z

eits

tem

pel.

Zei

tste

mpe

lka

nnm

anvo

ntime.time()

(Mod

ultim

e)ge

liefe

rtbe

kom

men

.to

day(

)L

iefe

rtda

she

utig

eD

atum

year

,mon

th,d

ay(K

lass

enat

trib

ute)

Rep

räse

ntie

ren

das

Jahr

,den

Mon

atun

dde

nTa

g

Page 252: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Tim

e-Fu

nktio

nen

Bed

eutu

ngho

ur,m

inut

e,se

cond

,mic

rose

-co

nd(K

lass

enat

trib

ute)

Rep

räse

ntie

-re

nSt

unde

,Min

ute,

Seku

nde

und

Mik

rose

kund

eis

ofor

mat

()L

iefe

rtdi

eZ

eiti

mIS

O86

01-F

orm

at:

HH

:MM

:SS.

mic

rose

kund

enst

rftim

e(fo

rmat

)L

iefe

rtdi

eZ

eitu

nter

Ver

wen

dung

von

Form

atan

gabe

n.B

eisp

iele

:•

%f:

Mik

rose

kund

en•

%H

:Stu

nden

im24

-Stu

nden

-Fo

rmat

•%

M:M

inut

en•

%S:

Seku

nden

Page 253: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

11.3

Mod

ulge

topt

Funk

tione

nin

nerh

alb

vongetopt

beha

ndel

nda

sTh

ema

Kom

man

doze

ilena

r-gu

men

te:

Funk

tion

Bed

eutu

ngge

topt

(Arg

umen

te,k

urze

Opt

ione

n,la

ngeO

ptio

nen)

Lie

stK

omm

ando

zeile

nopt

ione

n,w

iesi

ein

Arg

umen

teüb

erge

ben

wur

den

und

verg

leic

htsi

em

itku

r-ze

Opt

ione

n(-

f,-h

,...)

und

lang

e-O

ptio

nen

(--fi

le,-

-hel

p,...

).E

sw

erde

nzw

eiL

iste

nzu

rück

gege

-be

n,ei

neen

thäl

talle

empf

ange

nen

Opt

ione

nei

nsch

ließl

ich

derA

rgu-

men

te,d

iean

dere

Lis

teen

thäl

talle

Kom

man

doze

ilena

rgum

ente

,den

enke

ine

Opt

ion

vora

nges

tellt

wur

de.

Page 254: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

nggn

u_ge

topt

(Arg

umen

te,k

urze

-O

ptio

nen,

lang

eOpt

ione

n)W

ieob

en,j

edoc

hdü

rfen

Opt

ions

-un

dni

cht-

Opt

ions

argu

men

tege

-m

isch

twer

den.

langeOptionen

ist

optio

nal

und

enth

ält

eine

Lis

tem

itSt

ring

s,di

eal

sla

nge

Opt

ione

nin

terp

retie

rtw

erde

n.E

inna

chge

stel

ltes

Gle

ichh

eits

zeic

hen

bew

irkt

,da

ssdi

ese

Opt

ion

ein

Arg

umen

ter

war

tet.kurzeOptionen

ist

ein

Stri

ng,d

erdi

eB

uchs

tabe

nzu

den

pass

ende

nO

ptio

nen

bein

halte

t.E

inei

nem

Buc

hsta

ben

nach

gest

ellte

rDop

pelp

unkt

bew

irkt

,das

sdi

ese

Opt

ion

ein

Arg

umen

terw

arte

t.K

omm

ando

zeile

npar

amet

erw

erde

nty

pisc

herw

eise

von

der

Var

iabl

ensys.argv

bere

itges

tellt

,wob

eisys.argv[0]

derS

krip

tnam

eis

t.B

eisp

iel:

#!/usr/bin/python

import

getopt

import

sys

Page 255: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"Alle

Argumente:

",

sys.argv

shortOptions

='hf:'

longOptions

=['help',

'filename=',

'output=']

def

usage():

printsys.argv[0],

"--help

--filename=meinedatei

[--output=ausgabedatei]

..."

printsys.argv[0],

"-h

-f

meinedatei

..."

opts

=[]

args

=[]

try:opts,

args

=getopt.getopt(sys.argv[1:],

shortOptions,

longOptions)

except

getopt.GetoptError:

print"ERR:

Mindestens

eine

der

Optionen

ist

nicht

verfuegbar"

usage()

sys.exit()

print

"Optionenargumente:",

opts

print

"Nicht-Optionen-Argumente:",

args

for

o,

ain

opts:

Page 256: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ifo

==

"--help"

or

o==

"-h":

print"HELP"

usage()

elifo

==

"--filename"

or

o==

"-f":

print"Filename,

Bearbeite

Datei:",

aelifo

==

"--output":

print"Output,

Dateiname:",

a

for

ain

args:

print"Weiteres

Argument,

keine

Option:

",

a

Aus

gabe

userlocalhost:$̃./getopt1.py

--output

test

--filename

test1

-f

test2

test3

Alle

Argumente:

['./getopt1.py',

'--output',

'test',

'--filename',

'test1',

'-f',

'test2',

'test3']

Optionenargumente:

[('--output',

'test'),

('--filename',

'test1'),

('-f',

'test2')]

Nicht-Optionen-Argumente:

['test3']

Output,

Dateiname:

test

Filename,

Bearbeite

Datei:

test1

Page 257: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Filename,

Bearbeite

Datei:

test2

Weiteres

Argument,

keine

Option:

test3

Falls

eine

Opt

ion

eing

egeb

enw

urde

,die

nich

tBes

tand

teil

der

kurz

enod

erL

ange

nO

ptio

nslis

teis

t,da

nnw

ird

die

Exc

eptio

ngetopt.GetoptError

gew

orfe

n.D

ieO

ptio

nen-f

,--filename

und--output

erw

arte

nw

eite

reA

rgum

ente

.

11.4

Mod

ulm

ath

Das

Mod

ulm

ath

enth

ält

mat

hem

atis

che

Funk

tione

nun

dK

onst

ante

n.D

iefo

lgen

deTa

belle

zeig

tein

enA

usch

nitt:

Funk

tion

Bed

eutu

nge

Der

Wer

tder

Eul

erko

nsta

nte

2.71

8...

piD

erW

ertd

erK

reis

zahl

pi3.

14...

Page 258: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngsi

n(),

cos(

)Si

nus,

Kos

inus

eine

sW

inke

lsim

Bog

enm

aßde

gree

s()

Rec

hnet

eine

nW

inke

lvom

Bog

en-

maß

inG

rad

umra

dian

s()

Um

rech

nung

Gra

d->

Bog

enm

aßlo

g(),

exp(

)L

ogar

ithm

us,E

xpon

entia

lfun

ktio

n

Ein

Bei

spie

l:

#!/usr/bin/python

import

math

print

math.e

print

math.sin(math.pi/2)

Aus

gabe

userlocalhost:$̃./math.py

Page 259: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

2.71828182846

1.0 11.5

Mod

ulos

Die

ses

Mod

ulbe

inha

ltetV

aria

blen

und

Funk

tione

n,di

est

ark

vom

eing

eset

zten

Bet

rieb

ssys

tem

(Lin

ux,M

ac,O

penB

SD,.

..)ab

häng

en.

Bei

spie

l:

#!/usr/bin/python

import

os

print

"Arbeite

unter

"+

os.name

print

"Dieses

Programm

ist

unter

"+

os.curdir

+os.sep

+"ostest"

+os.extsep

+"py"

+"

zu

erreichen"

Page 260: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./ostest.py

Arbeite

unter

posix

Dieses

Programm

ist

unter

./ostest.py

zu

erreichen

Anm

erku

ng:

Die

ses

Prog

ram

mgi

btun

ter

vers

chie

dene

nB

etri

ebss

yste

men

unte

rsch

iedl

iche

Erg

ebni

sse

aus.

Hie

rfol

gen

eini

genü

tzlic

heFu

nktio

nen

aus

dem

Mod

ul:

11.5

.1D

atei

enun

dVe

rzei

chni

sse

Funk

tion

Bed

eutu

ngch

dir(

pfad

)W

echs

elti

nda

san

gege

bene

Ver

-ze

ichn

isch

mod

(pfa

d,m

odus

nder

tdie

Mod

i(L

esen

,Sch

rei-

ben,

Aus

führ

en)d

erD

atei

mit

dem

Dat

eina

men

pfad

.

Page 261: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngch

own(

pfad

,uid

,gid

nder

tdie

Bes

itzre

chte

derD

atei

mit

dem

Nam

enpf

adau

fdie

der

ange

gebe

nen

UID

und

GID

clos

e()

Dat

eiw

ird

gesc

hlos

sen

curd

ir,pa

rdir

(Kon

stan

ten)

Kür

zelf

ürda

sak

-tu

elle

Ver

zeic

hnis

(mei

st".

")od

erda

süb

erge

ordn

ete

Ver

zeic

hnis

(".."

)ge

tcw

d()

Lie

fert

das

aktu

elle

Arb

eits

ver-

zeic

hnis

listd

ir(p

fad)

Erz

eugt

eine

Lis

tem

itde

mIn

halt

des

ange

gebe

nen

Ver

zeic

hnis

ses

pfad

.

Page 262: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngls

eek(

fd,p

os,h

ow)

Posi

tioni

ertd

enD

atei

zeig

erde

rge

öffn

eten

Dat

eifd

andi

ePo

sitio

npo

s.ho

wbe

stim

mt,

wie

posi

tio-

nier

twir

d:•

SEE

K_S

ET:

rela

tivzu

mA

nfan

gde

rDat

ei(v

orei

nges

tellt

)•

SEE

K_C

UR

:rel

ativ

zura

ktue

l-le

nPo

sitio

n•

SEE

K_E

ND

:rel

ativ

zum

End

ede

rDat

ei

nam

e(K

onst

ante

n)K

ennu

ngfü

rdas

Bet

rieb

ssys

tem

(pos

ix,o

s2,r

isco

s,...

)

Page 263: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngop

en(fi

le,fl

ags[

,mod

e])

file:

Dat

eina

me,

flags

:Mod

ider

Art

•O

_RD

ON

LY:n

urL

esen

•O

_WR

ON

LY:n

ursc

hrei

ben

•O

_RD

WR

:les

enun

dsc

hrei

ben

•O

_APP

EN

D:a

nhän

gen

•O

_CR

EA

T:D

atei

wir

der

zeug

t•

O_E

XC

L:D

atei

wir

der

zeug

t,w

enn

essi

eno

chni

chtg

ibt.

Falls

esdi

eD

atei

gibt

,lie

fert

open

()ei

nen

Fehl

er.

•O

_TR

UN

C:D

atei

wir

dge

leer

tD

iese

Flag

skö

nnen

vero

dert

wer

-de

n.m

ode:

Dat

eire

chte

,wie

z.B

."0

660"

Page 264: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngre

ad(f

d,n)

Lie

stn

Zei

chen

aus

dero

ffen

enD

atei

fd.

rem

ove(

pfad

),rm

dir(

pfad

)E

ntfe

rnte

ine

Dat

eiod

erei

nV

er-

zeic

hnis

(rek

ursi

v).

wri

te(f

d,s)

Schr

eibt

eine

nSt

ring

sin

die

offe

-ne

Dat

eifd

.se

p,ex

tsep

(Kon

stan

ten)

Tren

nzei

chen

für

Pfad

nam

en("

/")u

ndD

atei

endu

n-ge

n("

.")

tmpfi

le()

Öff

nete

ine

tem

porä

reD

atei

imM

odus

"w+"

11.5

.2Pr

ozes

sman

agem

ent

Funk

tion

Bed

eutu

ng

Page 265: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngfo

rk()

Erz

eugt

eine

nK

indp

roze

ss.L

ie-

fert

0,w

enn

dies

esde

rKin

dpro

-ze

ssis

t,so

nstd

iePr

ozes

snum

mer

(PID

)des

Kin

des.

kill(

pid,

sign

al)

Send

etda

sSi

gnal

sign

alan

den

Proz

ess

mit

dera

ngeg

eben

enpi

d.ni

ce(w

ert)

Fügt

dem

aktu

elle

nPr

ozes

sde

nN

icew

ertw

erth

inzu

.sy

stem

(bef

ehl)

Führ

tein

enex

tern

enB

efeh

laus

.

11.6

Mod

ulos

.pat

h

Die

ses

Mod

ulen

thäl

tFu

nktio

nen,

die

Aus

kunf

tüb

erD

atei

enge

ben.

Man

kann

Änd

erun

g-un

dZ

ugri

ffsz

eite

nab

frag

en,f

ests

telle

n,ob

ein

Pfad

eine

(exi

stie

rend

e)D

atei

oder

ein

Ver

zeic

hnis

istu

ndvi

eles

meh

r.

Page 266: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngex

ists

(Pfa

d)L

iefe

rtTrue

,wen

nP

fad

exis

tiert

und

das

Prog

ram

mda

sR

echt

hat,

dies

enPf

adei

nzus

ehen

.ex

pand

user

(˜us

erna

me)

Erz

eugt

eine

nPf

ad,d

erda

sH

ome-

Ver

zeic

hnis

von

Ben

utze

ruse

rna-

me

ist.

geta

time(

Pfad

),ge

tmtim

e(Pf

ad)

Lie

fert

die

letz

teZ

ugri

ffsz

eito

der

die

Änd

erun

gsze

itis

file(

Pfad

)True

,wen

nde

rPfa

dei

neD

atei

dars

tellt

join

(Pfa

d1,P

fad2

,...)

Fügt

Pfad

ezu

sam

men

,wob

eiP

fad1

ein

Ver

zeic

hnis

sein

kann

,P

fad2

ein

Ver

zeic

hnis

inne

rhal

bvo

nP

fad1

oder

eine

Dat

ei.

Page 267: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

11.7

Mod

ulra

ndom

Das

Mod

ulra

ndom

stel

ltZu

falls

funk

tione

nzu

rVer

fügu

ng.E

inkl

eine

sBei

spie

lw

ürfe

ltei

neZ

ahlz

wis

chen

1un

d6:

#!/usr/bin/python

from

random

import

randint

#Zufallszahl

ermitteln

und

als

Wuerfelergebnis

nehmen.

def

print_random():

wuerfel

=randint(1,

6)

print"Der

Wurf

ergibt

"+

str(wuerfel)

#5mal

wuerfeln

for

iin

range(0,

5):

print_random()

Aus

gabe

userlocalhost:$̃./wuerfeln.py

Der

Wurf

ergibt

2

Page 268: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Der

Wurf

ergibt

6

Der

Wurf

ergibt

5

Der

Wurf

ergibt

6

Der

Wurf

ergibt

2

Anm

erku

ng:D

iese

sPr

ogra

mm

gibt

jede

sm

alan

dere

Erg

ebni

sse

aus.

11.8

Mod

ulre

adlin

e

Mit

dem

Mod

ulre

adlin

eka

nnei

neA

utov

ervo

llstä

ndig

ung

imSt

ilde

rBas

hin

die

Text

eing

abe

eing

ebau

twer

den.

Mit

eine

rgee

igne

ten

Funk

tion

zurV

er-

volls

tänd

igun

gan

gefa

ngen

erW

örte

rbra

ucht

man

nurn

och

die

Tabu

lato

rtas

tedr

ücke

n,um

bere

itsei

ndeu

tige

Ein

gabe

nzu

verv

olls

tänd

igen

.

Page 269: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

11.9

Mod

ulsy

s

Hie

rfol

gtei

neA

usw

ahli

nter

essa

nter

Funk

tione

nun

dVa

riabl

enin

nerh

alb

vom

Mod

ulsy

s.

Funk

tion

Bed

eutu

ngar

gvL

iste

von

Kom

man

doze

ilen,

die

dem

Skri

ptm

itgeg

eben

wur

den

exit(

Arg

)D

erop

tiona

leW

ertA

rgw

ird

aus-

gege

ben,

oder

,wen

nes

eine

Zah

lis

t,an

den

aufr

ufen

den

Proz

ess

(zum

Bei

spie

ldie

bash

)übe

rgeb

en.

exitf

unc

Die

seV

aria

ble

enth

ältd

enW

ert

eine

rFun

ktio

n,di

eal

sle

tzte

vor

dem

Prog

ram

men

deau

fger

ufen

wir

d.pa

thL

iste

alle

rMod

ulsu

chpf

ade

Page 270: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngpl

atfo

rmE

inSt

ring

,der

die

Plat

tfor

m,a

lso

das

Bet

rieb

ssys

tem

,ide

ntifi

zier

t.st

din

Ein

gabe

kana

l(D

atei

)ve

rsio

nD

ieak

tuel

lePy

thon

-Ver

sion

Ein

Bei

spie

lpro

gram

m,w

iem

anm

itexit()

undexitfunc

umge

ht:

#!/usr/bin/python

import

sys

def

LetzteWorte():

print"Das

Gold

befindet

sich

am

..."

exitfunc

=LetzteWorte()

sys.exit(42)

Page 271: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./sys1.py

Das

Gold

befindet

sich

am

...

Lei

derv

erst

arb

das

Prog

ram

m,b

evor

esun

sde

nO

rtne

nnen

konn

te,w

oda

sG

old

liegt

.Wir

könn

ende

nR

ückg

abew

ertd

esSk

ripte

sin

derb

ash

best

imm

en,

inde

mw

irdi

eSh

ell-

Var

iabl

e$?

abfr

agen

:

Aus

gabe

userlocalhost:$̃echo

$?

42 Das

folg

ende

Prog

ram

mbe

nutz

tstdin

,um

eine

nFi

lterz

uba

uen.

Mit

dess

enH

ilfe

könn

enw

irdi

eA

usga

beei

nes

Prog

ram

mes

als

Eing

abe

unse

res

Prog

ram

-m

esbe

nutz

en,u

mzu

mB

eisp

ielD

atei

enm

itZ

eile

nnum

mer

nzu

vers

ehen

:

#!/usr/bin/python

import

sys

Page 272: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

for

n,

lin

enumerate(sys.stdin):

print"%d:

%s"

%(n,

l[:-1])

Aus

gabe

userlocalhost:$̃./sys2.py

<sys2.py

0:

#!/usr/bin/python

1:

import

sys

2:

3:

for

n,

lin

enumerate(sys.stdin):

4:

print

"%d:

%s"

%(n,

l[:-1])

Alte

rnat

ivhä

tten

wir

das

Prog

ram

mau

chm

itcatsys2.py|

./sys2.py

aufr

ufen

könn

en.

Page 273: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

11.1

0M

odul

tarfi

le

Das

Mod

ulta

rfile

erm

öglic

htdi

eB

ehan

dlun

gvo

n\.t

ar(\

.gz|

\.bz2

)?-D

atei

enun

terP

ytho

n.E

inB

eisp

iel:

#!/usr/bin/python

from

sys

import

argv

import

tarfile

filename=argv[0]

tarname=filename+".tar.gz"

tar=tarfile.open(tarname,

"w:gz")

tar.add(filename)

tar.close()

file=open(filename)

file.seek(0,

2)

tar=open(tarname)

tar.seek(0,

2)

print

"Original:

"+

str(file.tell())

+"

Bytes"

print

"Compressed:

"+

str(tar.tell())

+"

Bytes"

Page 274: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#Noch

ein

paar

Kommentare,

damit

die

Datei

gross

genug

ist.

:-)

#Bei

zu

kleinen

Dateien

wirkt

sich

die

Kompression

negativ

aus.

Aus

gabe

userlocalhost:$̃./tar.py

Original:

464

Bytes

Compressed:

403

Bytes

11.1

1M

odul

time

Das

Mod

ultim

est

ellt

Funk

tione

nfü

rdas

Rec

hnen

mit

Zei

tzur

Ver

fügu

ng.E

sso

llte

nich

tmit

derK

lass

etime

imM

odul

date

time

verw

echs

eltw

erde

n.E

inB

eisp

ielp

rogr

amm

:

#!/usr/bin/python

from

time

import

clock,

strftime

Page 275: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def

do_loop(limit):

start_time=clock()

fori

in

range(1,limit):

forj

in

range(1,limit):

pass

end_time=clock()

returnend_time

-start_time

def

calibrate():

limit=1

elapsed=0.0

while(elapsed<1.0):

limit=limit*2

elapsed=do_loop(limit)

returnlimit

print

'Kalibriere

Zeitrechnung...'

limit

=calibrate()

print

'Rechne

('

+str(limit)

+')^2

Schleifen...'

print

'Vorher:

'+

strftime('%X')

elapsed=do_loop(limit)

print

'Nachher:

'+

strftime('%X')

Page 276: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print

"Gemessene

Zeit:

"+

str(elapsed)

+"s"

Aus

gabe

userlocalhost:$̃./timing.py

Kalibriere

Zeitrechnung...

Rechne

(4096)ˆ2

Schleifen...

Vorher:

17:14:57

Nachher:

17:14:58

Gemessene

Zeit:

1.16s

11.1

2M

odul

uu

Das

folg

ende

Prog

ram

mko

dier

tund

deko

dier

tsic

hse

lbst

:

#!/usr/bin/python

from

sys

import

argv

Page 277: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

from

uu

import

encode,

decode

infile=argv[0]

tmpfile=infile+".uu"

outfile=tmpfile+".py"

encode(infile,

tmpfile)

decode(tmpfile,

outfile)

file=open(outfile)

data=file.read()

lines=data.splitlines()

for

line

in

lines:

printline

Die

Aus

gabe

soll

hier

nich

tex

tra

aufg

efüh

rtw

erde

n,da

sie

iden

tisch

mit

dem

Prog

ram

mco

deis

t.Fü

rdi

eIn

tere

ssie

rten

hier

die

dabe

ierz

eugt

eD

atei

uudemo.py.uu

:

begin

755

uudemo.py

M(R$O=7-R+V)I;B]P>71H;VX*9G)O;2!S>7,@:6UP;W)T(&%R9W8*9G)O;2!U

M=2!I;7!O<G0@96YC;V1E+"!D96-O9&4*"FEN9FEL93UA<F=V6S!="G1M<&9I

M;&4]:6YF:6QE*R(N=74B"F]U=&9I;&4]=&UP9FEL92LB+G!Y(@H*96YC;V1E

Page 278: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

M*&EN9FEL92P@=&UP9FEL92D*9&5C;V1E*'1M<&9I;&4L(&]U=&9I;&4I"@IF

M:6QE/6]P96XH;W5T9FEL92D*9&%T83UF:6QE+G)E860H*0IL:6YE<SUD871A

M+G-P;&ET;&EN97,H*0IF;W(@;&EN92!I;B!L:6YE<SH*("

@("!P<FEN="!L

$:6YE"@

end

11.1

3A

llgem

eine

Info

rmat

ione

nüb

erM

odul

e

Das

folg

ende

Skri

ptze

igt,

wie

man

meh

rüb

erei

nM

odul

hera

usfin

det,

von

dem

man

nurd

enN

amen

kenn

t.

#!/usr/bin/python

import

os

help(os)

print

dir(os)

Page 279: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

Funk

tione

nhelp()

unddir()

gebe

nnü

tzlic

heIn

form

atio

nen

über

die

Mod

ule

aus.

Es

istr

echt

prak

tisch

,sie

imin

tera

ktiv

enM

odus

(sie

heK

apite

lE

rste

Schr

itte2 )e

inzu

gebe

n.

11.1

4A

nmer

kung

en

2K

apite

l2.1

aufS

eite

7

Page 280: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

12X

ML

WA

RN

UN

G: D

iese

sK

apite

list

volls

tänd

igve

ralte

tund

sollt

eer

setz

tode

ren

tfer

ntw

erde

n.E

sbe

schr

eibt

nich

tdie

aktu

ellz

umei

stve

rwen

dete

nX

ML

-B

iblio

thek

enE

lem

entT

ree1

und

lxm

l2 ,so

nder

nda

säl

tere

,lan

gsam

eun

dse

hrsp

eich

erin

tens

ive

Min

iDO

M-P

aket

und

die

kom

pliz

iert

zuve

rwen

dend

eSA

X-B

iblio

thek

.Die

sen

gege

nübe

rbie

ten

Ele

men

tTre

eun

dlx

ml

sehr

hohe

Ges

chw

indi

gkei

t3un

dSp

eich

eref

fizie

nz4 ,

leic

hter

eB

edie

nbar

keit

und

eine

1http://docs.python.org/library/xml.etree.elementtree.html

2http://lxml.de/

3http://lxml.de/performance.html

4http://effbot.org/zone/celementtree.htm

269

Page 281: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

wes

entli

chhö

here

Abd

ecku

ngvo

nX

ML-

Stan

dard

sund

-Fea

ture

s(z.

B.V

alid

ie-

rung

,XPa

thod

erX

SLT

).W

ähre

ndes

fürS

AX

zum

inde

stno

chei

nige

wen

ige

vertr

etba

reA

nwen

dung

sfäl

legi

bt,s

ollte

neu

gesc

hrie

bene

rCod

ein

sbes

onde

reni

chtm

ehrM

iniD

OM

verw

ende

n.

12.1

Ein

leitu

ng

XM

Lis

tein

eA

usze

ichn

ungs

spra

che,

mit

ders

ich

ande

reSp

rach

ende

finie

ren

lass

en.E

benf

alls

nutz

tman

XM

L,u

mhi

erar

chis

chge

glie

dert

eD

okum

ente

zuer

zeug

en.M

ehrü

berX

ML

finde

tsic

hin

den

Wik

iboo

ksX

ML

5un

dX

SLT

6 .E

ine

der

Spra

chen

,die

mit

Hilf

evo

nX

ML

defin

iert

wur

den

ist

XH

TM

L

5http://de.wikibooks.org/wiki/Websiteentwicklung%3A%20XML%

20

6http://de.wikibooks.org/wiki/Websiteentwicklung%3A%20XSLT%

20

Page 282: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

(HT

ML

)7 .D

iese

sK

apite

ldec

ktTe

ilede

rX

ML

-Mod

ule

ab,d

iem

itPy

thon

mitg

elie

fert

wer

den.

Wen

nSi

ehö

herw

ertig

eA

nwen

dung

enm

itSc

hem

ata

und

Nam

espa

ces

benö

tigen

,sol

lten

Sie

sich

das

Mod

ulpy

thon

-lib

xml2

ansc

haue

n.E

slä

ssts

ich

mit

den

Pake

tver

wal

tung

stoo

lsih

rer

Lin

ux-D

istr

ibut

ion

leic

htin

stal

liere

n.

12.2

XM

L-D

okum

ente

rzeu

gen

Das

folg

ende

Bei

spie

lerz

eugt

ein

XM

L-D

okum

entu

ndgi

btes

form

atie

rtau

s.W

irbe

nutz

enhi

erzu

das

Mod

ulxml.dom

.Das

Dok

umen

tent

hält

drei

Kno

ten

(Nod

eod

erE

lem

ent

gena

nnt)

,da

sei

gent

liche

Dok

umen

t,Test1

-Kno

ten,

eine

nK

note

nna

men

sHello

,der

ein

Attr

ibut

träg

tund

eine

nTe

xtkn

oten

:

#!/usr/bin/python

7http://de.wikibooks.org/wiki/Websiteentwicklung%3A%

20XHTML%20

Page 283: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#-*-

coding:

utf-8

-*-

import

xml.dom

#Dokument

erzeugen

implement

=xml.dom.getDOMImplementation()

doc

=implement.createDocument(None,

"Test1",

None)

#Child

Element

"Hello"

elem

=doc.createElement("Hello")

elem.setAttribute("output",

"yes")

text

=doc.createTextNode("Hello,

World!")

elem.appendChild(text)

#Child

an

Dokument

anhängen

doc.documentElement.appendChild(elem)

#Ausgeben

print

doc.toprettyxml()

Aus

gabe

userlocalhost:$̃./xml1.py

Page 284: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

<?xml

version="1.0"

?>

<Test1>

<Hellooutput="yes">

Hello,

World!

</Hello>

</Test1>

Mitxml.dom.getDOMImplementation()

besc

haff

enw

irun

sIn

for-

mat

ione

nüb

erdi

eak

tuel

leX

ML

-Im

plem

enta

tion.

Opt

iona

lkö

nnen

wir

mit

der

Funk

tion

Eig

ensc

haft

enan

ford

ern,

esw

ürde

dann

eine

pass

ende

Impl

emen

tatio

nhe

raus

gesu

cht.

Die

seIm

plem

enta

tion

benu

tzen

wir,

umei

nei

gene

sD

okum

ent

mit

dem

soge

nann

ten

Roo

t-E

lem

ent

zuer

zeug

en:

createDocument()

.Die

serF

unkt

ion

könn

ten

wir

noch

den

Nam

espa

ceun

dde

nD

okum

ente

ntyp

mitt

eile

n.

Hab

enw

irei

nD

okum

ente

rzeu

gt,k

önne

nw

irm

itcreateElement()

nach

Bel

iebe

nne

ueE

lem

ente

erst

elle

n.K

note

nkö

nnen

Attr

ibut

eha

ben,

die

man

mitsetAttribute()

inda

sEl

emen

tein

fügt

.Wird

ein

Elem

ente

rste

llt,s

ow

ird

esni

chts

ofor

tin

das

Dok

umen

tein

gefü

gt.appendChild()

erle

digt

dies

.

Page 285: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

createTextNode()

erze

ugt

eine

nsp

ezie

llen

Kno

ten,

der

nur

aus

Text

best

eht.

Die

serk

ann

kein

ew

eite

ren

Attr

ibut

eha

ben.

Das

Roo

t-E

lem

enth

olt

man

sich

mitdoc.documentElement

,an

dies

eska

nnm

anzu

mSc

hlus

sde

nE

lem

ente

-Bau

man

häng

en.

XM

L-D

okum

ente

möc

hte

man

auch

auf

die

Fest

plat

tesc

hrei

ben.

Das

fol-

gend

eB

eisp

ieli

mpl

emen

tiert

eine

Adr

esse

nein

gabe

.Läs

stm

ande

nN

amen

beid

erE

inga

bele

er,s

ow

ird

die

Ein

gabe

abge

broc

hen,

das

XM

L-D

okum

ent

ausg

egeb

en.B

itte

beac

hten

Sie,

dass

die

Dat

eibe

ijed

emA

ufru

fübe

rsch

rie-

ben

wir

d.E

sso

llte

sich

also

nach

Mög

lichk

eit

kein

ean

dere

wic

htig

eD

a-te

igl

eich

enN

amen

sim

Ver

zeic

hnis

befin

den.

Das

Bei

spie

lpro

gram

mer

-ze

ugte

inen

Bau

m,d

er<Adressen>

bein

halte

t.Je

dedi

eser

Adr

esse

nw

ird

durc

hei

nen<Adresse>

-Kno

ten

repr

äsen

tiert

,in

dem

sich

<Name>

-und

<Anschrift>

-Kno

ten

befin

den.

Als

Bes

onde

rhei

twird

noch

ein

Kom

men

-ta

rin

jede

sA

dres

senf

eld

gesc

hrie

ben:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

Page 286: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

import

xml.dom

#Dokument

erzeugen

implement

=xml.dom.getDOMImplementation()

doc

=implement.createDocument(None,

"Adressen",

None)

while

True:

#Namen

holen,

ist

er

leer

dann

Abbruch

name_text

=raw_input("Name

der

Person:

")

ifname_text

==

"":break

#Kommentar

kommentar_text

="Adresse

von

%s"

%(name_text)

commentNode

=doc.createComment(kommentar_text)

#neues

Adresse-Elemen

adresseElem

=doc.createElement("Adresse")

adresseElem.appendChild(commentNode)

#Name

anfügen

nameElem

=doc.createElement("Name")

adresseElem.appendChild(nameElem)

nameTextElem

=doc.createTextNode(name_text)

nameElem.appendChild(nameTextElem)

#Anschrift

anschrift_text

=raw_input("Anschrift:

")

Page 287: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

anschriftElem

=doc.createElement("Anschrift")

adresseElem.appendChild(anschriftElem)

anschriftTextElem

=doc.createTextNode(anschrift_text)

anschriftElem.appendChild(anschriftTextElem)

#Anhängen

an

Dokument

doc.documentElement.appendChild(adresseElem)

#Ausgeben

datei

=open("testxml2.xml",

"w")

doc.writexml(datei,

"\n",

"")

datei.close()

Sokö

nnte

beig

eeig

nete

rEin

gabe

die

Dat

eitestxml2.xml

auss

ehen

:

Aus

gabe

userlocalhost:$̃cat

testxml2.xml

<?xml

version="1.0"

?>

<Adressen>

<Adresse>

<!--Adresse

von

Sir

Spamalot-->

<Name>

Sir

Spamalot

</Name>

Page 288: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

<Anschrift>

Spamhouse

123

</Anschrift>

</Adresse>

<Adresse>

<!--Adresse

von

Lady

of

the

Lake-->

<Name>

Lady

of

the

Lake

</Name>

<Anschrift>

West

End

23

</Anschrift>

</Adresse>

<Adresse>

<!--Adresse

von

Brian-->

<Name>

Brian

</Name>

<Anschrift>

Im

Flying

Circus

</Anschrift>

</Adresse>

</Adressen>

Page 289: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

ses

Bei

spie

lent

hält

vers

chac

htel

teEl

emen

te.E

sw

irdna

chN

amen

und

An-

schr

iftge

frag

t,da

zuw

erde

npa

ssen

deK

note

ner

zeug

tund

anei

nand

erge

häng

t.N

ach

derE

inga

bede

sN

amen

ser

zeug

tcreateComment()

eine

nK

omm

en-

tar,

der

eben

falls

mitappendChild()

ange

häng

tw

erde

nka

nn.

Neu

ist,

dass

wir

das

erze

ugte

Dok

umen

tsch

reib

en.D

azu

nutz

enw

irwritexml()

,w

elch

eei

neof

fene

Dat

eier

war

tet.

Auß

erde

mge

ben

wir

noch

die

Art

derE

in-

rück

ung

mit:

Zwis

chen

zwei

Elem

ente

nso

llei

nene

ueZe

ileei

ngef

ügtw

erde

n,je

zwei

Ele

men

t-E

bene

nso

llen

durc

hL

eerz

eich

enge

tren

ntw

erde

n.

12.3

XM

Lle

sen

Ein

eX

ML

-Dat

eika

nnm

anbe

quem

mit

den

Funk

tione

nvo

nxml.dom.minidom

,ei

ner

"lei

chtg

ewic

htig

en"

Impl

emen

tatio

nvo

nX

ML

lese

n.H

ierz

unu

tzen

wir

eine

reku

rsiv

eFu

nktio

n,um

uns

alle

Kno

ten

ausz

ugeb

en.

Page 290: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

xml.dom.minidom

datei

=open("testxml2.xml",

"r")

dom

=xml.dom.minidom.parse(datei)

datei.close()

def

dokument(domina):

fornode

in

domina.childNodes:

print"NodeName:",

node.nodeName,

ifnode.nodeType

==

node.ELEMENT_NODE:

print

"Typ

ELEMENT_NODE"

elifnode.nodeType

==

node.TEXT_NODE:

print

"Typ

TEXT_NODE,

Content:

",

node.nodeValue.strip()

elifnode.nodeType

==

node.COMMENT_NODE:

print

"Typ

COMMENT_NODE,

"dokument(node)

dokument(dom)

Page 291: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./xml3.py

NodeName:

Adressen

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Adresse

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

#comment

Typ

COMMENT_NODE,

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Name

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

Sir

Spamalot

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Anschrift

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

Spamhouse

123

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Adresse

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

#comment

Typ

COMMENT_NODE,

Page 292: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Name

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

Lady

of

the

Lake

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Anschrift

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

West

End

23

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Adresse

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

#comment

Typ

COMMENT_NODE,

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Name

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

Brian

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

Anschrift

Typ

ELEMENT_NODE

NodeName:

#text

Typ

TEXT_NODE,

Content:

Im

Flying

Circus

Page 293: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

NodeName:

#text

Typ

TEXT_NODE,

Content:

NodeName:

#text

Typ

TEXT_NODE,

Content:

Die

Übe

rras

chun

gdü

rfte

groß

sein

.In

eine

rso

klei

nen

Text

date

iw

er-

den

sovi

ele

Kno

ten

gefu

nden

.D

erA

ussp

ruch

"Man

sieh

tde

nW

ald

vor

laut

erB

äum

enni

cht

meh

r"dü

rfte

hier

pass

en.

ImPr

ogra

mm

wir

dm

itxml.dom.minidom.parse()

eine

offe

neD

atei

gele

sen.

Die

Funk

tion

dokument()

wird

mit

jede

mK

inde

lem

ent,

das

mitchildNodes

erm

ittel

tw

ird,n

euau

fger

ufen

.Kin

derk

önne

nEl

emen

te,w

ie<Adresse>

oder

Kom

-m

enta

reod

erbe

liebi

ger

Text

sein

.Bel

iebi

gen

Text

,in

der

Aus

gabe

ande

nSt

elle

nm

it#text

zuer

kenn

en,h

aben

wir

alle

ine

dadu

rch

rech

toft

,da

wir

den

Text

mit

Ein

rück

ungs

zeic

hen

(Ind

ent)

beim

Spei

cher

nge

füllt

habe

n.N

urse

hrw

enig

eTEXT_NODE

-Zei

len

steh

enhi

erbe

ifür

sinn

volle

nTe

xt,a

llean

de-

ren

sind

Kno

ten,

die

nurw

egen

derL

eerz

eich

enun

dN

ewlin

e-Z

eich

en(\n

)hi

nein

gesc

hrie

ben

wur

den.

Da

wirstrip()

bei

jede

rA

usga

bebe

nutz

en,

sehe

nw

irvo

ndi

esen

Zei

chen

nich

ts.

Page 294: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Um

nur

die

inte

ress

ante

nE

lem

ente

ausz

ugeb

en,

müs

sen

wir

die

Stru

ktur

berü

cksi

chtig

en.W

irla

ssen

alle

sau

ßer

Ach

t,w

asni

cht

zum

gew

ünsc

hten

Ele

men

tinha

ltpa

sst:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

xml.dom.minidom

datei

=open("testxml2.xml",

"r")

dom

=xml.dom.minidom.parse(datei)

datei.close()

def

liesText(pretext,

knoten):

fork

in

knoten.childNodes:

ifk.nodeType

==

k.TEXT_NODE:

print

pretext,

k.nodeValue.strip()

def

liesAdressen(knoten):

fornum,

elem

in

enumerate(knoten.getElementsByTagName("Adresse")):

print"%d.

Adresse:"

%(num

+1)

forknotenNamen

in

elem.getElementsByTagName("Name"):

Page 295: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

liesText("Name:",

knotenNamen)

forknotenAnschrift

in

elem.getElementsByTagName("Anschrift"):

liesText("Anschrift:",

knotenAnschrift)

print

def

dokument(start):

forelem

in

start.getElementsByTagName("Adressen"):

liesAdressen(elem)

dokument(dom)

Aus

gabe

userlocalhost:$̃./xml4.py

1.

Adresse:

Name:

Sir

Spamalot

Anschrift:

Spamhouse

123

2.

Adresse:

Name:

Lady

of

the

Lake

Anschrift:

West

End

23

3.

Adresse:

Page 296: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Name:

Brian

Anschrift:

Im

Flying

Circus

Die

seA

usga

beis

twes

entli

chnü

tzlic

her.

MitgetElementsByTagName()

könn

enw

irfü

rdie

inte

ress

ante

nTa

gsal

leK

inde

lem

ente

hole

n.In

derF

unkt

ion

dokument()

wird

sofü

rden

Adr

esse

n-Ta

g,da

sRoo

t-Ele

men

t,ge

nau

einm

aldi

eFu

nktio

nliesAdressen()

aufg

eruf

en.

Die

seFu

nktio

ner

zeug

tdi

eei

gent

liche

Adr

esse

naus

gabe

.Es

wir

dda

bei

über

alleAdresse

-Ele

men

teite

rier

t,da

Kin

dele

men

tevo

nAdresse

nurName

undAnschrift

sein

könn

en,w

erde

ndi

ese

inde

rFun

ktio

neb

enfa

llsve

rarb

eite

t.A

lleTe

xtel

emen

tew

erde

nvo

nliesText()

bear

beite

t.

12.4

SAX

SAX

iste

inEr

eign

is-b

asie

rend

esPr

otok

ollz

umLe

sen

von

XM

L-D

okum

ente

n.Je

des

Mal

,wen

nei

nE

reig

nis

auft

ritt,

zum

Bei

spie

lein

Ele

men

tgel

esen

wir

d,w

ird

eine

Met

hode

aufg

eruf

en,d

iedi

eses

Ere

igni

sbe

hand

elt.

And

ers

als

bei

Page 297: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

DO

Mkö

nnen

sose

hrla

nge

XM

L-D

okum

ente

gele

sen

wer

den,

die

wes

entli

chgr

ößer

sind

als

derz

urV

erfü

gung

steh

ende

Spei

cher

.Das

folg

ende

Bei

spie

lze

igt,

wie

man

eine

nH

andl

erer

stel

lt,de

rauf

eini

geEr

eign

isse

reag

iere

nka

nn:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

xml.sax

class

MiniHandler(xml.sax.handler.ContentHandler):

defstartDocument(self):

print"ANFANG"

defendDocument(self):

print"ENDE"

defstartElement(self,

name,

attrs):

print"Element",

name

defcharacters(self,

content):

s=

content.strip()

ifs

!=

"":

print

"Textinhalt:",

s

Page 298: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

handler

=MiniHandler()

datei

=open("testxml2.xml",

"r")

xml.sax.parse(datei,

handler)

datei.close()

Aus

gabe

userlocalhost:$̃./xml5.py

ANFANG

Element

Adressen

Element

Adresse

Element

Name

Textinhalt:

Sir

Spamalot

Element

Anschrift

Textinhalt:

Spamhouse

123

Element

Adresse

Element

Name

Textinhalt:

Lady

of

the

Lake

Element

Anschrift

Page 299: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Textinhalt:

West

End

23

Element

Adresse

Element

Name

Textinhalt:

Brian

Element

Anschrift

Textinhalt:

Im

Flying

Circus

ENDE

xml.sax.handler.ContentHandler

ist

die

Bas

iskl

asse

für

eige

-ne

Han

dler

.In

davo

nab

gele

itete

nK

lass

enw

erde

nei

nige

Ere

igni

sse

wie

startDocument()

neu

defin

iert

,um

sopa

ssen

dzu

rA

nwen

dung

dar-

auf

reag

iere

nzu

könn

en.

Inun

sere

mB

eisp

iel

gebe

nw

irdi

eM

eldu

ngen

aus.

Ein

eIn

stan

zde

sMiniHandler

sw

ird,

nebe

nde

rof

fene

nD

atei

,xml.sax.parse()

mitg

egeb

en.D

asD

okum

entw

ird

sukz

essi

veve

rarb

ei-

tet,

die

imMiniHandler

anla

ufen

den

Erei

gnis

sedo

rtbe

arbe

itet.

Die

sesi

ndse

lbst

vers

tänd

lich

nure

inA

uszu

gal

lerm

öglic

hen

Ere

igni

sse.

Page 300: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

12.5

Nüt

zlic

heH

elfe

r

Fürd

iese

nütz

liche

nH

elfe

rbin

detm

anda

sM

odul

xml.s

ax.s

axut

ilsei

n:

Funk

tion

Bed

eutu

nges

cape

(Dat

en[,

Ent

itäte

n])

Ers

etzt

inei

nem

Stri

ng"D

aten

"al

leVo

rkom

men

von

Sond

erze

iche

ndu

rch

imD

ictio

nary

ange

-ge

bene

Ent

itäte

n.Z

umB

eisp

iel<

durc

h&

lt;.

Ein

ige

Ent

itäte

nw

erde

noh

neei

ner

wei

tert

esE

ntitä

ten-

Ver

zeic

hnis

erse

tzt.

unes

cape

(Dat

en[,

Ent

itäte

n])

Wie

esca

pe()

,nur

umge

kehr

t.Fü

rein

Bei

spie

lsi

ehe

Kap

itelN

etzw

erk8 .

Sie

könn

enei

nfü

res

cape

()vo

rber

eite

tes

Ent

itäte

n-V

erze

ichn

ishi

erni

chtw

iede

rver

wen

den,

sond

ern

müs

sen

den

Inha

ltum

kehr

en.

8K

apite

l14.

2au

fSei

te30

7

Page 301: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

xml.sax.saxutils

as

util

buch

={'ä'

:'&auml;'}

print

util.escape("Anzahl

der

Männer

<Anzahl

aller

Menschen!",

buch)

Aus

gabe

userlocalhost:$̃./xml6.py

Anzahl

der

M&auml;nner

&lt;

Anzahl

aller

Menschen!

Hie

rbra

ucht

enw

irda

sE

ntitä

tenv

erze

ichn

isnu

rfür

die

Um

laut

e,da

sK

lein

er-

Zei

chen

wur

depe

rVor

gabe

erse

tzt.

Page 302: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

12.6

Zus

amm

enfa

ssun

g

Indi

esem

Kap

itelh

aben

Sie

eine

berb

lick

über

die

Mög

lichk

eite

nde

rVer

-ar

beitu

ngvo

nX

ML-

Dok

umen

ten

mit

den

mitg

elie

ferte

nM

odul

enbe

kom

men

.E

sw

urde

nTe

chni

ken

wie

DO

Mun

dSA

Xvo

rges

tellt

.Tie

fgre

ifen

dere

Tech

ni-

ken

wer

den

von

ande

ren

exte

rner

hältl

iche

nM

odul

enab

gede

ckt.

Die

selie

gen

auße

rhal

bde

rZie

lset

zung

dies

esB

uche

s.

Page 303: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 304: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

13D

aten

bank

en

Indi

esem

Kap

itelg

ehte

sum

die

Ans

teue

rung

von

Dat

enba

kman

agem

ents

ys-

tem

en,k

urz

DB

MS.

Sie

dien

enda

zu,D

aten

daue

rhaf

tzu

spei

cher

nun

dm

itH

ilfe

eine

rei

gene

nSp

rach

e,zu

mei

stSQ

L,s

elek

tivab

zufr

agen

.Im

Reg

alE

DV

beiW

ikib

ooks

1fin

den

Sie

eini

geB

üche

rzum

The

ma

Dat

enba

nken

und

SQL

.Wir

verw

ende

ndi

eB

egri

ffe

DB

MS

und

Dat

enba

nken

inde

nfo

lgen

den

Abs

chni

tten

syno

nym

.

1http://de.wikibooks.org/wiki/Regal%3AEDV%

23Datenbanksysteme%20

293

Page 305: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Wir

stel

len

eini

geD

aten

bank

syst

eme

voru

ndze

igen

kurz

,wie

dies

eSy

stem

ein

Pyth

onan

gest

euer

twer

den.

Es

geht

uns

hier

beii

nsbe

sond

ere

nich

tum

die

Dar

stel

lung

derA

bfra

gesp

rach

e.

13.1

SQL

ite

SQLi

teis

tein

eD

aten

bank

,die

aufe

iner

einz

elne

nD

atei

basi

ert.

Esm

uss

kein

Serv

erin

stal

liert

wer

den,

dafü

rist

esnu

rsch

wer

mög

lich,

dass

vers

chie

dene

Anw

endu

ngen

glei

chze

itig

auf

eine

Dat

enba

nkzu

grei

fen.

Für

Web

appl

ika-

tione

nei

gnet

sich

dies

esSy

stem

nich

tso

gut

wie

ande

rehi

ervo

rges

tellt

eD

aten

bank

syst

eme.

Daf

ürsi

ndD

aten

bank

ensc

hnel

lund

ohne

läst

igen

Bal

last

eing

eric

htet

.Der

Zug

riff

erfo

lgtm

itH

ilfe

eini

ger

wen

iger

API

-Fun

ktio

nen.

Das

folg

ende

Bei

spie

lleg

tein

eD

aten

bank

als

Dat

eian

,fra

gtde

nN

utze

rnac

hE

inga

ben

und

spei

cher

tdie

seE

inga

ben

inde

rDat

enba

nk.STRG-C

bric

htdi

eE

inga

beab

.

Page 306: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

encoding:

utf-8

-*-

import

sqlite3

con

=sqlite3.connect('sl1.db')

con.isolation_level

=None

con.execute("CREATE

TABLE

IF

NOT

EXISTS

tiere

(name

TEXT,

farbe

TEXT)")

try:whileTrue:

tier

=raw_input("(Abbruch

mit

STRG-C)

Sag

mir

mal

ein

Tier>

")

farbe

=raw_input("Welche

Farbe

hat

\"%s\"?

>"

%tier)

con.execute("INSERT

INTO

tiere(name,

farbe)

VALUES(?,

?)",

(tier,

farbe))

except:

print;print

rows

=con.execute("SELECT

*FROM

tiere")

print

"Meine

Lieblingstiere:"

Page 307: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

for

row

in

rows:

printrow[0],

"hat

die

Farbe",

row[1]

Aus

gabe

userlocalhost:$̃./sl1.py

(Abbruch

mit

STRG-C)

Sag

mir

mal

ein

Tier>

Maus

Welche

Farbe

hat

"Maus"?

>mausgrau

(Abbruch

mit

STRG-C)

Sag

mir

mal

ein

Tier>

Bär

Welche

Farbe

hat

"Bär"?

>braun

(Abbruch

mit

STRG-C)

Sag

mir

mal

ein

Tier>

Delfin

Welche

Farbe

hat

"Delfin"?

>blau-grau

(Abbruch

mit

STRG-C)

Sag

mir

mal

ein

Tier>STRG-C

Meine

Lieblingstiere:

Maus

hat

die

Farbe

mausgrau

Bär

hat

die

Farbe

braun

Delfin

hat

die

Farbe

blau-grau

Mitconnect()

wir

ddi

eV

erbi

ndun

gzu

eine

rSQ

Lite

3-D

atei

herg

este

llt.

Falls

kein

eD

atei

gew

ünsc

htw

ird,

kann

durc

hde

nPa

ram

eter:memory:

die

Page 308: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Dat

enba

nkau

chim

verf

ügba

ren

Spei

cher

ange

legt

wer

den.

Zur

ückg

egeb

enw

ird

ein

soge

nann

tes

"Con

nect

ion-

Obj

ect"

.

SQL

ite3

istt

rans

aktio

nsba

sier

t.W

irm

üsst

enbe

ialle

ndi

eD

aten

bank

ände

rn-

den

Zug

riff

enw

ieINSERT

einCommit

durc

hfüh

ren,

durc

hdi

eA

ngab

evo

nisolation_level=None

wir

ddi

eD

BM

Sin

den

Auto

com

mit-

Mod

usge

setz

t,Ä

nder

unge

nw

erde

nal

soso

fort

gesc

hrie

ben.

execute()

führ

tein

SQL

-Sta

tem

enta

us.E

inso

lche

sSt

atem

entk

ann

Pa-

ram

eter

bein

halte

n,di

ein

SQL

als

Frag

ezei

chen

2ge

schr

iebe

nw

erde

n.D

iePa

ram

eter

wer

den

als

Tupe

lübe

rgeb

en.execute()

gibt

ein

soge

nann

tes

Cur

sor-

Obj

ektz

urüc

k.B

eiSELECT

-Abf

rage

nkö

nnen

wir

dies

esnu

tzen

,um

über

alle

abge

frag

ten

Zei

len

zuite

rier

en.

2D

iese

sis

tsog

leic

hdi

esi

cher

eV

aria

nte,

sie

schü

tztg

utvo

rSQ

L-I

njec

tion.

Page 309: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

13.2

MyS

QL

Wir

stel

len

ihne

nhi

erei

nB

eisp

ielv

or,b

eide

mau

fein

een

tfern

teD

aten

bank

zuge

griff

enw

ird:

#!/usr/bin/python

import

MySQLdb

db

=MySQLdb.co

nnect("anderer.host.entf3rnt.de","Tandar","ge431m","meine_datenbank")

cursor

=db.cursor()

cursor.execute("SELECT

VERSION()")

row

=cursor.fetchone()

print

"server

version:",

row[0]

cursor.close()

db.close()

Aus

gabe

userlocalhost:$̃./my1.py

server

version:

5.0.32-Debian_7etch8-log

Page 310: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

Ver

bind

ung

wir

dhi

erer

zeug

tmitconnect()

.Der

entf

ernt

eSe

rver

,der

Ben

utze

rnam

e,da

sPa

ssw

ortu

nddi

eei

gent

liche

Dat

enba

nk,m

itde

rwir

uns

verb

inde

nw

olle

n,w

erde

nal

sPa

ram

eter

über

gebe

n.Zu

rück

erha

lten

wir

eine

nD

aten

bank

hand

leod

erei

neE

xcep

tion,

wen

net

was

schi

efgi

ng.

Ans

chlie

ßend

beso

rgen

wir

uns

ein

Cur

sor-

Obj

ekt,

mit

dess

enH

ilfe

wir

Abf

ra-

gen

form

ulie

ren

könn

en(execute("SELECTVERSION()")

)un

dei

neE

rgeb

nisz

eile

erha

lten

(fetchone()

).

Die

Aus

gabe

zeile

könn

enw

irso

dann

sofo

rtau

sgeb

en.

Zum

Schl

uss

wir

dde

rC

urso

rw

ieau

chdi

eV

erbi

ndun

gzu

rD

aten

bank

jew

eils

mitclose()

gesc

hlos

sen.

Das

nun

folg

ende

Bei

spie

lerg

änzt

das

ober

eB

eisp

ielu

mdi

eFä

higk

eit,

eine

Tabe

llean

zule

gen,

Dat

enhi

nein

zusc

hrei

ben

und

dies

ean

schl

ieße

ndzu

sele

k-tie

ren:

#!/usr/bin/python

#-*-

encoding:

utf-8

-*-

Page 311: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

import

MySQLdb

db

=MySQLdb.co

nnect("anderer.host.entf3rnt.de","Tandar","ge431m","meine_datenbank")

cursor

=db.cursor()

cursor.execute("CREATE

TABLE

IF

NOT

EXISTS

bar(uid

int,

anmeldedatum

date)")

cursor.execute("INSERT

INTO

bar

values(0,

'2009-04-17')")

cursor.execute("INSERT

INTO

bar

values(0,

'2009-03-13')")

cursor.execute("INSERT

INTO

bar

values(500,

'2009-04-16')")

cursor.close()

db.query("SELECT

uid,

anmeldedatum

FROM

bar

WHERE

uid=0")

result

=db.store_result()

nZeilen

=result.num_rows()

nSpalten

=result.num_fields()

print

"Anzahl

Zeilen:",

nZeilen,

"Anzahl

Spalten:",

nSpalten

for

zeile

in

xrange(nZeilen):

row

=result.fetch_row()

uid,

datum

=row[0]

printuid,

datum

db.close()

Page 312: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Aus

gabe

userlocalhost:$̃./my2.py

Anzahl

Zeilen:

2Anzahl

Spalten:

2

02009-04-17

02009-03-13

And

ers

als

imob

eren

Bei

spie

lnu

tzen

wirquery()

,um

eine

Anf

rage

andi

eD

aten

bank

zuse

nden

.W

irkö

nnen

das

Erg

ebni

sdi

eser

Abf

rage

mit

store_result()

spei

cher

nun

der

halte

nso

die

Erg

ebni

smen

geal

sSp

ei-

cher

obje

ktzu

rück

.Alte

rnat

ivkö

nnen

wiruse_result()

verw

ende

n,um

die

Erg

ebni

szei

len

nach

und

nach

zuer

halte

n.

Mitnum_rows()

undnum_fields()

erm

ittel

nw

irdi

eA

nzah

lder

Erge

b-ni

szei

len

und

die

Anz

ahld

erFe

lder

pro

Zei

le.

fetch_row()

entn

imm

tder

Erg

ebni

smen

geei

neZ

eile

und

liefe

rtsi

eal

sZ

eile

ntup

elhe

raus

.Die

einz

elne

nFe

lder

(hie

ruid

unddatum

)si

ndse

lbst

ein

Tupe

lim

erst

enE

lem

entd

erZ

eile

.

Page 313: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

13.3

Any

DB

M

Any

DB

Mis

tein

Mod

ul,w

elch

essi

chm

itD

BM

-ähn

liche

nD

aten

bank

enbe

-sc

häfti

gt.V

ondi

eser

Sorte

gibt

eszw

eiSt

ück3 ,n

ämlic

hD

BM

und

GN

U-D

BM

.D

iese

unte

rsch

eide

nsi

chin

ihre

min

tern

enA

ufba

uun

dde

rLiz

enz,

sind

aber

anso

nste

ngl

eich

.

DB

M-D

aten

bank

ensi

ndei

neA

rtvo

nW

örte

rbüc

hern

,sie

spei

cher

nSt

ring

-D

ictio

nari

esab

.Fol

gend

esB

eisp

ielz

eigt

die

grun

dsät

zlic

heA

rbei

tsw

eise

mit

ihne

n:

#!/usr/bin/python

#-*-

encoding:

utf-8

-*-

import

anydbm

db

=anydbm.open("wertpapiere.gdbm",

"c",

0660)

db["Siemens"]

="1000"

3So

wei

twir

wis

sen.

..

Page 314: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

db["Apple"]

="2000"

db["Red

Hat"]

="3000"

db.close()

db

=anydbm.open("wertpapiere.gdbm",

"r")

for

key,

value

in

db.iteritems():

print"Von

der

Aktie",

key,

"habe

ich",

value,

"Stück"

db.close()

Aus

gabe

userlocalhost:$̃./dbm1.py

Von

der

Aktie

Apple

habe

ich

2000

Stück

Von

der

Aktie

Red

Hat

habe

ich

3000

Stück

Von

der

Aktie

Siemens

habe

ich

1000

Stück

Man

kann

nur

Stri

ngs

spei

cher

n.M

itopen(dateiname,art,dateiflags)

wir

dei

neso

lche

Dat

eian

gele

gtod

erge

lese

n.D

iear

tist"c"

zum

Erz

euge

nde

rD

aten

bank

,wen

nsi

eni

cht

exis

tiert

,"w"

zum

Schr

eibe

n,"r"

zum

Les

en.d

atei

flags

ist

ein

Page 315: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

num

eris

cher

Wer

t,de

r,in

Abh

ängi

gkei

tvo

nde

rak

tuel

len

umas

k4 ,de

nD

atei

mod

ussp

ezifi

zier

t.

Die

Wer

tew

erde

nw

iein

eine

mD

ictio

nary

eing

etra

gen,

ansc

hlie

ßend

wird

die

Dat

eim

itclose()

wie

derg

esch

loss

en.Ü

berd

ieSc

hlüs

sel-

Wer

tpaa

reka

nnm

anm

itde

rMet

hodeiteritems()

iteri

eren

.

13.4

Zus

amm

enfa

ssun

g

Indi

esem

Kap

itel

habe

nw

irei

nige

Dat

enba

nken

kenn

enge

lern

tun

ddi

ety

pisc

heA

rbei

tsw

eise

mit

ihne

nau

fgez

eigt

.

13.5

Anm

erku

ngen

4Si

ehe

die

Man

ual-

Seite

zuba

sh(1

)

Page 316: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

14N

etzw

erk

14.1

Ein

fach

erZ

ugri

ffau

fWeb

ress

ourc

en

"Wie

ist

das

Wet

ter

auf

Haw

aii?

","W

elch

esSt

ück

wir

dge

rade

imR

adio

gesp

ielt?

"od

er"W

iela

utet

die

aktu

elle

Linu

x-K

erne

lver

sion

?"si

ndty

pisc

heFr

agen

,der

enA

ntw

orte

nsi

chzu

mei

stm

itH

ilfe

eine

sB

row

sers

finde

nla

ssen

.M

öcht

em

anje

doch

inei

nerk

onkr

eten

Anw

endu

ngni

chti

mm

erde

nB

row

ser

aufr

ufen

,hel

fen

zum

eist

klei

nePr

ogra

mm

eda

bei,

die

benö

tigte

nA

ntw

orte

nau

tom

atis

chzu

finde

n.D

ieak

tuel

leK

erne

lver

sion

zum

Bei

spie

list

leic

htau

s

305

Page 317: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

eine

rWeb

seite

hera

uszu

extr

ahie

ren.

Hie

rzu

sind

alle

rdin

gsK

ennt

niss

evo

mA

ufba

ude

rSei

teun

erlä

sslic

h.

#!/usr/bin/python

import

urllib2,

re

url

=urllib2.urlopen('http://www.kernel.org')

html

=url.read()

url.close()

table

=re.search("""<table

class="kver">.*?<td>(?P<kertext>.*?)&.*?</td>.*?<td><b><a

href=".*?">(?P<kerver>.*?)</a></b></td>""",

html,

re.S)

print

table.group('kertext'),

table.group('kerver')

Aus

gabe

userlocalhost:$̃./url1.py

The

latest

stable

version

of

the

Linux

kernel

is:

2.6.23.13

Die

Funk

tionurllib2.urlopen()

öffn

etei

nean

gege

bene

Web

seite

,die

wir

miturl.read()

volls

tänd

igle

sen

könn

en.I

nde

rV

aria

blen

html

ist

Page 318: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

nun

der

gesa

mte

Inha

ltde

rW

ebse

itege

spei

cher

t,w

irbe

nötig

enal

sode

nw

eite

ren

Net

zwer

kzug

riff

nich

tmeh

rund

schl

ieße

nda

herd

ieV

erbi

ndun

gm

iturl.close()

.Sch

autm

ansi

chdi

eW

ebse

iteau

fht

tp://

ww

w.k

erne

l.org

1im

Que

llcod

ean

,so

stel

ltm

anfe

st,d

ass

die

füru

nsin

tere

ssan

ten

Info

rmat

ione

nin

eine

rTab

elle

hint

erle

gtsi

nd,d

iem

it<tableclass="kver">

begi

nnt.

Inne

rhal

bde

rer

sten

beid

en<td>

-Zei

len

befin

den

sich

die

Info

rmat

ione

n,di

ew

irm

itde

mre

gulä

ren

Aus

druc

khe

raus

löse

n.

14.2

Les

enbe

iWik

iBoo

ks

Etw

asko

mpl

izie

rteri

stes

,auf

Wik

iboo

ks-I

nhal

tezu

zugr

eife

n.D

ieM

edia

Wik

i-So

ftw

are

verl

angt

ein

Min

dest

maß

anüb

ertr

agen

enB

row

ser-

Info

rmat

ione

nun

dda

sPr

otok

oll

GE

T.D

asnu

nfo

lgen

dePr

ogra

mm

benu

tzt

dahe

rei

nen

Req

uest

,dem

wir

eini

geH

eade

rhin

zufü

gen.

1http://www.kernel.org

Page 319: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

import

urllib2,

re

import

xml.sax.saxutils

as

util

header

={'User-agent'

:'PythonUnterLinux',

'Accept-Charset'

:'utf-8'}

request

=urllib2.Request('http://de.wikibooks.org/w/

index.php?title=Diskussion:Python_unter_Linux:_Netzwerk&action=edit',

headers=header)

print

"DEBUG:

",

request.get_method()

url

=urllib2.urlopen(request)

html

=url.read()

url.close()

found

=re.search("<textarea

.*?>(?P<inhalt>.*?)</textarea>",

html,

re.S)

print

util.unescape(found.group('inhalt'))

Aus

gabe

userlocalhost:$̃./url2.py

DEBUG:

GET

Page 320: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

<!--

Dient

zum

Testen

der

hier

vorgestellten

Skripte

-->

TESTINHALT

Die

HTT

PR

eque

stH

eade

rge

ben

den

Nam

enun

sere

sse

lbst

gesc

hrie

bene

nB

row

sers

mit

"Pyt

honU

nter

Linu

x"an

.Accept-Charset

iste

ine

Info

rmat

i-on

darü

ber,

wel

che

Zei

chen

codi

erun

gdi

eser

Bro

wse

rver

steh

t.D

iese

Hea

der

wer

den

als

Arg

umen

tuns

erem

Req

uest

mit

aufd

enW

egge

gebe

n.D

ieV

erbi

n-du

ngw

irdw

iede

rmiturlopen()

geöf

fnet

,der

Res

tdes

Prog

ram

mes

glei

cht

dem

aus

dem

erst

enB

eisp

iel.

Wir

öffn

endi

eD

isku

ssio

nsse

itedi

eser

Seite

,um

die

dort

enth

alte

nen

In-

form

atio

nen

bequ

emau

sei

ner

HT

ML

-Tex

tbox

extr

ahie

ren

zukö

nnen

.Mit

dem

Arg

umen

taction=edit

inde

rUR

Lge

ben

wir

an,d

ass

wir

die

Seite

eige

ntlic

hzu

mSc

hrei

ben

öffn

en.D

asm

ache

nw

ir,da

sodi

ein

tere

ssan

ten

Info

rmat

ione

nle

icht

erzu

finde

nsi

nd.D

erR

egul

äre

Aus

druc

kex

trah

iert

aus

dem<textarea>

-Ber

eich

derW

ebse

itede

nIn

halt.

Die

serI

nhal

tist

HTM

L-co

dier

t,w

esw

egen

wir

den

Strin

gm

itxml.sax.saxutils.unescape()

wie

deri

nei

nena

türl

ich-

lesb

are

Zei

chen

kette

umw

ande

ln.

Page 321: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

14.3

Auf

Wik

iBoo

kssc

hrei

ben

Um

anon

ym2

auf

WB

schr

eibe

nzu

könn

en,m

üsse

nzu

erst

eini

geIn

form

a-tio

nen

von

der

Web

seite

geho

ltw

erde

n,au

fde

rSi

esc

hrei

ben

möc

hten

.Im

HT

ML

-Que

llcod

ede

rSei

tesi

ndsi

eal

s<input...

zuer

kenn

en.D

iese

Da-

ten

müs

sen

beim

schr

eibe

nden

Zug

riff

mitü

berg

eben

wer

den,

esha

ndel

tsic

hin

dies

emFa

llum

ein

PO

ST-R

eque

st.D

asfo

lgen

dePr

ogra

mm

fügt

auf

die

Dis

kuss

ions

seite

dies

esK

apite

lsei

nen

klei

nen

Text

hinz

u,w

eite

reA

usga

beer

folg

tnic

ht.

#!/usr/bin/env

python

import

urllib,

urllib2,

re

import

xml.sax.saxutils

as

util

#Lies

die

Seite

header

={'User-agent'

:'PythonUnterLinux',

'Accept-Charset'

:

2So

anon

ymsi

ndSi

ega

rnic

ht.A

ufW

Bw

erde

nal

leÄ

nder

unge

n,di

eei

nN

utze

rode

rein

eIP

mac

htpr

otok

olie

rt

Page 322: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

'utf-8'}

request

=urllib2.Request('http://de.wikibooks.org/w/

index.php?title=Diskussion:Python_unter_Linux:_Netzwerk&action=edit')

url

=urllib2.urlopen(request)

html

=url.read()

url.close()

#RegExp

vorbereiten

s_str

="<form

id=\"editform\"

name=\"editform\"

method=\"post\"

action=\"(?P<actionurl>.*?)\".*?>"

s_str

+=

".*?<input

type=\"text\"

name=\"wpAntispam\"

id=\"wpAntispam\"

value=\"(?P<wpAntispamValue>)\"

/>"

s_str

+=

".*?<input

type=\'hidden\'

value=\"(?P<wpSectionValue>.*?)\"

name=\"wpSection\"

/>"

s_str

+=

".*?<input

type=\'hidden\'

value=\"(?P<wpStarttimeValue>.*?)\"

name=\"wpStarttime\"

/>"

s_str

+=

".*?<input

type=\'hidden\'

value=\"(?P<wpEdittimeValue>.*?)\"

name=\"wpEdittime\"

/>"

s_str

+=

".*?<input

type=\'hidden'

value=\"(?P<wpScrolltopValue>.*?)\"

name=\"wpScrolltop\"

id=\"wpScrolltop\"

/>"

s_str

+=

".*?<textarea

name=\"wpTextbox1\"

id=\"wpTextbox1\"

cols=\"80\"

rows=\"25\"

.*?>(?P<content>.*?)</textarea>"

s_str

+=

".*?<input

tabindex=\'2\'

type=\'text\'

value=\"(?P<wpSummaryValue>.*?)\"

name=\'wpSummary\'

id=\'wpSummary\'

Page 323: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

maxlength=\'200\'

size=\'60\'

/>"

s_str

+=

".*?<input

name=\"wpAutoSummary\"

type=\"hidden\"

value=\"(?P<wpAutoSummaryValue>.*?)\"

/>"

s_str

+=

".*?<input

type=\'hidden\'

value=\"(?P<wpEditTokenValue>.{2})\"

name=\"wpEditToken\"

/>"

#RegExp

ausfuehren

found

=re.search(s_str,

html,

re.S)

#Neuen

Inhalt

aufbauen

new_content

=util.unescape(found.group("content"))

+"\n===Neuer

Inhalt===\ntest

neues

Skript"

summary

="Python

unter

Linux

Browser"

#zu

uebermittelnde

Daten

vorbereiten

data_dict

={"wpAntispam"

:found.group("wpSectionValue"),

"wpSection"

:found.group("wpSectionValue"),

"wpStarttime"

:found.group("wpStarttimeValue"),

"wpEdittime"

:found.group("wpEdittimeValue"),

"wpScrolltop"

:found.group("wpScrolltopValue"),

"wpTextbox1"

:new_content,

"wpSummary"

:summary,

"wpAutoSummary"

:found.group("wpAutoSummaryValue"),

"wpEditToken"

:found.group("wpEditTokenValue")}

Page 324: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

data

=urllib.urlencode(data_dict)

#und

abschicken...

request

=urllib2.Request('http://de.wikibooks.org/w/

index.php?title=Diskussion:Python_unter_Linux:_Netzwerk&action=edit')

url

=urllib2.urlopen(request)

url.close()

Der

erst

eTe

ilde

sPr

ogra

mm

esis

tdaz

uda

,die

Seite

zule

sen.

Der

neue

In-

halt,

wie

auch

die

Zus

amm

enfa

ssun

gde

rÄnd

erun

g,w

erde

nin

den

Var

iabl

ennew_content

undsummary

vorb

erei

tet.

Auf

derg

eles

enen

Web

seite

be-

finde

nsi

chei

nige

Dat

enw

iewpSummary

-Zus

amm

enfa

ssun

gde

rÄnd

erun

g-,

wpAutoSummary

-Kon

stan

terW

ert,

derz

urüc

kgeg

eben

wer

den

mus

s-un

dwpTextbox1

,der

den

eige

ntlic

hen,

zuüb

erm

ittel

nden

Inha

ltde

rSei

teda

r-st

ellt.

Die

seFe

lder

müs

sen

extr

ahie

rtun

d,ge

gebe

nfal

lsm

odifi

zier

t,zu

rück

ge-

schi

cktw

erde

n.urllib.urlencode()

erze

ugta

usde

mD

ictio

nary

eine

nSt

ring

,der

dem

Req

uest

mitg

egeb

enw

ird.

Page 325: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

14.4

Anm

elde

nm

itC

ooki

es

Inm

anch

enFo

ren

und

Wik

iska

nnod

erm

uss

man

sich

anm

elde

n,um

Bei

träge

zusc

hrei

ben.

Die

Anm

elde

date

nw

erde

nhä

ufig

inei

nem

Coo

kie

gesp

eich

ert.

Soau

chbe

iWik

iboo

ks.D

asfo

lgen

deB

eisp

ielz

eigt

eine

Mög

lichk

eit,

sich

beiW

ikib

ooks

anzu

mel

den.

Auf

eine

Test

ausg

abe

auf

der

Dis

kuss

ions

seite

habe

nw

irdi

esm

alve

rzic

htet

,de

nC

ode

dazu

kenn

enSi

esc

hon

aus

dem

vorh

erig

enB

eisp

iel.

Esw

irdle

digl

ich

eine

Bes

tätig

ung

über

den

erfo

lgre

iche

nA

nmel

devo

rgan

gau

sgeg

eben

:

#!/usr/bin/python

import

urllib,

urllib2,

re

import

cookielib

USERNAME

="Testaccount007"

PASSWORD

="test123"

header

={'User-agent'

:'PythonUnterLinux',

'Accept-Charset'

:'utf-8'}

Page 326: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

data_dict

={"wpName"

:USERNAME,

"wpPassword"

:PASSWORD,

"wpRemember"

:"1"}

data

=urllib.urlencode(data_dict)

cookieMonster

=cookielib.CookieJar()

opener

=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieMonster))

urllib2.install_opener(opener)

request

=urllib2.Request('http://de.wikibooks.o

rg/w/index.php?title=Spezial:Anmelden&action=submitlogin&type=login',

data,

header)

url

=urllib2.urlopen(request)

html

=url.read()

url.close()

res

=re.search("<p>(?P<ret>.*?)</p>",

html,

re.S)

print

res.group('ret')

Aus

gabe

userlocalhost:$̃./url4.py

Du

bist

jetzt

als

„Testaccount007“

bei

Wikibooks

angemeldet.

Page 327: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Auf

der

Anm

elde

seite

steh

enim

Form

ular

unte

ran

dere

mdi

eE

inga

beze

i-le

n,di

em

itwpName

undwpPassword

imH

TM

L-C

ode

bena

nnts

ind.

Die

-se

Var

iabl

enw

erde

nm

ittel

surllib.urlencode()

inD

aten

für

den

anst

ehen

den

PO

ST-R

eque

stum

gew

ande

lt.B

eide

rV

erw

altu

ngvo

nC

oo-

kies

hilf

tun

sdi

eK

lass

ecookielib.CookieJar()

.M

itih

rer

Hilf

eba

uen

wir

eine

nO

pene

r,de

nm

ansi

chal

sei

neA

rtSc

hlüs

sel

vors

tel-

len

kann

.M

itopener.open()

könn

ten

wir

die

Web

seite

scho

nöf

fnen

,je

doch

habe

nw

ires

ande

rSt

elle

vorg

ezog

en,

den

Ope

ner

glob

alm

iturllib2.install_opener()

zuin

stal

liere

n.

14.5

Zei

tser

ver

Selb

stve

rstä

ndlic

hka

nnm

anm

itPy

thon

nich

tnur

Bro

wse

rsch

reib

en,s

onde

rnga

nzbe

quem

auch

Serv

er.W

irim

plem

entie

ren

hier

eine

nSe

rver

,bei

dem

sich

Clie

nts

anm

elde

nm

üsse

nun

dzu

rB

eloh

nung

die

Zei

tda

uerh

aft

ange

zeig

t

Page 328: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

beko

mm

en.

Clie

nts

sind

hier

einf

ache

Teln

et-S

itzun

gen,

die

sie

nach

dem

Star

ten

des

Serv

ers

inei

nem

ande

ren

Fens

terö

ffne

nkö

nnen

.

Uns

erSe

rver

war

teta

ufzw

eiVe

rbin

dung

en.D

ieC

lient

sm

üsse

nsi

chdu

rch

die

Eing

abe

von

HELO

ausw

eise

n.Si

ndzw

eiC

lient

sak

zept

iert

wor

den,

wird

anbe

ide

die

aktu

elle

Zei

tges

chic

kt.

#!/usr/bin/python

import

socket,

select,

time

host

='127.0.0.1'

port

=6000

s=

socket.socket(socket.AF_INET,

socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET,

socket.SO_REUSEADDR,

1)

s.bind((host,

port))

s.listen(2)

allConnected

=False

allClients

=[]

Page 329: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#Clients

verbinden

while

not

allConnected:

clientsock,

clientaddr

=s.accept()

print"Verbindungswunsch

von",

clientsock.getpeername(),

data

=clientsock.recv(4096)

data.strip()

ifdata.startswith("HELO"):

allClients.append(clientsock)

print"akzeptiert"

else: clientsock.close()

print"nicht

akzeptiert"

print"Wir

haben

",

len(allClients),

"Clients"

iflen(allClients)

==

2:

allConnected

=True

#Daten

senden,

empfangen

while

True:

time.sleep(2)

listIn,

listOut,

listTmp

=select.select(allClients,

allClients,

[],

1)

forsock

in

listIn:

data

=sock.recv(4096)

print"--\nAnkommende

Daten:",

len(data),

"Zeichen.

Inhalt:

",

data

Page 330: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

iflen(data)

==

0:

print

"Client

hat

die

Verbindung

getrennt"

sock.close()

allClients.remove(sock)

listIn.remove(sock)

listOut.remove(sock)

forsock

in

listOut:

msg

=time.strftime("%H:%M:%S\n")

num

=sock.send(msg)

Mitsocket.socket(socket.AF_INET,socket.SOCK_STREAM)

wir

dei

nSo

cket

erze

ugt,

eine

Stru

ktur

,die

eine

Net

zwer

kver

bind

ung

repr

ä-se

ntie

rt.I

ndi

esem

Fall

soll

esei

neda

uerh

afte

TC

P/IP

-Ver

bind

ung

sein

.Der

Port

,auf

dem

dies

eV

erbi

ndun

gla

usch

t,so

llw

iede

rver

wer

tbar

sein

.Wen

nde

rSe

rver

sich

been

det,

soll

derP

ortw

iede

rgen

utzt

wer

den

könn

en.D

azu

dien

tsetsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)

.A

nsch

ließe

ndbi

nden

wir

den

Port

andi

eIP

-Adr

esse

und

die

Port

num

mer

(bind((host,port))

).So

lang

eni

cht

alle

Clie

nts

verb

unde

nsi

nd,

wer

den

Ver

bind

ungs

wün

sche

akze

ptie

rt(accept()

).Se

ndet

der

Clie

ntet

was

,das

mit

HELO

begi

nnt,

sow

ird

erau

fgen

omm

en,s

onst

abge

lehn

t.

Page 331: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

folg

ende

Schl

eife

wir

dal

lezw

eiSe

kund

enau

sgef

ührt

.select.select(allClients,allClients,[],1)

war

tet

höch

sten

sei

neSe

kund

eau

fClie

nts,

die

zum

Send

enod

erE

mpf

ange

nbe

reit

sind

.Die

Funk

tion

gibt

drei

Lis

ten

zurü

ck.D

ieer

sten

beid

enL

iste

nen

thal

ten

dabe

idie

jeni

gen

Sock

ets,

die

zum

Send

enod

erzu

mE

mpf

ange

nbe

reit

sind

.Se

ndet

ein

Sock

etei

nele

ere

Zei

chen

kette

,dan

nbe

deut

etda

s,da

sser

sich

been

deth

at.S

onst

wir

dan

alle

Clie

nts

die

Zei

taus

gege

ben.

Aus

gabe

userlocalhost:$̃./server.py

Verbindungswunsch

von

('127.0.0.1',

40510)

akzeptiert

Wir

haben

1Clients

Verbindungswunsch

von

('127.0.0.1',

40511)

akzeptiert

Wir

haben

2Clients

Auf

zwei

ande

ren

Kon

sole

n(H

ierw

ird

HELO

eing

egeb

en):

Aus

gabe

userlocalhost:$̃telnet

localhost

6000

Page 332: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Trying

127.0.0.1...

Connected

to

localhost.

Escape

character

is

'ˆ]'.

HELO

15:46:20

...

14.6

Cha

tser

ver

Eine

nSe

rver

fürs

Cha

tten

zusc

hrei

ben

istn

urw

enig

schw

erer

.Hie

rbei

geht

esda

rum

,das

ssi

chei

nige

Clie

nts

wäh

rend

eine

rCha

t-Sitz

ung

verb

inde

n,w

iede

rab

mel

den

und

Dat

envo

nei

nem

Clie

ntan

alle

ande

ren

Clie

nts

über

trag

enw

erde

n.Fo

lgen

des

Bei

spie

lver

deut

licht

das:

#!/usr/bin/python

import

socket,

select,

time

Page 333: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

host

='127.0.0.1'

port

=6000

s=

socket.socket(socket.AF_INET,

socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET,

socket.SO_REUSEADDR,

1)

s.bind((host,

port))

s.listen(1)

allClients

=[]

#Daten

senden,

empfangen

while

True:

time.sleep(2)

#Server

socket

hinzufuegen

listIn,

listOut,

listTmp

=select.select(allClients

+[s],

allClients,

[],

1)

forsock

in

listIn:

ifsock

is

s:

clientsock,

clientaddr

=s.accept()

print

"+

Verbindungswunsch

von",

clientsock.getpeername(),

"akzeptiert"

allClients.append(clientsock)

else: data

=sock.recv(4096)

iflen(data)

==

0or

data.startswith("quit"):

Page 334: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

print"-

Client",

clientsock.getpeername(),

"hat

die

Verbindung

getrennt"

sock.close()

allClients.remove(sock)

listIn.remove(sock)

listOut.remove(sock)

else: #

nicht

an

den

Sender

schreiben

listOut.remove(sock)

forsout

in

listOut:

sout.send(data)

Der

Serv

erlä

ufta

nfan

gsoh

neV

erbi

ndun

g.W

enn

ein

Clie

ntsi

chve

rbin

den

möc

hte,

sow

ird

der

Serv

er-S

ocke

t(s

)le

sebe

reit.

Vor

raus

setz

ung

dafü

ris

t,da

ssw

irim

Auf

rufv

onselect()

den

Serv

eral

sim

Prin

zip

empf

angs

bere

itei

nstu

fen.

Ein

Clie

ntka

nnsi

chnu

ndu

rch

Eing

abe

von

quit

been

den.

Falls

derC

lient

Dat

ense

ndet

,wer

den

dies

eD

aten

anal

lean

dere

nC

lient

seb

enfa

llsve

rsch

ickt

,ni

chtj

edoc

han

denj

enig

en,d

erge

send

etha

t.D

adur

chso

llei

nw

eite

res

Ech

ode

rEin

gabe

verm

iede

nw

erde

n.

Page 335: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

Aus

gabe

des

Prog

ram

mes

istb

eiei

nerT

elne

t-Si

tzun

gda

s,w

asm

anvo

nei

nem

Cha

terw

arte

t:E

sw

erde

nD

aten

anal

leC

lient

süb

ertr

agen

.Des

weg

enve

rzic

hten

wir

hier

aufd

ieD

arst

ellu

ng.

14.7

Zus

amm

enfa

ssun

g

Um

spez

ialis

iert

eB

row

serz

usc

hrei

ben,

benö

tigtm

anW

isse

nüb

erdi

eW

eb-

seite

und

Ken

ntni

sse

derb

enöt

igte

nPr

otok

olle

.Bei

des

kann

man

zum

eist

aus

den

Que

lltex

ten

derW

ebse

iten

hera

usle

sen.

Zum

eist

sind

nurw

enig

eZ

eile

nPr

ogra

mm

code

nötig

,um

eine

Web

seite

kom

plet

tein

zule

sen,

dafü

rvie

lePr

o-gr

amm

zeile

n,di

eD

aten

aus

dem

HT

ML

-Cod

ezu

extr

ahie

ren.

Falls

Sie

die

hier

vorg

este

llten

und

gege

bene

nfal

lsm

odifi

zier

ten

Prog

ram

me

aufW

ikib

ooks

zum

ehr,

alsn

urzu

Test

zwec

ken

benu

tzen

wol

len,

frag

enSi

ebi

ttedi

eA

dmin

is-

trat

oren

umE

rlau

bnis

.Pyt

hon

enth

älte

benf

alls

eine

volls

tänd

ige

Anb

indu

ngan

Net

zwer

kpro

toko

llen.

Hie

rmit

lass

ensi

chC

lient

sun

dSe

rver

schr

eibe

n.

Page 336: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

14.8

Anm

erku

ng

Page 337: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 338: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

15Py

Gam

e

PyG

ame

iste

ine

Gru

ppe

von

Mod

ulen

,die

eine

nPr

ogra

mm

iere

rbei

derE

rste

l-lu

ngvo

nSp

iele

nun

ters

tütz

t.D

iese

Mod

ule

bein

halte

nZ

ugri

ffau

fgen

auei

nG

rafik

fens

ter.

PyG

ame

unte

rstü

tztd

enE

ntw

ickl

erm

itG

rafik

prim

itive

n,ei

nfa-

chem

Soun

dzug

riff

sow

ieSp

rite

sun

dvi

elem

meh

r.Ty

pisc

heG

UI-

Ele

men

tegi

btes

indi

esen

Mod

ulen

jedo

chni

cht.

PyG

ame

bein

halte

tein

eG

rafik

bibl

io-

thek

,zu

der

Wik

iboo

ksau

chei

nB

uch

hat,

näm

lich

SDL

1 .E

inig

ede

rhi

eran

gefü

hrte

nB

eisp

iele

sind

dies

emB

uch

entle

hnt.

Hin

terg

rund

info

rmat

ione

nzu

den

Mod

ulen

finde

tsic

hau

fder

PyG

ame-

Web

seite

2 .

1http://de.wikibooks.org/wiki/SDL

2http://www.pygame.org/

327

Page 339: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

15.1

Ein

Gra

fikfe

nste

r

#!/usr/bin/python

import

pygame

import

sys

def

init():

WINWIDTH

=640

WINHEIGHT

=480

pygame.init()

screen

=pygame.display.set_mode((WINWIDTH,

WINHEIGHT))

screen.fill((200,

200,

200))

pygame.display.update()

def

event_loop():

whileTrue:

forevent

in

pygame.event.get():

ifevent.type

==

pygame.QUIT:

sys.exit()

elif

event.type==

pygame.KEYDOWN:

sys.exit()

if

__name__==

'__main__':

Page 340: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

init()

event_loop()

Abb

.2B

ildde

rAnw

endu

ng

Page 341: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

PyG

ame

mus

sin

itial

isie

rtw

erde

n,da

süb

erni

mm

tdi

eFu

nktio

npygame.init()

,w

elch

evo

ral

len

ande

ren

PyG

ame-

Funk

tione

nau

fger

ufen

wer

den

mus

s.E

inne

ues

Fens

ter

erha

lten

wir

mit

der

Met

hode

pygame.display.set_mode()

,de

rw

irne

ben

der

Fens

terg

röße

als

Tupe

lau

chno

chw

eite

reFl

ags

mitg

eben

könn

-te

n.W

eite

reA

ngab

enw

ären

zum

Bei

spie

l,da

ssw

irde

nV

oll-

bild

mod

us(pygame.FULLSCREEN

)od

erO

penG

L-U

nter

stüt

zung

(pygame.OPENGL

)w

ünsc

hen.

pygame.display.set_mode()

über

gibt

eine

soge

nann

teSu

rfac

e,ei

neSt

rukt

ur,

die

das

Gra

fik-

fens

ter

repr

äsen

tiert

.D

enB

ildsc

hirm

fülle

nw

irm

itei

ner

Farb

escreen.fill((200,200,200))

(gra

u),d

iew

iral

sTu

pelü

berg

eben

.D

amit

dies

eFä

rbun

gw

irksa

mw

ird,f

risch

tpygame.display.update()

den

gesa

mte

nB

ildsc

hirm

auf.

PyG

ame

spei

cher

tal

leE

reig

niss

ew

ieTa

sten

drüc

ke,

Mau

sbew

e-gu

ngen

und

Joys

tick-

Kom

man

dos

inei

ner

Folg

evo

nE

vent

s.M

itpygame.event.get()

hole

nw

irun

sda

snä

chst

ean

steh

ende

Er-

eign

is.I

mA

ttrib

utevent.type

istd

ieA

rtvo

nE

reig

nis

gesp

eich

ert,

die

Page 342: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

anlie

gt.I

nun

sere

mei

nfac

hen

Bei

spie

lw

ird

nur

nach

pygame.QUIT

und

pygame.KEYDOWN

verz

wei

gt,i

ndi

esen

Fälle

nbe

ende

tsic

hda

sPr

ogra

mm

.D

iena

chst

ehen

deTa

belle

enth

älte

inen

Aus

schn

ittde

rmög

liche

nE

reig

niss

e,fü

rein

evo

llstä

ndig

eLi

ste

zieh

enSi

ebi

ttedi

eO

nlin

e-D

okum

enta

tion

zuR

ate.

Ere

igni

sB

edeu

tung

QU

ITA

nwen

derw

ünsc

htda

sPr

ogra

mm

zube

ende

n,be

ispi

elsw

eise

durc

hD

rück

ende

sSc

hlie

ßen-

Kno

pfes

KE

YD

OW

NTa

ste

wur

dehe

runt

erge

drüc

ktK

EY

UP

heru

nter

gedr

ückt

eTa

ste

wur

dew

iede

rlos

gela

ssen

MO

USE

MO

TIO

ND

ieM

aus

wur

debe

weg

tM

OU

SEB

UT

TON

DO

WN

Ein

Kno

pfan

derM

aus

wur

dege

drüc

kt

Page 343: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ere

igni

sB

edeu

tung

USE

RE

VE

NT

Ein

frei

defin

ierb

ares

Ere

igni

spa

ssie

rte.

Gen

auge

nom

men

gibt

eshi

ervi

ele

wei

tere

Eve

nts,

die

frei

defin

ierb

arsi

nd,n

ämlic

hal

-le

zwis

chen

USE

RE

VE

NT

und

NU

ME

VE

NT

S-1.

15.2

Mal

prog

ram

m

Um

die

Eve

nts

einm

alre

alzu

benu

tzen

,ha

ben

wir

ein

Mal

prog

ram

mal

sB

eisp

ielg

esch

rieb

en.M

itde

nTa

sten

0bi

s3

steu

ertm

andi

eFa

rbw

ahl,

drüc

ktm

anei

nen

derM

ausk

nöpf

eim

Fens

ter,

sow

ird

dort

ein

Kle

cks

mit

der

aktu

ellg

ewäh

lten

Farb

ege

zeic

hnet

.Die

Tast

eEscape

bric

htda

sPro

gram

mab

.

Page 344: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

import

pygame

import

sys

class

Malprogramm:

def__init__(self,

width,

height):

self._width

=width

self._height

=height

pygame.init()

self._screen

=pygame.display.set_mode((self._width,

self._height))

self._screen.fill((200,

200,

200))

pygame.display.update()

self._drawColor

=(200,

0,

0)

defmalen(self,

(x,

y)):

pygame.draw.circle(self._screen,

self._drawColor,

(x,

y),

10)

pygame.display.update((x-10,

y-10,

20,

20))

defevent_loop(self):

whileTrue:

for

event

in

pygame.event.get():

ifevent.type

==

pygame.QUIT:

sys.exit()

Page 345: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

elifevent.type

==

pygame.KEYDOWN:

ifevent.key

==

pygame.K_ESCAPE:

sys.exit()

elifevent.key

==

pygame.K_0:

self._drawColor

=(255,

255,

255)

elifevent.key

==

pygame.K_1:

self._drawColor

=(0,

0,

255)

elifevent.key

==

pygame.K_2:

self._drawColor

=(0,

255,

0)

elifevent.key

==

pygame.K_3:

self._drawColor

=(255,

0,

0)

elifevent.type

==

pygame.MOUSEBUTTONDOWN:

self.malen(event.pos)

if

__name__==

'__main__':

m=

Malprogramm(640,

480)

m.event_loop()

Page 346: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.3B

ildde

rAnw

endu

ng

Die

__init__()

-Met

hode

der

Kla

sse

verh

ält

sich

,w

iedi

eFu

nktio

ninit()

aus

dem

erst

enB

eisp

iel,

bis

auf

dass

sie

eine

Star

tfar

bebe

legt

:self._drawColor=(200,0,0)

(rot

).D

iese

Farb

ew

irdin

derM

e-th

odeevent_loop()

beie

ntsp

rech

ende

nTa

sten

drüc

ken

verä

nder

t.

Page 347: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Inde

rMet

hode

malen()

wir

dei

nebe

stim

mte

ange

gebe

nSt

elle

mit

eine

mau

sgef

üllte

nK

reis

bem

alt.pygame.draw.circle()

benö

tigt

dazu

die

Surf

ace,

die

Farb

eal

sTu

pel,

den

Mitt

elpu

nkt

als

Tupe

lun

dde

nR

adiu

s.pygame.display.update()

fris

chtd

enB

ildsc

hirm

wie

der

auf,

dam

itw

irdi

esen

Kre

isse

hen

könn

en.I

ndi

esem

Fall

benu

tzen

wir

eine

Var

iant

ede

rM

etho

de,d

aw

irni

chtd

enge

sam

ten

Bild

schi

rmbe

mal

thab

en,s

onde

rnnu

rei

nR

echt

eck.

Die

ses

den

Kre

isfle

ckum

gebe

neR

echt

eck

über

gebe

nw

irde

rM

etho

depygame.display.update()

,die

dadu

rch

wes

entli

chsc

hnel

ler

arbe

iten

kann

,als

müs

ste

sie

den

gesa

mte

nB

ildsc

hirm

auff

risc

hen.

Bei

gedr

ückt

erTa

ste

isti

nevent.key

die

Kon

stan

tede

rged

rück

ten

Tast

ege

spei

cher

t.E

inen

unvo

llstä

ndig

enÜ

berb

lick

über

die

Info

rmat

ione

n,di

eSi

eau

sde

revent

-Var

iabl

enhe

raus

löse

nkö

nnen

inA

bhän

gigk

eitv

omge

wäh

lten

Ere

igni

styp

gibt

die

folg

ende

Tabe

lle:

Ere

igni

styp

Eve

nt-

Feld

erB

edeu

tung

Page 348: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ere

igni

styp

Eve

nt-

Feld

erB

edeu

tung

KE

YD

OW

Nun

icod

eD

asU

nico

de-Z

eich

endi

eses

Tast

endr

ucke

ske

yK

_0..K

_9-Z

iffer

ntas

teK

_a..K

_zB

uchs

tabe

ntas

teun

dvi

ele

meh

rm

odK

MO

D_L

SHIF

T-l

inke

Schi

ft-T

aste

,K

MO

D_L

CT

RL

linke

STR

G-T

aste

KM

OD

_RA

LTre

chtA

LT-

Tast

eun

dvi

ele

meh

rK

EY

UP

key,

mod

wie

oben

MO

USE

MO

TIO

Npo

sA

bsol

ute

Posi

tion

inne

r-ha

lbde

sFe

nste

rsal

sTu

pel

Page 349: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ere

igni

styp

Eve

nt-

Feld

erB

edeu

tung

rel

Ver

ände

rung

zurl

etzt

enPo

sitio

nbu

ttons

gedr

ückt

eM

ausk

nöpf

eM

OU

SEB

UT

TO

N-

DO

WN

,MO

USE

BU

T-TO

NU

P

pos,

butto

nw

ieob

en

15.3

Ani

mat

ion

Zu

folg

ende

mB

eisp

ielp

asst

derA

ussc

hnitt

aus

Hei

nric

hH

eine

sG

edic

ht:E

inJü

nglin

glie

btei

nM

ädch

en:

Ein

Jüngling

liebt

ein

Mädchen,

die

hat

einen

andern

erwählt;

der

andre

liebt

eine

andre,

Page 350: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

und

hat

sich

mit

dieser

vermählt.

Das

Mädchen

heiratet

aus

Ärger

den

ersten

besten

Mann,

der

ihr

in

den

Weg

gelaufen;

der

Jüngling

ist

übel

dran.

Wir

vers

uche

nei

nmal

eine

ähnl

iche

Situ

atio

nzu

prog

ram

mie

ren,

wob

eide

rJü

nglin

gde

mM

ädch

enhi

nter

herl

äuft

,die

sew

iede

rum

ihre

mE

rwäh

lten,

der

sein

erse

itsei

nera

nder

enhi

nter

herl

äuft

.Die

sew

iede

rum

vers

ucht

den

Jüng

-lin

gzu

erha

sche

n.Te

chni

sch

gese

hen

lass

enw

irsc

hlic

htei

nige

Punk

tesi

chau

fein

ande

rzu

bew

egen

.

Das

folg

ende

Prog

ram

mge

neri

erte

inE

reig

nis

(USEREVENT

)auf

derB

asis

eine

sTi

mer

s.D

erTi

mer

löst

das

Ere

igni

sna

ch20

0M

illis

ekun

den

aus,

inde

rE

vent

-Loo

pw

ird

ents

chie

den,

obna

chw

eite

ren

0,2

Seku

nden

erne

utda

sgl

eich

eE

reig

nis

erfo

lgen

soll.

Nac

hje

dem

Zei

tinte

rval

lwer

den

Lin

ien

zwsc

hen

Punk

ten,

die

sich

bew

egen

,neu

geze

ichn

et:

#!/usr/bin/python

Page 351: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

import

pygame

import

math

import

sys

class

Animation:

def__init__(self,

width,

height):

self._width

=width

self._height

=height

pygame.init()

self._screen

=pygame.display.set_mode((self._width,

self._height))

self._screen.fill((200,

200,

200))

pygame.display.update()

self._punkte

=[(0.0,

0.0),

(width

-1.0,

0.0),

(width

-1.0,

height

-1.0),

(0.0,

height

-1.0)]

pygame.time.set_timer(pygame.USEREVENT,

200)

defmalen(self):

pygame.draw.line(self._screen,

(0,0,0),

self._punkte[0],

self._punkte[1],

1)

pygame.draw.line(self._screen,

(0,0,0),

self._punkte[1],

self._punkte[2],

1)

pygame.draw.line(self._screen,

(0,0,0),

self._punkte[2],

self._punkte[3],

1)

Page 352: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

pygame.draw.line(self._screen,

(0,0,0),

self._punkte[3],

self._punkte[0],

1)

pygame.display.update()

defberechnen(self):

punkte_tmp

=[]

anz_punkte

=len(self._punkte)

dx

=0.0

#vorbelegt,

da

wir

den

Wert

zurueckgeben

fori

in

xrange(4):

x1,

y1

=self._punkte[i]

x2,

y2

=self._punkte[(i+1)

%anz_punkte]

dx

=x2

-x1

dy

=y2

-y1

#Einheitsvektor

laenge

=math.sqrt(dx

*dx

+dy

*dy)

ex

=dx

/laenge

ey

=dy

/laenge

x_neu

=x1

+5.0*

ex

y_neu

=y1

+5.0*

ey

punkte_tmp.append((x_neu,

y_neu))

self._punkte

=punkte_tmp

returndx

defevent_loop(self):

whileTrue:

Page 353: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

for

event

in

pygame.event.get():

ifevent.type

==

pygame.QUIT:

sys.exit()

elifevent.type

==

pygame.KEYDOWN:

ifevent.key

==

pygame.K_ESCAPE:

sys.exit()

elifevent.type

==

pygame.USEREVENT:

self.malen()

dist

=self.berechnen()

ifdist

>20.0:

pygame.time.set_timer(pygame.USEREVENT,

200)

if

__name__==

'__main__':

a=

Animation(800,

800)

a.event_loop()

Page 354: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.4B

ildde

rAni

mat

ion

self._punkte

iste

ine

Lis

te,d

iePu

nkte

als

Tupe

lent

hält.

Die

sePu

nkte

wer

den

inde

rM

etho

deberechnen()

neu

bere

chne

tun

des

wer

den

Li-

nien

zwis

chen

den

Punk

ten

neu

geze

ichn

et.

Die

Punk

teso

llen

sich

dabe

iau

fein

ande

rzu

bew

egen

.Der

Tim

erw

ird

in__init__()

mit

dem

Auf

ruf

Page 355: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

pygame.time.set_timer()

gest

arte

t.D

ieA

rgum

ente

sind

der

Ere

ig-

nist

ypun

ddi

eZ

eits

pann

ein

Mill

isek

unde

n.D

ieM

etho

demalen()

sorg

tda

für,

daß

zwis

chen

alle

nvi

erPu

nkte

nLi

nien

insc

hwar

zge

mal

twer

den.

Tritt

einUSEREVENT

ein,

sow

erde

ndi

eL

inie

nzw

isch

ende

nPu

nkte

nge

mal

t,es

wer

den

neue

Punk

tebe

rech

netu

nden

tsch

iede

n,ob

wei

tere

Punk

tebe

rech

net

wer

den

müs

sen.

Geg

eben

enfa

llsw

ird

derT

imer

erne

utge

star

tet.

Det

ails

Die

Ber

echn

ung

erfo

lgtn

ach

folg

ende

mSc

hem

a:Zu

erst

wer

den

alle

Punk

tein

den

Ecke

nve

rteilt

.Ans

chlie

ßend

bew

egts

ich

jede

rPun

ktei

nSt

ück

aufd

enan

dere

nzu

.Der

Punk

tsel

f._pu

nkte

[0]b

eweg

tsi

chin

die

Ric

htun

gde

sPu

nkte

sse

lf._p

unkt

e[1]

und

sofo

rt,d

erle

tzte

bew

egts

ich

wie

dera

ufde

ner

sten

Punk

tzu.

Mat

hem

atis

chbe

deut

etda

s,~ P (

t+20

0ms)=~ P t+

v∗~ez

ube

rech

nen,

wob

ei~e

dern

orm

ierte

Ric

htun

gsve

ktor

zwis

chen

zwei

bena

chba

rten

Punk

ten

ist.

und

t+20

0ms

den

näch

sten

Zei

tsch

ritt

bede

utet

.

Page 356: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

15.4

Bild

erun

dFo

nts

Das

folg

ende

Bei

spie

ldem

onst

rier

t,w

iem

anB

ilder

inPy

Gam

elä

dtun

dm

itH

ilfe

von

Font

sei

nen

Text

inih

nen

aufb

ring

t.D

amit

das

Prog

ram

mko

rrek

tfu

nktio

nier

t,m

uss

ein

Bild

mit

dem

Nam

enbeispiel.png

imak

tuel

len

Ver

zeic

hnis

liege

n.

#!/usr/bin/python

import

pygame

import

sys

WINWIDTH

=640

WINHEIGHT

=480

def

init(width,

height):

pygame.init()

screen

=pygame.display.set_mode((width,

height))

screen.fill((250,

250,

250))

pygame.display.update()

returnscreen

def

load_pic(filename,

width,

height):

Page 357: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

surface

=pygame.image.load(filename)

picW,

picH

=surface.get_size()

transform

=False

ifpicW

>width:

picH

=1.0

*width

/picW

*picH

picW

=width

transform

=True

ifpicH

>height:

picW

=1.0

*height

/picH

*picW

picH

=height

transform

=True

iftransform:

w=

int(round(picW))

h=

int(round(picH))

tmp

=pygame.transform.scale(surface,

(w,

h))

surface

=tmp

returnsurface

def

blit_pic(surface,

pic,

width,

height):

picW,

picH

=pic.get_size()

w=

(width

-picW)

/2

h=

(height

-picH)

/2

surface.blit(pic,

(w,

h))

font

=pygame.font.SysFont('curier',

50)

text

=font.render("Hallo,

Welt",

True,

(0,

0,

200))

Page 358: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

picW,

picH

=text.get_size()

w=

(width

-picW)

/2

h=

(height

-picH)

/2

surface.blit(text,

(w,

h))

pygame.display.update()

def

event_loop():

whileTrue:

forevent

in

pygame.event.get():

ifevent.type

==

pygame.QUIT:

sys.exit()

elif

event.type==

pygame.KEYDOWN:

sys.exit()

if

__name__==

'__main__':

screen

=init(WINWIDTH,

WINHEIGHT)

pic

=load_pic('beispiel.png',

WINWIDTH,

WINHEIGHT)

blit_pic(screen,

pic,

WINWIDTH,

WINHEIGHT)

event_loop()

Page 359: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.5B

ilder

anze

igen

Neu

andi

esem

Prog

ram

msi

nddi

ebe

iden

Funk

tione

nload_pic()

und

blit_pic()

.Inload_pic()

wir

dei

nB

ildge

lade

n.D

iese

sB

ildw

ird

repr

äsen

tiert

durc

hei

neSu

rfac

e,di

esi

chm

anip

ulie

ren

läss

t,al

sobe

ispi

elsw

ei-

sedr

ehen

,bem

alen

und

skal

iere

n.D

ieM

etho

desurface.get_size()

Page 360: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

liefe

rtun

sdi

eG

röße

des

Bild

es.D

asB

ildw

ird

sosk

alie

rt,d

ass

esau

fda

sFe

nste

rpas

st.

blit_pic()

dien

tda

zu,d

asB

ildau

fda

sG

rafik

fens

ter

zuze

ichn

en.D

a-m

ites

mitt

iger

sche

int,

wir

dhi

erm

itH

ilfe

der

Surf

ace-

Grö

ßede

rR

and

ausg

erec

hnet

.surface.blit(pic,(w,h))

über

nim

mt

das

eige

ntli-

che

Blit

ten,

eine

Ope

ratio

n,di

eei

neSu

rfac

eau

fei

nen

ande

reko

pier

t.D

erPa

ram

eter(w,h)

isth

ierb

eide

rUrs

prun

gde

sB

ildes

.

Ebe

nfal

lsm

ittig

soll

eine

Schr

ifta

ufda

sB

ildge

brac

htw

erde

n.H

ierz

ula

den

wir

mitpygame.font.SysFont()

eine

Schr

ifta

rt"C

urie

r"in

50Pu

nkte

Grö

ße.M

itfont.render()

wird

dann

eine

neue

Surf

ace

erze

ugt,

die

eine

nko

nkre

ten

Text

unte

rA

nwen

dung

von

Ant

i-A

lias

mit

der

gew

ählte

nFa

rbe

repr

äsen

tiert

.Auc

hdi

ese

wir

dau

fde

nB

ildsc

hirm

geze

ichn

et.N

ach

beid

enB

lit-O

pera

tione

nw

ird

das

Gra

fikfe

nste

rauf

gefr

isch

t.

Page 361: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

15.5

Mus

ik

Das

folg

ende

Prog

ram

msp

ielt

WAV

und

OG

G/V

orbi

s-D

atei

en,d

ieau

fde

rK

omm

ando

zeile

über

gebe

nw

erde

nab

:

#!/usr/bin/python

import

pygame

import

sys

import

os.path

def

hinweis():

print"./sound

soundfile"

sys.exit()

if

len(sys.argv)

!=

2:

hinweis()

if

not

os.path.exists(sys.argv[1]):

hinweis()

pygame.init()

pygame.mixer.music.set_endevent(pygame.USEREVENT)

Page 362: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

pygame.mixer.music.load(sys.argv[1])

pygame.mixer.music.play()

while

True:

forevent

in

pygame.event.get():

ifevent.type

==

pygame.USEREVENT:

sys.exit()

Die

Funk

tion

pygame.init()

initi

alis

iert

auch

den

Mix

er.

pygame.mixer.music.set_endevent()

legt

ein

Ere

igni

sfe

st,

wel

ches

eint

riff

t,so

bald

eine

Soun

d-D

atei

zuen

dege

spie

ltis

t.D

ieau

fde

rK

omm

ando

zeile

über

gebe

neSo

undd

atei

wir

dm

itpygame.mixer.music.load()

gela

den,

ansc

hlie

ßend

mit

pygame.mixer.music.play()

abge

spie

lt.

Mit

Hilf

eei

ner

zusä

tzlic

hen

Funk

tion

pygame.mixer.set_volume(lautstärke)

könn

ten

wir

noch

die

Lau

tstä

rke

eins

telle

n.D

iese

rW

ertl

iegt

zwis

chen

0.0

und1.0

.Da

das

Abs

piel

enei

ner

Soun

ddat

eida

sPr

ogra

mm

über

daue

rnka

nn,

müs

sen

wir

hier

eine

Eve

nt-L

oop

eins

etze

n.D

asPr

ogra

mm

wür

deso

nstb

eend

etw

erde

n,

Page 363: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

bevo

rdie

Dat

eiab

gesp

ielt

wür

de.A

mE

nde

beko

mm

enw

irda

san

gefo

rder

teE

reig

nis,

das

Prog

ram

mka

nnsi

chda

nnzu

mri

chtig

enZ

eitp

unkt

been

den.

15.6

Zus

amm

enfa

ssun

g

Die

ses

Kap

itelh

atei

nen

Übe

rblic

küb

erM

öglic

hkei

ten

von

PyG

ame

gebo

ten.

Wir

könn

enge

nau

ein

Gra

fikfe

nste

röff

nen,

zeic

hnen

,auf

Erei

gnis

sere

agie

ren

und

selb

erE

reig

niss

eer

zeug

en.D

arüb

erhi

naus

habe

nw

irge

zeig

t,w

iem

anB

ilder

lädt

und

Text

eze

ichn

et.P

yGam

eka

nnm

ehr,

als

wir

hier

ausg

efüh

rtha

ben.

..E

xper

imen

tiere

nSi

ese

lbst

!

Page 364: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

16G

rafis

che

Ben

utze

robe

rfläc

hen

mit

Qt4

Indi

esem

Kap

itelg

ehte

sum

grafi

sche

Ben

utze

robe

rfläc

hen.

Wir

gebe

nei

nen

Einb

lick

indi

ePr

ogra

mm

ieru

ngm

itQ

tVer

sion

4,zu

derW

ikib

ooks

das

Buc

hQ

tfür

C++

-Anf

änge

r1al

szu

sätz

liche

sA

ngeb

otha

t.

1http://de.wikibooks.org/wiki/Qt%20f%FCr%20C%2B%2B-Anf%

E4nger

353

Page 365: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

16.1

Fens

ter,

öffn

eD

ich!

Die

erst

eA

nwen

dung

öffn

etei

nFe

nste

rund

hate

inen

Fens

tert

itel:

#!/usr/bin/python

import

sys

from

PyQt4

import

QtGui

class

Fenster(QtGui.QMainWindow):

def__init__(self):

QtGui.QMainWindow.__init__(self)

self.setWindowTitle("Python

unter

Linux")

self.resize(300,

300)

self.show()

app

=QtGui.QApplication(sys.argv)

f=

Fenster()

app.exec_()

Page 366: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.6gu

iqt1

.py

Wir

bind

enPyQt4.QtGui

ein,

umau

fEle

men

tede

rgra

fisch

enB

enut

zero

ber-

fläch

ezu

grei

fen

zukö

nnen

.DieFenster

klas

sew

irdvo

nQMainWindow

ab-

gele

itet,

eine

rKla

sse,

die

scho

ndi

ew

icht

igst

enE

lem

ente

eine

sH

aupt

fens

ters

mitb

ringt

.Es

istr

echt

einf

ach,

wie

wir

spät

erse

hen

wer

den,

aufG

rund

lage

die-

Page 367: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

serK

lass

eM

enüs

und

eine

Stat

usle

iste

hinz

uzuf

ügen

.setWindowTitle()

legt

den

Nam

enfü

rdas

Fens

terf

est,resize()

eine

Anf

angs

größ

e,di

ew

irdy

nam

isch

ände

rnkö

nnen

.Mitshow()

wir

dda

sO

bjek

tang

ezei

gt.

ImH

aupt

prog

ram

mer

zeug

enw

irei

nQApplication()

-Obj

ekt

und

un-

ser

Fens

ter.exec_()

star

tet

die

Anw

endu

ngun

dw

arte

t,bi

sda

sFe

nste

rge

schl

osse

nw

ird.

16.2

Sign

ale

empf

ange

n

Gra

fisch

eN

utze

robe

rfläc

hen

best

ehen

aus

Ele

men

ten,

inQ

tW

idge

tsge

-na

nnt,

die

sich

umdi

eIn

tera

ktio

nm

itB

enut

zern

küm

mer

n.W

idge

tssi

ndzu

mB

eisp

iel

Text

feld

er(QLabel

),E

dito

ren

(QTextEdit

)od

erK

nöpf

e(QPushButton

).V

iele

dies

erW

idge

tsne

hmen

Ben

utze

rein

gabe

nen

tgeg

en,

soka

nnei

nK

nopf

gedr

ückt

wer

den,

ein

Men

üpun

ktak

tivie

rtw

erde

n.Q

tsW

idge

tsse

nden

beiI

nter

aktio

nen

Sign

ale

aus,

die

man

vera

rbei

ten

kann

.Die

Page 368: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

folg

ende

Anw

endu

ngze

igt,

wie

man

Men

üser

zeug

tund

reag

iert

,wen

nsi

eak

tivie

rtw

erde

n:

#!/usr/bin/python

import

sys

from

PyQt4

import

QtCore,

QtGui

class

Fenster(QtGui.QMainWindow):

def__init__(self):

QtGui.QMainWindow.__init__(self)

self.setWindowTitle("Python

unter

Linux")

self.makeActions()

self.makeMenu()

self.show()

defmakeActions(self):

self._exitAction

=QtGui.QAction("&Ende",

None)

self._helpAction

=QtGui.QAction("Hilfe!",

None)

self.connect(self._exitAction,

QtCore.SIGNAL('triggered()'),

self.slotClose)

self.connect(self._helpAction,

QtCore.SIGNAL('triggered()'),

self.slotHelp)

defmakeMenu(self):

Page 369: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

menuBar

=self.menuBar()

fileMenu

=menuBar.addMenu("&Datei")

fileMenu.addAction(self._exitAction)

helpMenu

=menuBar.addMenu("&Hilfe")

helpMenu.addAction(self._helpAction)

defslotClose(self):

self.close()

defslotHelp(self):

QtGui.QMessageBox.information(None,

"Dies

ist

die

Hilfe",

"Hilf

dir

selbst,

sonst

hilft

dir

keiner!")

app

=QtGui.QApplication(sys.argv)

f=

Fenster()

app.exec_()

Page 370: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.7gu

iqt2

.py

Inne

rhal

bvo

nmakeActions()

defin

iere

nw

irzw

eiQAction()

-O

bjek

te.

Die

seO

bjek

teha

ben

eine

nN

amen

und

optio

nal

ein

Bild

.W

ann

imm

erQAction()

-Obj

ekte

aktiv

iert

wer

den,

sie

also

das

Sign

alQtCore.SIGNAL('triggered()')

send

en,s

oll

eine

Funk

tion

aufg

e-

Page 371: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

rufe

nw

erde

n,di

ew

irin

der

Kla

sse

defin

iert

habe

n,al

sobe

ispi

elsw

ei-

seslotClose()

.D

iese

Ver

knüp

fung

zwis

chen

den

beid

enO

bjek

ten,

QAction()

aufd

erei

nen

Seite

und

demFenster()

-Obj

ekta

ufde

rand

e-re

nSe

iteüb

erni

mm

tdie

Funk

tionconnect()

.

makeMenu()

erze

ugt

die

Men

üs.QtGui.QMainWindow

enth

ält

selb

stsc

hon

eine

Men

üzei

le,d

iem

ansi

chm

itmenuBar()

besc

haff

t.A

ndi

ese

Men

üzei

lefü

gtm

anm

itaddMenu()

eine

nM

enüe

intr

aghi

nzu.

Die

seM

e-nü

sfin

det

man

zuob

erst

inde

rM

enüz

eile

eine

rje

den

Anw

endu

ng.

Jede

sM

enü

kann

belie

big

viel

eQAction()

-Ein

träg

eha

ben.

Da

dies

eei

nen

ei-

gene

nTi

tel

habe

n,w

erde

nsi

eso

glei

chan

geze

igt.

Die

wei

tere

nM

etho

den

der

Kla

sse

bein

halte

ndi

eE

reig

niss

e:close()

schl

ießt

das

Fens

ter

und

QMessageBox.information()

zeig

tein

enin

form

ativ

enTe

xtan

.

Page 372: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

16.3

Meh

rW

idge

ts

Hau

ptfe

nste

rhab

enüb

liche

rwei

seze

ntra

leW

idge

ts.D

assi

ndzu

mei

stse

lbst

gesc

hrie

bene

Wid

get-K

lass

en,i

nde

nen

die

haup

tsäc

hlic

heIn

tera

ktio

nst

attfi

n-de

t,w

iezu

mB

eisp

ield

ieA

nzei

geei

nerW

ebse

iteim

Bro

wse

r.D

asfo

lgen

deB

eisp

ieli

mpl

emen

tiert

eine

nE

inka

ufsb

erat

er.D

erei

gent

liche

Ein

kauf

finde

tin

eine

mei

gene

nD

ialo

gst

att,

die

Zus

amm

enfa

ssun

ger

folg

tin

eine

rTab

elle

imH

aupt

fens

ter.

Zw

isch

enD

ialo

gun

dH

aupt

fens

terw

ird

eine

Nac

hric

htüb

erde

nK

aufw

unsc

hun

ddi

eZ

ahlu

ngsw

eise

ausg

etau

scht

.

#!/usr/bin/python

#-*-

coding:utf-8

-*-

import

sys

from

PyQt4

import

QtCore,

QtGui

class

Dialog(QtGui.QDialog):

"""Der

Einkaufsdialog"""

def__init__(self):

QtGui.QDialog.__init__(self)

self.setWindowTitle("Elektronischer

Einkauf")

Page 373: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

vbox

=QtGui.QVBoxLayout()

self._liste

=QtGui.QListWidget()

self._liste.addItem(u"Milch")

self._liste.addItem(u"Eier")

self._liste.addItem(u"Käse")

vbox.addWidget(self._liste)

group

=QtGui.QGroupBox("Zahlungsweise")

vboxGroup

=QtGui.QVBoxLayout()

self._r1

=QtGui.QRadioButton("Kreditkarte")

vboxGroup.addWidget(self._r1)

self._r2

=QtGui.QRadioButton("Bargeld")

vboxGroup.addWidget(self._r2)

self._r3

=QtGui.QRadioButton("Nachnahme")

vboxGroup.addWidget(self._r3)

self._r2.setChecked(True)

group.setLayout(vboxGroup)

vbox.addWidget(group)

fertigButton

=QtGui.QPushButton("Fertig")

self.connect(fertigButton,

QtCore.SIGNAL('clicked()'),

self.fertig)

vbox.addWidget(fertigButton)

self.setLayout(vbox)

self.show()

deffertig(self):

Page 374: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ware

=u"%s"

%self._liste.currentItem().text()

label

=""

forrb

in

[self._r1,

self._r2,

self._r3]:

ifrb.isChecked():

label

="%s"

%rb.text()

break

self.emit(QtCore.SIGNAL('signalEinkaufFertig'),

(ware,

label))self.accept()

class

Fenster(QtGui.QMainWindow):

"""Diese

Klasse

stellt

das

Hauptfenster

dar,

das

zentrale

Widget

ist

eine

Tabelle"""

def__init__(self):

QtGui.QMainWindow.__init__(self)

self.setWindowTitle("Python

unter

Linux")

self.makeActions()

self.makeMenu()

#Statuszeile

self._label

=QtGui.QLabel(u"Einkaufszähler")

self.statusBar().addWidget(self._label)

#Tabelle

self._tableWidget

=QtGui.QTableWidget(0,

2)

self._tableWidget.setHorizontalHeaderLabels(["Ware",

Page 375: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

"Zahlungsweise"])

self.setCentralWidget(self._tableWidget)

self.show()

defmakeActions(self):

self._dialogAction

=QtGui.QAction("Einkauf",

None)

self._exitAction

=QtGui.QAction("&Ende",

None)

self.connect(self._dialogAction,

QtCore.SIGNAL('triggered()'),

self.slotEinkauf)

self.connect(self._exitAction,

QtCore.SIGNAL('triggered()'),

self.slotClose)

defmakeMenu(self):

menuBar

=self.menuBar()

fileMenu

=menuBar.addMenu("&Datei")

fileMenu.addAction(self._dialogAction)

fileMenu.addSeparator()

fileMenu.addAction(self._exitAction)

defslotEinkauf(self):

"""Ruft

den

Einkaufsdialog

auf"""

d=

Dialog()

self.connect(d,

QtCore.SIGNAL('signalEinkaufFertig'),

self.slotEinkaufFertig)

d.exec_()

Page 376: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

defslotClose(self):

"""Wird

aufgerufen,

wenn

das

Fenster

geschlossen

wird"""

ret

=QtGui.QMessageBox.question(None,

"Ende?",

"Wollen

Sie

wirklich

schon

gehen?",

QtGui.QMessageBox.Yes,

QtGui.QMessageBox.No)

ifret

==

QtGui.QMessageBox.Yes:

self.close()

defslotEinkaufFertig(self,

ware):

"""Dieser

Slot

fügt

eine

Tabellenzeile

an

und

stellt

in

dieser

die

gekaufen

Waren

vor"""

numRows

=self._tableWidget.rowCount()

#Neue

Zeile

self._tableWidget.insertRow(numRows)

#Inhalte

einfügen

t1

=QtGui.QTableWidgetItem(ware[0])

t2

=QtGui.QTableWidgetItem(ware[1])

self._tableWidget.setItem(numRows,

0,

t1)

self._tableWidget.setItem(numRows,

1,

t2)

#Update

Statuszeile

text

=u"Heute

wurden

%d

Aktionen

getätigt"

%(numRows

+1)

self._label.setText(text)

if

__name__==

"__main__":

Page 377: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

app

=QtGui.QApplication(sys.argv)

f=

Fenster()

app.exec_()

Abb

.8gu

iqt3

.py

Anw

endu

ngA

bb.9

guiq

t3.p

yD

ialo

gfen

ster

Page 378: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Der

Ein

kauf

sber

ater

best

eht

aus

zwei

Ele

men

ten,

näm

lich

dem

Dia

log,

ei-

ner

vonQDialog

abge

leite

ten

Kla

sse,

und

dem

Hau

ptfe

nste

r.D

erD

ialo

gw

ird

ange

zeig

t,w

enn

die

Met

hode

slotEinkauf()

vom

Hau

ptfe

nste

rau

fger

ufen

wur

de.

Der

Dia

log

best

eht

aus

eini

gen

inei

nand

erge

scha

chte

l-te

nE

lem

ente

n:In

nerh

alb

des

vert

ikal

enL

ayou

ts(QVBoxLayout

)w

erde

nei

nL

ist-

Wid

get(QListWidget

),ei

neG

roup

-Box

(QGroupBox

)un

dei

nK

nopf

(QPushButton

)ei

ngef

ügt.

Der

Lis

tbox

wer

den

mitaddItem()

eini

geB

eisp

ielw

aren

hinz

ugef

ügt.

Die

Gro

up-B

oxen

thäl

tei

nei

gene

sve

rtik

ales

Lay

out,

mit

dem

sie

drei

Aus

wah

lsch

alte

r(QRadioButton

)zu

rA

ngab

ede

rZ

ahlu

ngsw

eise

verw

alte

t,vo

nde

nen

eine

rvo

rsel

ektie

rt(self._r2.setChecked(True)

)ist

.

Wir

dde

rKno

pf("

Fert

ig")

gedr

ückt

,sol

ldie

Met

hode

Dialog.fertig()

aufg

eruf

enw

erde

n.In

dies

erM

etho

dew

erde

ndi

eA

usw

ahlk

nöpf

eab

gefr

agt,

gena

uei

nerv

onih

nen

isti

mm

erak

tivie

rt.E

benf

alls

wir

dde

rim

Lis

t-W

idge

tak

tivie

rte

Text

abge

frag

t.So

bald

beid

eIn

form

atio

nen

vorl

iege

n,w

ird

ein

Sign

alab

gesc

hick

t.D

iese

sbe

sorg

tdie

Met

hodeemit()

,die

das

Sign

alw

ie

Page 379: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

auch

ein

Tupe

lm

itIn

form

atio

nen

erw

arte

t.A

nsch

ließe

ndw

ird

der

Dia

log

gesc

hlos

sen.

Das

Hau

ptfe

nste

ren

thäl

tMen

üs,e

ine

Stat

usze

ile,i

nde

rsi

chei

neTe

xtfe

ld(QLabel

)be

finde

tw

ieau

chal

sze

ntra

les

Ele

men

tei

neTa

belle

.Wir

dpe

rM

enü

die

Met

hode

slotEinkauf()

aufg

eruf

en,e

rste

lltsi

ede

nbe

schr

ie-

bene

nD

ialo

g,ve

rknü

ftda

svo

ndi

esem

ausg

ehen

deSi

gnal

mit

dem

Slot

slotEinkaufFertig()

und

ruft

dess

enexec_()

-Met

hode

auf.

slotEinkaufFertig()

enth

älti

mPa

ram

eterware

das

Tupe

lmit

den

aktu

elle

nE

inka

ufsi

nfor

mat

ione

n.D

iese

Info

rmat

ione

nso

llen

indi

eTa

bel-

lege

schr

iebe

nw

erde

n,w

obei

dies

ezu

erst

umei

neZ

eile

wac

hsen

mus

s.D

ann

wer

den

pro

Spal

teei

nQTableWidgetItem

erst

ellt,

dies

ew

erde

npe

rsetItem(Reihe,Spalte,Item)

indi

eTa

belle

eing

efüg

t.Zu

gu-

terL

etzt

wir

dda

sL

abel

derS

tatu

szei

leau

fden

neus

ten

Stan

dge

brac

ht.

Page 380: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

16.4

Des

ign-

Serv

er

Der

Ein

kauf

sfüh

rerb

rach

tees

ande

nTa

g:D

ashä

ndis

che

schr

eibe

nvo

nW

id-

gets

und

das

pass

ende

Plaz

iere

nde

rsel

bige

nau

fei

nem

Fens

ter

mac

htvi

elM

ühe.

Vie

lle

icht

erge

htes

,wen

nm

ansi

chdi

eFe

nste

run

dde

ren

Inha

ltezu

sam

men

klic

kt.D

asPr

ogra

mm

hier

zuhe

ißtD

esig

ner

(designer-qt4

).M

itse

iner

Hilf

epl

azie

rtm

anau

fFen

ster

ndi

eW

idge

ts,d

iem

anbe

nötig

tund

layo

utet

sie

aufg

rafis

che

Wei

se.

Page 381: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.10

Des

igne

rA

bb.1

1U

nser

Dia

logf

enst

er

Das

folg

ende

Prog

ram

mbe

nötig

tnur

drei

Lab

els

inei

nem

Dia

log-

Fens

ter,

von

dene

nzw

eilabel_client1

undlabel_client2

heiß

en.A

ufdi

ese

beid

enLa

bels

wol

len

wir

imQ

uellt

extv

erw

eise

n.Sc

haue

nSi

esi

chhi

erzu

bitte

Page 382: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

das

Bild

Uns

erD

ialo

gfen

ster

an.S

peic

hern

Sie

die

Des

igne

r-D

atei

unte

rdem

Nam

enserver.ui

ab.S

ieen

thäl

tin

XM

L-N

otat

ion

alle

Info

rmat

ione

nüb

erda

sD

ialo

g-Fe

nste

r.

Um

den

Dia

log

fürP

ytho

nbe

nutz

barz

um

ache

n,is

tnoc

hei

nZ

wis

chen

schr

ittnö

tig:A

usga

beuserlocalhost:$̃pyuic4

-o

server_ui.py

server.ui

(keine

Ausgabe)

Sie

erha

lten

eine

Dat

eim

itde

mN

amen

server_ui.py

.Die

sekö

nnen

Sie

dire

ktin

den

Pyth

on-C

ode

impo

rtie

ren.

Das

Prog

ram

m,w

elch

esw

irnu

nbe

spre

chen

wol

len,

iste

inSe

rver

,der

Ver

-bi

ndun

gsin

form

atio

nen

bere

ithä

lt.M

anka

nnsi

chan

ihm

anm

elde

n,w

obei

erzw

eiC

lient

sak

zept

iert.

Die

sen

send

eter

eine

nW

illko

mm

ensg

ruß

und

schr

eibt

aufd

enD

ialo

gei

nen

Ver

bind

ungs

hinw

eis.

Wir

dei

nC

lient

been

det,

sore

gis-

trie

rtde

rSe

rver

das

istb

erei

t,ei

new

eite

reV

erbi

ndun

gzu

akze

ptie

ren.

Der

Serv

ertu

tals

oni

chts

als

zum

erke

n,ob

gera

deei

nC

lient

verb

unde

nis

tode

rni

cht.

Page 383: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

import

sys

from

server_ui

import

Ui_Dialog

from

PyQt4

import

QtCore,

QtGui,

QtNetwork

class

Dialog(QtGui.QDialog,

Ui_Dialog):

def__init__(self):

QtGui.QDialog.__init__(self)

self.setupUi(self)

defconnect(self,

num):

ifnum

==

1:

self.label_client1.setText

("Client1

connected")

else: self.label_client2.setText

("Client2

connected")

defdisconnect(self,

num):

ifnum

==

1:

self.label_client1.setText

("Client1

disconnected")

else: self.label_client2.setText

("Client2

disconnected")

class

Server(QtNetwork.QTcpServer):

Page 384: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def__init__(self,

numClients):

QtNetwork.QTcpServer.__init__(self)

self._numClientsWanted

=numClients

self._numClients

=0

self.address

=QtNetwork.QHostAddress(QtNetwork.QHostAddress.LocalHost)

#socketInfo:

[(socket,

connected,

num),

...]

self.socketInfo

=[]

fori

in

xrange(numClients):

self.socketInfo.append((None,

False,

i+1))

ret

=self.listen(self.address,

6000)

self.connect(self,

QtCore.SIGNAL("newConnection()"),

self.connection)

defconnection(self):

ifself.hasPendingConnections():

print

"connection

available",

socket

=self.nextPendingConnection()

ifself._numClients

<self._numClientsWanted:

self.connect(socket,

QtCore.SIGNAL("disconnected()"),

self.dis)

fori,

(p,

c,

n)

in

enumerate(self.socketInfo):

ifc

==

False:

self.socketInfo[i]

=(socket,

True,

n)

print

"accepted"

Page 385: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

msg

="You

are

accepted.

Client

%d"

%n

socket.write(msg)

self.emit(QtCore.SIGNAL("connected"),

n)

break

self._numClients

+=

1else: print"rejected"

socket.close()

defdis(self):

print"socket

disconnected"

self._numClients

=0

fori,

(p,

c,

n)

in

enumerate(self.socketInfo):

ifc: ifp.state()

==

QtNetwork.QAbstractSocket.UnconnectedState:

p.close()

self.socketInfo[i]

=(None,

False,

n)

self.emit(QtCore.SIGNAL("disconnected"),

n)

else: self._numClients

+=

1

app

=QtGui.QApplication(sys.argv)

window

=Dialog()

server

=Server(2)

Page 386: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

app.connect(server,

QtCore.SIGNAL("connected"),

window.connect)

app.connect(server,

QtCore.SIGNAL("disconnected"),

window.disconnect)

window.show()

sys.exit(app.exec_())

Die

Des

igne

r-D

atei

wir

dm

itfromserver_uiimportUi_Dialog

eing

ebun

den.

Der

Nam

eis

tin

der

Pyth

on-D

atei

server_ui.py

beka

nnt.

Ein

Dia

log

auf

der

Bas

isw

ird

erst

ellt,

inde

mer

vom

QDialog

und

dem

Ui_Dialog

abge

leite

tw

ird:

classDialog(QtGui.QDialog,Ui_Dialog)

.D

ieM

etho

desetupUi(self)

initi

alis

iert

dies

enD

ialo

gan

schl

ieße

nd.

Der

Res

tde

rK

lass

edi

entd

azu,

die

Ver

bind

ungs

info

rmat

ione

nan

zuze

igen

.

Der

Serv

erw

irdvo

nde

rBas

iskl

asseQTcpServer

abge

leite

t.D

erSe

rver

soll

max

imal

2Ve

rbin

gung

engl

eich

zeiti

gha

ben,

und

aufd

emei

gene

nH

ost(

Loca

lho

st,QHostAddress(QtNetwork.QHostAddress.LocalHost))

lauf

en,s

eine

Port

adre

sse

laut

et60

00.socketInfo

ist

eine

Lis

te,d

iedi

eC

lient

ssp

eich

ert,

wob

eije

der

Clie

ntdu

rch

eine

nT

CP-

Sock

et,

eine

nH

in-

wei

sda

rauf

,ob

die

Ver

bind

ung

aktiv

ist

und

eine

eind

eutig

eN

umm

erge

-

Page 387: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

kenn

zeic

hnet

ist.

Mitlisten(self.address,6000)

wir

dau

fVer

bin-

dung

swün

sche

der

Clie

nts

gew

arte

t.Tr

effe

ndi

ese

ein,

wir

ddi

eM

etho

deconnection()

aufg

eruf

en.F

alls

wir

den

Ver

bind

ungs

wun

sch

akze

ptie

ren,

wird

mitnextPendingConnection()

derS

ocke

tdes

Clie

nts

geho

ltun

dan

pass

ende

rSte

llein

die

Stru

ktursocketInfo

eing

efüg

t.D

emC

lient

wird

eine

Nac

hric

htge

schi

cktu

ndde

mD

ialo

gw

ird

ange

zeig

t,da

sssi

chei

nC

lient

verb

unde

nha

t.

Falls

sich

ein

Clie

ntve

rabs

chie

det,

beis

piel

swei

se,

wei

ldi

eD

SL-L

eitu

ngun

terb

roch

enw

urde

oder

derN

utze

rdas

Clie

nt-P

rogr

amm

aufa

nder

eW

eise

been

dete

,wir

ddi

eM

etho

dedis()

aufg

eruf

en.S

iefin

deth

erau

s,w

elch

erC

lient

sich

abge

mel

deth

atun

dgi

bten

tspr

eche

ndN

achr

icht

darü

bera

us.

Um

das

Prog

ram

mzu

test

en,

benu

tzen

Sie

einf

ach

das

Prog

ram

mTe

lnet

.St

arte

nSi

ehi

erzu

den

Serv

erun

dru

fen

aufe

iner

ande

ren

Kon

sole

folg

ende

sau

f:

Aus

gabe

userlocalhost:$̃telnet

localhost

6000

Page 388: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Trying

127.0.0.1...

Connected

to

localhost.

Escape

character

is

'ˆ]'.

You

are

accepted.

Client

1

Soba

ldSi

esi

chve

rbun

den

habe

n,w

irddi

eses

auch

imD

ialo

gfen

ster

ange

zeig

t.

16.5

Zus

amm

enfa

ssun

g

Indi

esem

Kap

itel

habe

nSi

edi

eG

rund

züge

der

Prog

ram

mie

rung

mit

dem

Tool

kitQ

tVer

sion

4ke

nnen

gele

rnt.

Wir

habe

nei

nige

Wid

gets

besp

roch

en,d

asSi

gnal

-Slo

t-Kon

zept

kenn

enge

lern

tund

Serv

er-P

rogr

amm

ieru

ngal

sThe

ma

für

Fortg

esch

ritte

neB

enut

zerb

espr

oche

n.D

asK

apite

lwur

dem

itei

nerE

infü

hrun

gin

den

Qt-

Des

igne

rabg

erun

det.

Page 389: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 390: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

17G

rafis

che

Ben

utze

robe

rfläc

hen

mit

wxP

ytho

n

Sie

habe

nnu

nei

nen

wei

tere

nA

bsch

nitt

erre

icht

,der

sich

mit

grafi

sche

nB

enut

-ze

robe

rfläc

hen

inPy

thon

besc

häfti

gt.D

iesm

alm

itde

rpla

ttfor

mun

abhä

ngig

en,

aufw

xWid

gets

aufb

auen

den

Var

iant

ew

xPyt

hon1 .

Gen

auer

eD

etai

lszu

den

beso

nder

enA

spek

ten

wxP

ytho

nsfin

den

sich

inde

nje

wei

ligen

Abs

chni

tten.

1http://de.wikipedia.org/wiki/WxPython

379

Page 391: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

17.1

Vorb

erei

tung

und

Inst

alla

tion

Da

wxP

ytho

nni

chtz

umSt

anda

rdre

pert

oire

eine

rPy

thon

inst

alla

tion

gehö

rt,

mus

ses

erst

inst

allie

rtw

erde

n-

und

zwar

über

all

da,

wo

die

Anw

endu

ngsp

äter

ausg

efüh

rtw

erde

nso

ll.E

sgi

btIn

stal

latio

nspa

kete

füra

llem

öglic

hen

Bet

rieb

ssys

tem

e.In

den

mei

sten

Lin

ux-D

istr

ibut

ione

nfin

dets

ich

wxP

ytho

nim

Pake

tman

ager

.Fal

lsda

sbe

iIhn

enni

chtd

erFa

llis

t,kö

nnen

Sie

Pyth

ons

setu

ptoo

ls2

oder

ein

Inst

alla

tions

pake

t3ve

rwen

den.

Die

erst

eV

aria

nte

sollt

edi

eei

nfac

hste

sein

,fun

ktio

nier

tebe

imir

imTe

stab

er(o

hne

größ

ere

Schr

itte

zurA

ufkl

ärun

gde

sPr

oble

mes

)lei

dern

icht

:

Aus

gabe

userlocalhost:$̃sudo

easy_install

wxpython

Searching

for

wxpython

Reading

http://pypi.python.org/simple/wxpython/4

2http://pypi.python.org/pypi/setuptools

3http://www.wxpython.org/download.php#binaries

4http://pypi.python.org/simple/wxpython/

Page 392: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Reading

http://wxPython.org/5

Reading

http://wxPython.org/download.php6

Best

match:

wxPython

src-2.8.9.1

Downloading

http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.9.1.tar.bz27

Processing

wxPython-src-2.8.9.1.tar.bz2

error:

Couldn't

find

asetup

script

in

/tmp/easy_-

install-PkAhhW/wxPython-src-2.8.9.1.tar.bz2

Lass

enSi

esi

chda

von

aber

nich

tbei

rren

.Ver

mut

lich

brau

chen

Sie

nuri

nIh

rem

Pake

tman

ager

nach

wxP

ytho

nzu

such

enun

dal

les

ande

rege

htvo

nse

lbst

.

5http://wxPython.org/

6http://wxPython.org/download.php

7http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.

9.1.tar.bz2

Page 393: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

17.2

Plop

p!

...od

erw

elch

esG

eräu

sch

auch

imm

erSi

em

itde

ffne

nei

nes

Fens

ters

asso

ziie

ren:

Mit

wxP

ytho

ner

reic

hen

Sie

dies

enPu

nktj

eden

falls

einf

ach

und

schn

ell:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

wx

if

__name__==

'__main__':

app

=wx.PySimpleApp()

frame

=wx.Frame(None,

title="Hallo

Welt!")

frame.Show()

app.MainLoop()

Kur

zzu

rErl

äute

rung

:

InZ

eile

4im

port

iere

nw

irda

sPa

ketwx

,w

elch

esal

leK

ompo

nent

envo

nw

xPyt

hon

bein

halte

t.In

älte

ren

Bei

spie

len

könn

ten

sich

auch

noch

die

Var

i-

Page 394: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

ante

n"importwxPythonaswx

"od

er"fromwxPythonimport

*"

finde

n.Ve

rwen

den

Sie

dies

eni

cht!

Sie

sind

vera

ltet.

Ster

nche

n-Im

port

e-

wie

inde

rzw

eite

nV

aria

nte

-sin

dau

ßerd

emge

nere

llni

chtg

ern

gese

hen.

InZ

eile

7w

ird

das

App

likat

ions

-Obj

ekt

erst

ellt.

Ohn

edi

eses

Obj

ekt

geht

erst

mal

garn

icht

s.B

eide

rErs

tellu

ngw

ird

das

grafi

sche

Syst

em,d

erM

essa

ge-

bzw

.Eve

ntha

ndle

run

dal

les

wei

tere

wic

htig

ein

itial

isie

rt.D

ieN

utzu

ngvo

nwx.PySimpleApp()

mac

htda

sga

nze

amun

kom

pliz

iert

este

n.

Zei

le8

erze

ugte

inFr

ame-

Obj

ekt.

Die

sers

tellt

inun

sere

mB

eisp

ield

asH

aupt

-fe

nste

rda

r.E

ine

App

likat

ion

kann

aus

meh

rere

nFr

ames

best

ehen

,abe

rnu

rei

nen

Hau

pt-F

ram

eha

ben.

Alle

nw

eite

ren

mus

sda

nnal

ser

sten

Para

met

erde

nih

nen

über

geor

dnet

enFr

ame

über

gebe

nw

erde

n.A

ndi

eser

Stel

lew

ird

hierNone

über

gebe

n,da

ein

Hau

ptfr

ame

kein

enPa

rent

hat.

Bis

her

gibt

esfu

erdi

esen

Para

met

erau

chke

inen

Stan

dard

-Wer

t,so

das

min

dest

ensNone

ange

gebe

nw

erde

nm

uss.

Die

folg

ende

Zei

le9

sorg

tdaf

ür,d

ass

der

Fram

eau

chan

geze

igtw

ird.

Der

Fram

eka

nnzw

arau

chdy

nam

isch

imla

ufen

den

Bet

rieb

erze

ugtu

ndva

riie

rt

Page 395: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

wer

den,

aber

die

initi

alen

Ele

men

teso

llten

erze

ugtw

erde

n,be

vor.Show()

ausg

efüh

rtw

ird.

Abs

chlie

ßend

star

ten

wir

die

Mai

nLoo

p,al

sodi

eH

aupt

-Eve

ntsc

hlei

fevo

nw

xWid

gets

.Die

seSc

hlei

felä

ufts

ola

nge,

bis

das

Hau

ptfe

nste

r(ge

naue

ralle

Thr

eads

)in

irgen

dein

erW

eise

gesc

hlos

sen

wir

d.

Bra

vo!N

unha

ben

Sie

das

erst

eFe

nste

rers

tellt

und

auch

scho

nei

nige

sgr

und-

lege

ndes

uebe

rwxP

ytho

nge

lern

t.D

asw

arau

chga

rnic

htso

schw

er,o

der?

17.3

Ein

enSc

hritt

wei

ter

Kom

plex

ere

Anw

endu

ngen

erbe

nüb

liche

rwei

sevo

nH

aupt

elem

ente

nw

iewx.Frame

ab.B

eisp

iels

wei

seso

:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

Page 396: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

import

wx

class

MyFrame(wx.Frame):

def__init__(self):

wx.Frame.__init__(self,

None,

title="Hallo

Welt!")

self.panel

=wx.Panel(self)

self.label

=wx.StaticText(

self.panel,

label

="Python

unter

Linux",

pos

=(5,

5),

)

if

__name__==

'__main__':

app

=wx.PySimpleApp()

frame

=MyFrame()

frame.Show()

app.MainLoop()

Jena

chA

nfor

deru

ngw

ird

beis

piel

swei

seau

chvo

nw

x.Pa

nel

abge

erbt

.Im

Lau

fedi

eses

Tuto

rial

sw

erde

nw

irei

nen

tspr

eche

ndes

Bei

spie

lbeh

ande

ln.

Page 397: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

17.4

Win

dow

s

Inw

xst

amm

enal

lesi

chtb

aren

Ele

men

tevo

nw

x.W

indo

wab

.So

mit

wir

dje

des

ents

prec

hend

eE

lem

ent

von

einf

ache

mTe

xtbi

shi

nzu

rM

enül

eis-

teau

chw

indo

wge

nann

t.D

abei

unte

rsch

eide

nw

irzu

mei

nen

zwis

chen

Con

tain

erob

jekt

en,d

iew

eite

reW

indo

ws

enth

alte

nkö

nnen

,zum

Bei

spie

lwx.Frame

,wx.Panel

und

zum

ande

ren

Con

trol

s:wx.StaticText

,wx.TextCtrl

,wx.Button

.Die

seU

nter

sche

idun

gis

tzw

aret

was

ober

-flä

chlic

h,ab

erim

Mom

entv

öllig

ausr

eich

end

füru

ns.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

wx

class

MyFrame(wx.Frame):

def__init__(self):

wx.Frame.__init__(self,

None,

title="Hallo

Welt!")

self.panel

=wx.Panel(self)

Page 398: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

self.label

=wx.StaticText(

self.panel,

label

="Python

unter

Linux",

pos

=(5,

5),

)

if

__name__==

'__main__':

app

=wx.PySimpleApp()

frame

=MyFrame()

frame.Show()

app.MainLoop()

Die

Mar

kier

ung

zeig

tden

derz

eitig

enH

aupt

teil

des

Prog

ram

mes

.Fal

lsSi

eZ

eile

9ni

chtg

anz

vers

tehe

n,sc

haue

nSi

eno

chei

nmal

zurü

ckin

das

Kap

itel

OO

P8 .

Das

Hau

ptpa

neld

esFr

ames

wir

din

Zei

le10

ange

legt

und

dann

mit

eine

mei

nfac

hen

Text

vers

ehen

.Die

Para

met

erfü

rwx.StaticText

beko

mm

en

8http://de.wikibooks.org/wiki/Python_unter_Linux:_Rund_um_

OOP#Vererbung

Page 399: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

derÜ

bers

icht

halb

erje

wei

lsei

neei

gene

Zeile

und

sollt

ense

lbst

erkl

ären

dse

in.

Näh

ere

Info

rmat

ione

nfin

den

Sie

imen

tspr

eche

nden

Ein

trag

derA

PI9 .

Hie

rsi

eht

man

gut

den

grun

dleg

ende

nA

ufba

uei

nes

Fens

ters

.D

asPa

nel

dien

tals

Elte

rn-E

lem

entf

uera

llew

eite

ren

Con

trol

s.E

ser

sche

intm

anch

mal

nich

tnot

wen

dig,

sollt

eab

erim

mer

genu

tztw

erde

n.M

anch

eSy

stem

ekö

nnen

Con

trols

nich

tkor

rekt

oder

garn

icht

dars

telle

n,w

enn

sie

dire

ktau

fdem

Fram

ean

gebr

acht

wer

den.

17.5

Eve

nts

Alle

mod

erne

ngr

afisc

hen

Anw

endu

ngen

arbe

iten

Even

tbas

iert.

Ihre

Elem

ente

send

enSi

gnal

ean

den

soge

nann

ten

Eve

ntha

ndle

rund

empf

ange

nsi

evo

nih

m.

Der

Löw

enan

teil

der

Funk

tiona

lität

wir

dso

real

isie

rt.H

ier

wer

den

wir

nun

dara

ufei

ngeh

en,w

iem

anE

vent

sin

wxP

ytho

nbe

nutz

t.

9http://www.wxpython.org/docs/api/wx.StaticText-class.html

Page 400: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

wx

class

MyFrame(wx.Frame):

def__init__(self):

wx.Frame.__init__(self,

None,

title="Hallo

Welt!")

self.panel

=wx.Panel(self)

self.label

=wx.StaticText(

self.panel,

label

="Python

unter

Linux",

pos

=(5,

5),

size

=(self.Size.width

-10,

-1),

) self.input

=wx.TextCtrl(

self.panel,

pos

=(5,

30),

size

=(100,

-1),

) self.btn_text

=wx.Button(

Page 401: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

self.panel,

label

="Text

ändern",

pos

=(110,

30),

size

=(95,

-1),

) self.btn_text.Bind(wx.EVT_BUTTON,

self.on_change_text)

self.btn_title

=wx.Button(

self.panel,

label

="Titel

ändern",

pos

=(210,

30),

size

=(95,

-1),

) self.btn_title.Bind(wx.EVT_BUTTON,

self.on_change_title)

defon_change_text(self,

evt):

self.label.Label

=self.input.Value

defon_change_title(self,

evt):

self.Title

=self.input.Value

if

__name__==

'__main__':

app

=wx.PySimpleApp()

Page 402: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

frame

=MyFrame()

frame.Show()

app.MainLoop()

Das

Bei

spie

lzei

gtei

neei

nfac

heA

nwen

dung

von

But

tons

.Mit

Hilf

ede

rBin

d-M

etho

dew

erde

nde

rE

vent

-Bin

der

wx.

EV

T_B

UT

TO

Nun

dei

neM

etho

dean

eine

nK

nopf

gebu

nden

.Die

seM

etho

dew

ird

dann

aufg

eruf

en,s

obal

dde

rK

nopf

gedr

ueck

twir

d.

Alle

Eve

nt-B

inde

rfan

gen

mit

EV

T_an

und

sind

kom

plet

tgro

ßge

schr

iebe

n.Im

von

mir

genu

tzte

nw

xPyt

hon

2.8.

9.1

gibt

es23

3so

lche

rO

bjek

tem

itm

eist

selb

ster

klär

ende

mN

amen

.Ein

ige

davo

nw

erde

nw

irhi

erim

Lau

fede

sPr

ogra

mm

aufb

aus

noch

kenn

enle

rnen

.

Page 403: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Det

ails

Wie

funk

tioni

erte

inE

vent

?

Obj

ekte

oder

Met

hode

nkö

nnen

jede

rzei

tEve

nts

ausl

ösen

.Dab

eier

zeug

ensi

eIn

stan

zen

von

ents

prec

hend

enE

vent

-Kla

ssen

und

schi

cken

dies

eda

nnan

den

Eve

ntH

andl

er.

Bei

dies

emsi

ndau

chdi

eB

indu

ngen

derE

vent

sge

spei

cher

t,so

das

erdi

een

tspr

eche

nden

Met

hode

nm

itde

rIns

tanz

des

ausg

elös

ten

Eve

nts

aufr

ufen

kann

.

17.6

Anm

erku

ngen

Page 404: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18G

rafis

che

Ben

utze

robe

rfläc

hen

mit

GT

K+

Indi

esem

Kap

itelg

ehte

sum

die

Prog

ram

mie

rung

von

grafi

sche

nB

enut

zer-

ober

fläch

enm

itG

TK

+.G

TK

+w

ird

inA

nwen

dung

enw

ieG

IMP1

benu

tzt

und

bild

etdi

eB

asis

für

die

Des

ktop

-Um

gebu

ngG

NO

ME

2 .Fa

llsSi

em

ehr

Info

rmat

ione

nzu

rPr

ogra

mm

ieru

ngin

GT

K+

inan

dere

nSp

rach

ensu

chen

,w

erde

nSi

eim

Wik

ibuc

hG

TK

3fü

ndig

.In

dies

emK

apite

lgeb

enw

irih

nen

1http://de.wikibooks.org/wiki/GIMP

2http://de.wikibooks.org/wiki/GNOME

3http://de.wikibooks.org/wiki/GTK

393

Page 405: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

eine

nE

inbl

ick

indi

ePr

ogra

mm

ieru

ngm

itde

mM

odul

pyth

on-g

tk2,

wel

ches

Sie

sich

mit

ihre

mPa

ketm

anag

erle

icht

inst

allie

ren

könn

en.

18.1

Das

erst

eFe

nste

r

Das

folg

ende

Prog

ram

möf

fnet

ein

Fens

teru

ndst

ellt

Text

inei

nem

Lab

elda

r.A

nsch

ließe

ndw

arte

tdas

Prog

ram

mda

rauf

,bee

ndet

zuw

erde

n:

#!/usr/bin/python

import

gtk

class

HalloWelt(object):

def__init__(self):

"""

Initialisiert

das

Fenster

"""

self.window

=gtk.Window(gtk.WINDOW_TOPLEVEL)

self.window.set_title("Mein

erstes

Fenster")

self.window.set_default_size(300,

100)

self.window.connect("delete_event",

self.event_delete)

Page 406: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

self.window.connect("destroy",

self.destroy)

label

=gtk.Label("Hallo,

Welt!")

self.window.add(label)

label.show()

self.window.show()

defevent_delete(self,

widget,

event,

data=None):

"""

reagiert

auf

'delete_event'

"""

returnFalse

defdestroy(self,

data=None):

"""

reagiert

auf

'destroy'

"""

gtk.main_quit()

defmain(self):

"""

Nachrichtenschleife

"""

gtk.main()

if

__name__==

"__main__":

hallo

=HalloWelt()

hallo.main()

Die

Kla

sseHalloWelt

enth

ältv

ierM

etho

den.

Page 407: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Inne

rhal

bvo

n__init__()

wird

mitgtk.Window()

ein

neue

sso

gena

nn-

tesT

op-L

evel

-Fen

ster

erze

ugt.

Esgi

btve

rsch

iede

neA

rten

von

Fens

tern

,auf

die

wir

nich

tein

gehe

n.D

iese

sTop

-Lev

el-F

enst

eris

tgen

auda

s,w

asm

ansi

chun

ter

eine

mPr

ogra

mm

-Fen

ster

vors

tellt

.set_title()

legt

eine

nFe

nste

rtite

lfes

tun

dset_default_size()

eine

Anf

angs

größ

e.D

ieG

röße

des

Fens

ters

istz

urL

aufz

eitä

nder

bar.

Die

näch

sten

beid

enFu

nktio

nen

verk

nüpf

enE

reig

niss

em

itso

gena

nnte

nC

allb

ack-

Met

hode

n.D

iese

wer

den

aufg

eruf

en,w

enn

das

Erei

gnis

"delete_-

event

"od

er"destroy

"au

ftri

tt.D

asdelete_event

wir

dim

mer

dann

aufg

eruf

en,w

enn

derA

nwen

derv

ersu

cht,

das

Fens

terz

usc

hlie

ßen.destroy

erfo

lgtd

ann,

wen

nda

sFe

nste

rech

tges

chlo

ssen

wird

.Die

ses

Sign

alka

nnm

anim

Geg

ensa

tzzu

mdelete_event

nich

tabw

eise

n.

Nun

fehl

tuns

noch

ein

Lab

el,d

asw

irm

itgtk.Label()

erze

ugen

und

mit

window.add()

dem

Fens

terh

inzu

füge

n.D

asL

abel

wie

auch

das

Fens

ter

wer

den

sich

tbar

gem

acht

.Hie

rzu

dien

tdie

Funk

tionshow()

.

Page 408: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Die

Met

hode

event_delete()

istv

erkn

üpft

mit

demdelete_event

.A

ndi

eser

Stel

lekö

nnte

das

Prog

ram

mfr

agen

,ob

derA

nwen

derd

asPr

ogra

mm

wir

klic

hbe

ende

nm

öcht

e.G

ibtd

ieM

etho

deFalse

zurü

ck,w

irddestroy

als

neue

sSi

gnal

gese

ndet

.Gib

tmanTrue

zurü

ck,w

irdda

sEr

eign

isab

gew

ie-

sen.

Die

Met

hodedestroy()

hatn

undi

eA

ufga

be,d

asFe

nste

rzu

zers

töre

n,in

dies

emFa

llso

lldi

ege

sam

teA

nwen

dung

been

detw

erde

n.

Jede

Anw

endu

ng,d

iegr

afisc

heN

utze

robe

rfläc

hen

benu

tzt,

verf

ügtü

bere

ine

Hau

ptsc

hlei

fe,i

nde

rN

achr

icht

enan

ihre

Em

pfän

ger

wei

terg

elei

tetw

erde

n.So

lche

Nac

hric

hten

könn

enA

nwen

derw

ünsc

hew

ieda

sB

eend

ende

rAnw

en-

dung

sein

,Mau

sbew

egun

gen

oder

das

Drü

cken

von

Knö

pfen

.Die

seH

aupt

-sc

hlei

few

ird

mitgtk.main()

bere

itges

tellt

.

Page 409: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18.2

Lay

out

Ben

utzt

man

meh

rere

grafi

sche

Ele

men

te,w

iezu

mB

eisp

ielm

ehre

reL

abel

s,ka

nnm

anm

itH

ilfe

von

Lay

out-

Funk

tione

nbe

stim

men

,wie

dies

eE

lem

ente

ange

ordn

etw

erde

n.So

läss

tsic

hei

nH

aupt

fens

term

itei

nem

Tabe

llenl

ayou

tve

rseh

enod

erin

waa

gere

chte

und

senk

rech

teB

oxen

unte

rtei

len.

18.2

.1Ta

belle

nlay

out

Das

einf

achs

teLa

yout

istd

ieA

nord

nung

von

Elem

ente

nin

Form

eine

rTab

elle

.Fo

lgen

des

Bei

spie

lver

deut

licht

das:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

gtk

class

Tabelle1(object):

Page 410: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

def__init__(self):

self.window

=gtk.Window(gtk.WINDOW_TOPLEVEL)

self.window.set_title("Mein

erstes

Fenster")

self.window.set_default_size(300,

100)

self.window.connect("delete_event",

self.event_delete)

self.window.connect("destroy",

self.destroy)

table

=gtk.Table(3,

2,

False)

self.window.add(table)

label

=gtk.Label("Zelle

1-1")

table.attach(label,

0,

1,

0,

1)

label.show()

label

=gtk.Label("Zelle

1-2")

table.attach(label,

1,

2,

0,

1)

label.show()

label

=gtk.Label("Eine

etwas

größere

Zelle")

table.attach(label,

0,

1,

1,

2)

label.show()

label

=gtk.Label("Zelle

2-2")

table.attach(label,

1,

2,

1,

2)

label.show()

label

=gtk.Label("<u>die

letzte

Zeile

geht

über

die

gesamte

Tabellenbreite</u>")

label.set_use_markup(True)

table.attach(label,

0,

2,

2,

3)

Page 411: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

label.show()

table.show()

self.window.show()

defevent_delete(self,

widget,

event,

data=None):

returnFalse

defdestroy(self,

data=None):

gtk.main_quit()

defmain(self):

gtk.main()

if

__name__==

"__main__":

tab

=Tabelle1()

tab.main()

Inne

rhal

bvo

n__init__()

wir

dei

neTa

belle

erze

ugt.

Indi

eTa

belle

nzel

len

wer

den

jew

eils

eini

geL

abel

sun

terg

ebra

cht.

Ein

esde

rLab

els

benu

tztH

TM

L-

Mar

kup,

umse

inen

Text

darz

uste

llen

und

geht

über

die

gesa

mte

Tabe

llenb

reite

.

Page 412: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ein

eTa

belle

wir

dm

itgtk.Table(Zeilen,Spalten,homogen)

.Z

eile

nun

dSp

alte

nsi

ndse

lbst

erkl

ären

d.Is

tder

Wer

tvon

hom

ogen

True

,da

nnha

ben

alle

Tabe

llene

lem

ente

die

glei

che

Grö

ße.O

bwoh

lman

die

Tabe

llese

lbst

nich

tsi

eht,

mus

sm

ansi

em

itwindow.add(table)

dem

Fens

ter

hinz

ufüg

enun

dm

itshow()

sich

tbar

mac

hen.

Ein

Ele

men

tw

ird

der

Tabe

llem

itde

rM

etho

deattach(Element,links,rechts,oben,unten)

hinz

u-ge

fügt

.Dab

eibe

zieh

ensi

chdi

eK

oord

inat

enau

fdie

Tabe

llenr

ände

r,ni

chta

ufdi

eZ

eile

n/Sp

alte

n-N

umm

erie

rung

.Der

linke

Ran

dei

ner

3X2-

Tabe

lleis

t0,

derr

echt

eR

and

ist2

.Obe

nis

t0,u

nten

ist3

.Es

wer

den

also

die

(ged

acht

en)

Gitt

erlin

ien

durc

hnum

mer

iert

.A

ufdi

ese

Wei

seka

nnm

anau

chE

lem

ente

einf

ügen

,die

sich

über

meh

rere

Zei

len

und

Spal

ten

erst

reck

en,w

ieim

letz

ten

Lab

el-B

eisp

iel.

Der

Text

inei

nem

Labe

lkan

nm

itH

TML-

Mar

kup

vers

ehen

wer

den,

indi

esem

Fall

wir

der

unte

rstr

iche

nda

rges

tellt

.Um

Mar

kup

zuak

tivie

ren,

benu

tztm

andi

eM

etho

deset_use_markup()

.

Page 413: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18.2

.2B

oxen

layo

ut

Es

gibt

hori

zont

ale

und

vert

ikal

eB

oxen

.Hor

izon

tale

Box

enle

gen

Wid

gets

nebe

nein

ande

r,ve

rtik

ale

über

eina

nder

.Im

folg

ende

nB

eisp

ielb

enut

zen

wir

stat

tLab

elsgtk.Button()

-Obj

ekte

(Sch

altk

nöpf

e),d

iese

habe

nde

nV

or-

teil,

dass

man

ihre

Aus

dehn

ung

sieh

t.D

asH

aupt

layo

utbe

steh

tau

sei

ner

horiz

onta

len

Box

,in

die

eine

verti

kale

Box

und

ein

Scha

ltkno

pfge

legt

wer

den:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

gtk

class

Box1(object):

def__init__(self):

self.window

=gtk.Window(gtk.WINDOW_TOPLEVEL)

self.window.set_title("Mein

erstes

Fenster")

self.window.set_default_size(300,

100)

self.window.connect("delete_event",

self.event_delete)

self.window.connect("destroy",

self.destroy)

#horizontale

Box

Page 414: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

hbox

=gtk.HBox(True,

30)

#Vertikale

Box

vbox

=gtk.VBox(True,

1)

button

=gtk.Button("vbox

0")

button.show()

vbox.pack_start(button)

button

=gtk.Button("vbox

1")

button.show()

vbox.pack_start(button)

button

=gtk.Button("vbox

2")

button.show()

vbox.pack_start(button)

button

=gtk.Button("vbox

3in

der

letzten

Reihe")

button.show()

vbox.pack_start(button)

#Ende

vertikale

box

hbox.pack_start(vbox)

button

=gtk.Button("Noch

ein

Knopf")

button.show()

hbox.pack_start(button)

#Alles

zusammenfügen

self.window.add(hbox)

#Anzeigen

vbox.show()

hbox.show()

Page 415: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

self.window.show()

defevent_delete(self,

widget,

event,

data=None):

returnFalse

defdestroy(self,

data=None):

gtk.main_quit()

defmain(self):

gtk.main()

if

__name__==

"__main__":

box

=Box1()

box.main()

Box

enw

erde

ner

zeug

tm

itgtk.HBox(homogen,abstand)

und

gtk.VBox(homogen,abstand)

.D

erPa

ram

eter

hom

ogen

best

imm

t,da

ssal

leen

thal

tene

nW

idge

tsdi

esel

beB

reite

(HB

ox)

oder

dies

elbe

Höh

e(V

Box

)hab

en.a

bsta

ndis

tein

Wer

tin

Pixe

ln,d

erde

nA

bsta

ndzw

eier

bena

ch-

bart

erW

idge

tsvo

rgib

t.

Page 416: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Wid

gets

wer

den

mit

pack_start(Widget)

von

links

nach

rech

tsun

dvo

nob

enna

chun

ten

hinz

ugef

ügt.U

min

umge

kehr

ter

Rei

henf

olge

hinz

uzuf

ügen

,ka

nnm

andi

eFu

nktio

npack_end(Widget)

benu

tzen

.B

eide

Funk

tione

nha

ben

meh

rPa

ram

eter

,al

shi

erda

rges

tellt

,nä

mlic

hpack_start(Widget,expandieren,füllen,platz)

.Mit

ih-

nen

kann

man

best

imm

en,o

bei

nW

idge

tsic

hüb

erde

nge

sam

ten

Plat

zau

sdeh

-ne

nda

rf(e

xpan

dier

en=

True

)und

wen

nja

,ob

derz

usät

zlic

hePl

atz

dem

Wid

get

gehö

rt(f

ülle

n=Tr

ue).

Mit

plat

zw

ird

zusä

tzlic

herR

and

umda

shi

nzug

efüg

teW

idge

ther

umbe

legt

.

Box

enm

üsse

neb

enso

wie

ande

reW

idge

tssi

chtb

arge

mac

htw

erde

n.

Wir

erm

utig

enSi

ean

dies

erSt

elle

,die

vers

chie

dene

nM

öglic

hkei

ten

derP

ara-

met

erau

szup

robi

eren

,um

ein

Gef

ühlf

ürih

reB

edeu

tung

zube

kom

men

.

Page 417: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18.3

Gra

fisch

eE

lem

ente

18.3

.1B

utto

n

Scha

ltknö

pfe

dien

enda

zu,b

eim

Drü

cken

ein

Sign

alzu

erze

ugen

.Die

sesS

igna

lka

nnm

itei

ner

soge

nann

ten

Cal

lbac

k-Fu

nktio

nau

fgef

ange

nun

dbe

arbe

itet

wer

den,

wie

folg

ende

sB

eisp

ielz

eigt

.Auf

Kno

pfdr

uck

wir

dde

rTe

xtei

nes

Lab

els

verä

nder

t:

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

gtk

class

Button1(object):

def__init__(self):

self.window

=gtk.Window(gtk.WINDOW_TOPLEVEL)

self.window.set_title("Von

Buttons

und

Labeln")

self.window.set_default_size(300,

100)

self.window.connect("delete_event",

self.event_delete)

Page 418: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

self.window.connect("destroy",

self.destroy)

#vertikale

Box

vbox

=gtk.VBox(True,

30)

button

=gtk.Button("Drück

mich")

button.connect("clicked",

self.button_clicked)

button.show()

vbox.pack_start(button)

self.label

=gtk.Label("")

self.label.show()

vbox.pack_start(self.label)

self.window.add(vbox)

vbox.show()

self.window.show()

defbutton_clicked(self,

data=None):

self.label.set_text("Danke!

Sie

haben

ein

einfaches\nLabel

sehr

glücklich

gemacht.")

defevent_delete(self,

widget,

event,

data=None):

returnFalse

defdestroy(self,

data=None):

gtk.main_quit()

defmain(self):

Page 419: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

gtk.main()

if

__name__==

"__main__":

b=

Button1()

b.main()

Cal

lbac

k-Fu

nktio

nen

wie

button_clicked(data)

,od

erin

dies

emFa

llM

etho

den,

habe

nin

GT

K+

imm

erei

neäh

nlic

heG

esta

lt.M

itde

mop

tiona

len

Para

met

erdata

könn

enD

aten

über

gebe

nw

erde

n,di

evo

nconnect(signal,callback,data)

bere

itges

tellt

wer

den.

18.3

.2D

ialo

g,Te

xtfe

ld,R

ahm

en

Das

folg

ende

Bei

spie

lent

hält

zwei

Text

zeile

n,in

die

der

Anw

ende

rse

inen

Nam

enun

dse

ine

E-M

aile

inge

ben

kann

.Die

seD

aten

wer

den

inei

nem

An-

zeig

edia

log

aufg

efüh

rt.D

ieW

idge

tssi

ndin

nerh

alb

eine

sR

ahm

ens

mit

eine

mTi

telf

eld

unte

rgeb

rach

t.

#!/usr/bin/python

Page 420: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#-*-

coding:

utf-8

-*-

import

gtk

class

Entry1(object):

def__init__(self):

self.window

=gtk.Window(gtk.WINDOW_TOPLEVEL)

self.window.set_title("Entry

und

Frame")

self.window.set_default_size(300,

100)

self.window.connect("delete_event",

self.event_delete)

self.window.connect("destroy",

self.destroy)

frame

=gtk.Frame("Möchten

Sie

SPAM

bekommen?")

self.window.add(frame)

#vertikale

Box

vbox

=gtk.VBox(True,

10)

frame.add(vbox)

#obere

hbox

hbox1

=gtk.HBox(True,

0)

vbox.pack_start(hbox1)

label

=gtk.Label("Name")

label.show()

hbox1.pack_start(label)

self.entry1

=gtk.Entry()

Page 421: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

self.entry1.show()

hbox1.pack_start(self.entry1)

hbox1.show()

#untere

hbox

hbox2

=gtk.HBox(True,

0)

vbox.pack_start(hbox2)

label

=gtk.Label("E-Mail")

label.show()

hbox2.pack_start(label)

self.entry2

=gtk.Entry()

self.entry2.show()

hbox2.pack_start(self.entry2)

hbox2.show()

#Knopf

button

=gtk.Button("Im

SPAM-Verteiler

eintragen")

button.connect("clicked",

self.button_clicked)

button.show()

vbox.pack_start(button)

#fertig

vertikale

Box

vbox.show()

frame.show()

self.window.show()

defbutton_clicked(self,

data=None):

name

=self.entry1.get_text()

Page 422: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

email

=self.entry2.get_text()

text

="%s,

wir

schicken

ihnen

ab

sofort

regelmäßig

SPAM

an

die

Adresse

%s!"

%(name,

email)

dlg

=gtk.MessageDialog(flags=gtk.DIALOG_MODAL,

buttons=gtk.BUTTONS_OK,

message_format=text)

dlg.set_title("Danke

für

ihre

Adresse")

dlg.run()

dlg.destroy()

defevent_delete(self,

widget,

event,

data=None):

returnFalse

defdestroy(self,

data=None):

gtk.main_quit()

defmain(self):

gtk.main()

if

__name__==

"__main__":

e=

Entry1()

e.main()

Rah

men

wer

den

mit

eine

mop

tiona

len

Tite

lfel

ddu

rch

die

Funk

tion

gtk.Frame(titel)

erze

ugt.

Die

serR

ahm

enka

nnse

lbst

ein

Lay

outa

uf-

Page 423: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

nehm

en,i

ndi

esem

Fall

eine

verti

kale

Box

.Inn

erha

lbdi

eser

Box

wer

den

Labe

lun

dTe

xtei

ngab

enei

ngef

ügt.

Text

eing

aben

sind

einz

eilig

eTe

xtfe

lder

,die

mit

gtk.Entry(länge)

erze

ugtw

erde

n.lä

nge

isto

ptio

nalu

ndm

eint

die

ma-

xim

ale

Anz

ahla

nZ

eich

en,d

ieda

sFe

ldau

fneh

men

kann

.Zum

Schl

uss

wir

dei

nK

nopf

eing

efüg

t,de

rmit

derC

allb

ack-

Met

hode

button_clicked()

verk

nüpf

twir

d.

Inne

rhal

bvo

nbutton_clicked()

wer

den

die

Text

zeile

nm

itget_text()

ausg

eles

enun

din

eine

mTe

xtzu

sam

men

gefü

gt.

An-

schl

ieße

ndw

ird

ein

Dia

logo

bjek

ters

tellt

.Die

ser

Dia

log

istm

odal

,läs

stbi

szu

mE

nde

kein

ew

eite

ren

Ein

gabe

nzu

.Ere

nthä

ltle

digl

ich

den

Kno

pf"O

K"

und

stel

ltde

nTe

xtw

ieau

chei

nen

Tite

ldar

.

Der

Dia

log

wir

dm

itrun()

gest

arte

t.W

enn

derA

nwen

dera

uf"O

K"

klic

kt,

wird

dierun()

-Met

hode

been

detu

ndde

rDia

log

mitdestroy()

gesc

hlos

-se

n.

Page 424: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18.3

.3M

enü,

Zei

chne

nm

itC

airo

Abb

.12

Vek

torg

rafik

mit

Cai

ro

Imfo

lgen

den

Bei

spie

lerz

euge

nw

irei

nM

enü

und

eine

Mal

fläch

e,in

die

wir

mit

Hilf

ede

rVek

torg

rafik

-Bib

lioth

ekC

airo

eini

geG

rafik

prim

itive

wie

Kre

ise,

Page 425: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Rec

htec

keod

erTe

xtze

ichn

en.H

ierz

ube

nötig

enw

irzw

eiK

lass

en,n

ämlic

hMalfeld

,die

Kla

sse,

die

den

Zeic

henb

erei

chbe

reits

tellt

undMenu1

,die

das

Men

üer

zeug

tund

das

Mal

feld

inne

rhal

bei

nes

Fram

esau

fnim

mt.

Akt

ivie

rtde

rN

utze

rdas

Men

ü,w

ird

entw

eder

etw

asTe

xtge

zeic

hnet

oder

das

Prog

ram

mve

rlas

sen.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

gtk

import

math

class

Malfeld(gtk.DrawingArea):

def__init__(self):

gtk.DrawingArea.__init__(self)

self.connect("expose_event",

self.event_expose)

self.drawText

=False

defevent_expose(self,

widget,

event):

grafik

=widget.window.cairo_create()

width,

height

=widget.window.get_size()

Page 426: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

width

=width

/5

height

=height

/3

self.draw(grafik,

width,

height)

ifself.drawText:

self.draw_text(grafik,

*self.drawText)

self.drawText

=False

returnFalse

defdraw(self,

context,

w,

h):

context.set_source_rgb(0.5,

0.0,

0.0)

context.rectangle(w,

h,

w,

h)

context.stroke()

context.set_source_rgb(0.0,

1.0,

0.0)

context.arc(3.0*w,

h,

min(w,

h),

0,

2.0

*math.pi)

context.fill()

defdraw_text(self,

context,

x,

y,

text):

context.set_source_rgb(0.0,

0.0,

1.0)

context.set_font_size(30)

context.move_to(x,

y+

30)

context.show_text(text)

defset_draw_text(self,

x,

y,

text):

self.drawText

=(x,

y,

text)

self.queue_draw()

Page 427: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

class

Menu1(object):

def__init__(self):

self.window

=gtk.Window(gtk.WINDOW_TOPLEVEL)

self.window.set_title("Menü")

self.window.set_default_size(300,

100)

self.window.connect("delete_event",

self.event_delete)

self.window.connect("destroy",

self.destroy)

#Menu

menu

=gtk.Menu()

#erstes

Item

menuItem

=gtk.MenuItem("Hallo")

menuItem.show()

menuItem.connect("activate",

self.menu_clicked)

menu.append(menuItem)

#Quit-Item

menuItem

=gtk.MenuItem("Quit")

menuItem.show()

menuItem.connect("activate",lambda

w:

gtk.main_quit())

menu.append(menuItem)

#Hauptmenu

wird

in

der

Menuzeile

angezeigt

mainMenu

=gtk.MenuItem("Hauptmenu")

mainMenu.set_submenu(menu)

Page 428: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

mainMenu.show()

#Menuzeile

menuBar

=gtk.MenuBar()

menuBar.append(mainMenu)

menuBar.show()

#Malfeld

frame

=gtk.Frame("Malfeld")

self.malen

=Malfeld()

self.malen.show()

frame.add(self.malen)

frame.show()

#VBox

vbox

=gtk.VBox()

vbox.pack_start(menuBar,

False,

False,

0)

vbox.pack_start(frame,

True,

True,

0)

vbox.show()

self.window.add(vbox)

self.window.show()

defmenu_clicked(self,

widget,

data=None):

self.malen.set_draw_text(10,

10,

"Menü

wurde

geklickt")

defevent_delete(self,

widget,

event,

data=None):

returnFalse

Page 429: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

defdestroy(self,

data=None):

gtk.main_quit()

defmain(self):

gtk.main()

if

__name__==

"__main__":

m=

Menu1()

m.main()

Die

Kla

sseMalfeld

wird

von

derG

TK+-

Kla

sseDrawingArea

abge

leite

t,ei

nerK

lass

e,di

ese

lbst

eine

Zei

chen

fläch

eim

plem

entie

rt,j

edoc

hnu

rwen

igU

nter

stüt

zung

für

Gra

fikpr

imiti

vem

itbri

ngt.

Die

seK

lass

est

ellt

Ere

igni

sse

bere

it,di

eda

rauf

hinw

eise

n,w

ann

neu

geze

ichn

etw

erde

nso

ll."expose_-

event

"is

tein

solc

hes

Ere

igni

s.E

str

ittda

nnei

n,w

enn

das

Fens

terv

erde

ckt

oder

sein

eG

röße

verä

nder

twur

de.D

iese

sE

reig

nis

verk

nüpf

enw

irm

itde

rM

etho

deevent_expose()

.

event_expose(widget,event)

über

gibt

das

neu

zuze

ichn

ende

Wid

get

und

das

betr

effe

nde

Ere

igni

s.In

nerh

alb

der

Funk

tion

wir

dm

it

Page 430: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

cairo_create()

die

Unt

erst

ützu

ngfü

rVek

torg

rafik

enak

tivie

rt.D

erR

ück-

gabe

wer

tist

ein

Gra

fikko

ntex

t,al

soei

neK

lass

e,di

eal

lesN

ötig

ezu

mZe

ichn

enm

itbri

ngt.

Es

kann

übri

gens

nuri

nner

halb

vonevent_expose()

geze

ich-

net

wer

den.

Der

Gra

fikko

ntex

tka

nnni

cht

für

spät

ere

Zw

ecke

gesp

eich

ert

wer

den.

Mitget_size()

hole

nw

irun

sdi

eG

röße

des

Zei

chen

bere

iche

sun

dbe

rech

nen

Orte

vor,

wo

wir

Din

geze

ichn

enw

olle

n.A

nsch

ließe

ndw

erde

nei

nige

Gra

fiken

gem

alt

und

bei

Bed

arf

Text

geze

ichn

et.D

erB

edar

fer

gibt

sich

aus

dem

Auf

rufd

erM

etho

deset_draw_text()

,die

beim

Akt

ivie

ren

eine

sM

enüs

aufg

eruf

enw

ird.

Inne

rhal

bvo

ndraw()

wird

mitset_source_rgb(rot,grün,blau)

eine

Farb

evo

rgeg

eben

.Die

Farb

wer

tedü

rfen

zwis

chen0.0

und1.0

liege

n.Ei

nR

echt

eck

wird

mitrectangle(x,y,Breite,Höhe)

vorb

erei

tet,

mitstroke()

wird

dasR

echt

eck

inse

inen

Um

risse

nge

zeic

hnet

.Fül

len

kann

man

dasz

ulet

ztan

gege

bene

Obj

ektm

itfill()

.Ein

enK

reis

zeic

hnet

man

mit

derM

etho

dearc(x,y,Radius,Winkel_Von,Winkel_Bis)

.

draw_text()

zeic

hnet

Text

anei

ner

ange

gebe

nen

Posi

tion.

Hie

rzu

wir

ddi

eSc

hrif

tgrö

ßefe

stge

legt

,ans

chlie

ßend

wir

dei

nG

rafik

curs

oran

eine

Stel

le

Page 431: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

imFe

nste

rges

etzt

(move_to(x,y)

).show_text(Text)

zeic

hnet

dann

den

eige

ntlic

hen

Text

inde

rzul

etzt

fest

gele

gten

Farb

e.

Die

Kla

sseMenu1

erze

ugtd

asH

aupt

fens

ter.

Esw

erde

nei

nige

Men

üite

ms

mit

MenuItem(Text)

erze

ugtu

ndm

iten

tspr

eche

nden

Cal

lbac

k-Fu

nktio

nen

verk

nüpf

t.D

iese

Item

sw

erde

nzu

eine

mM

enüe

intr

agzu

sam

men

gefa

sstu

ndde

mM

enü,

das

mitMenu()

erze

ugtw

ird,h

inzu

gefü

gt.D

asan

geze

igte

Men

üis

tw

iede

rum

ein

Men

uite

mun

dha

tde

nN

amen

mainMenu

.D

iese

sw

ird

derMenuBar()

hinz

ugef

ügt.

Die

sis

tsch

onda

s,w

asim

ober

enB

erei

chde

sFe

nste

rsan

geze

igtw

erde

nso

ll.

Es

wer

den

also

zuer

stIt

ems

erze

ugt,

dann

wer

den

dies

eIt

ems

inei

nem

Me-

nüzu

sam

men

gefa

sstu

ndw

iede

rum

inei

nem

Item

eing

etra

gen.

Die

seIt

ems

wer

den

eine

rM

enüz

eile

hinz

ugef

ügt.

Auf

dies

eW

eise

erze

ugtm

anM

enüs

und

Unt

erm

enüs

.Das

Ver

fahr

engl

eich

tje

nem

der

Lay

outs

.Dab

eiw

erde

neb

enfa

llsEl

emen

tein

Layo

utbo

xen

gepa

ckt,

dies

ew

erde

nw

iede

rum

inB

oxen

verp

ackt

und

irgen

dwan

nde

mFe

nste

rode

rdem

Fram

ehi

nzug

efüg

t.

Page 432: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18.4

Ben

utze

robe

rfläc

hen

-sch

nell

und

einf

ach

Abb

.13

Gla

dehi

lftb

eim

Ers

telle

nvo

ngr

afisc

hen

Ben

utze

robe

rfäc

hen

Page 433: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ben

utze

robe

rfläc

hen

könn

enun

terG

TK

+m

itgr

afisc

hen

Wer

kzeu

gen

erst

ellt

wer

den.

Ein

beka

nnte

sW

erkz

eug

istG

lade

4 ,de

ssen

Bed

ienu

ngw

irku

rzan

-sp

rech

enw

olle

n.Si

ebe

nötig

enfü

rdas

Bei

spie

ldas

Mod

ulpython-glade2

sow

ie-s

elbs

tver

stän

dlic

h-G

lade

Ver

sion

25 .

Ein

eB

enut

zero

berfl

äche

erst

ellt

man

inG

lade

fast

volls

tänd

igvi

suel

l.E

sw

ird

eine

XM

L-D

atei

gesp

eich

ert,

die

imH

aupt

prog

ram

mge

öffn

etw

ird.

Dor

tw

erde

nau

chdi

ein

Gla

deer

stel

lten

Cal

lbac

k-Fu

nktio

nen

regi

stri

ert,

ansc

hlie

ßend

kann

die

Ben

utze

robe

rfläc

hege

nutz

twer

den.

4W

eite

reD

esig

ner-

Tool

sfin

den

Sie

unte

rht

tp://

wik

i.pyt

hon.

org/

moi

n/G

uiPr

ogra

mm

ing

ˆ{http://wiki.python.org/moin/GuiProgramming}

aufg

elis

tet.

5Z

urne

uen

Ver

sion

3lie

gen

uns

noch

kein

ePy

thon

-Erf

ahru

ngen

vor.

Page 434: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

18.4

.1B

enut

zero

berfl

äche

erst

elle

n

Abb

.14

Ben

utze

robe

rfläc

hein

Gla

deer

stel

len

Für

das

folg

ende

Bei

spie

lsta

rten

Sie

Gla

deun

der

zeug

enei

nH

aupt

fens

ter

und

eine

nD

ialo

g.W

enn

Sie

das

Bei

spie

lpr

aktis

chna

chvo

llzie

hen

wol

len,

Page 435: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

müs

sen

Sie

dara

ufac

hten

,das

sdi

eN

amen

derG

UI-

Ele

men

te(I

D)m

itde

nen

imQ

uellc

ode

über

eins

timm

en.

Hau

ptfe

nste

r

Abb

.15

Das

Hau

ptfe

nste

r

Page 436: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Inda

sH

aupt

fens

ter

kom

mtz

uers

tein

eve

rtik

ale

Box

mit

drei

Abs

chni

tten.

Ans

chlie

ßend

wir

dei

nM

enü,

ein

Kno

pfun

dei

nL

abel

(als

Stat

usze

ile)

ein-

gefü

gt.I

mE

igen

scha

ften

-Dia

log

wir

dim

Rei

ter"

Sign

ale"

ein

Sign

alhi

nzu-

gefü

gt.W

irve

rbin

den

dazu

das

Sign

aldestroy

(nic

htzu

verw

echs

eln

mit

destroy_signal

)mit

derC

allb

ackf

unkt

ionon_fenster1_destroy

.Eb

enfa

llsw

irdda

s"clicked

"-Si

gnal

vom

Kno

pfm

itde

rCal

lbac

k-Fu

nktio

non_button1_clicked

verk

nüpf

t.

Das

Men

üw

ird

etw

asau

fger

äum

t,üb

rig

blei

ben

Datei->Quit

und

Hilfe->Info

.D

ie"activate

"-Si

gnal

ew

erde

nm

iton_quit1_activate

bezi

ehun

gsw

eise

on_info1_activate

verk

nüpf

t.

Dam

itda

sfo

lgen

deB

eisp

ielf

unkt

ioni

ert,

mus

sda

sSt

atus

zeile

n-L

abel

die

ID"Label2

"tr

agen

und

das

Fens

terd

ieID

"fenster1

"ha

ben.

Page 437: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Dia

log

Abb

.16

Der

Dia

log

Es

wir

dei

nD

ialo

gm

itde

rID

"dialog1

"er

stel

lt.D

erD

ialo

gso

llüb

erei

neSt

anda

rd-K

nopf

anor

dnun

gm

itei

nem

Schl

ieße

n-K

nopf

verf

ügen

.Das

Page 438: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

clicked

-Sig

nald

iese

sK

nopf

esw

irdm

iton_closebutton1_clicked

verk

nüpf

t.W

irfü

gen

ein

Lab

elm

itet

was

Bei

spie

ltext

hinz

u.

Abs

chlu

ss

Dan

nsi

ndw

irfe

rtig

und

könn

enda

sPr

ojek

tsp

eich

ern,

wob

eiw

irnu

rdi

een

tste

hend

eprojekt1.glade

-Dat

eibe

nötig

en.

ImSp

eich

ern-

Dia

log

könn

enw

irda

rauf

verz

icht

en,d

ass

alle

sons

tigen

Prog

ram

mda

teie

ner

stel

ltw

erde

n.D

iese

sind

fürP

ytho

nnu

rübe

rflüs

sige

rBal

last

.

18.4

.2Q

uellc

ode

Das

folg

ende

Prog

ram

mlä

dtdi

ein

Gla

deer

stel

lteB

enut

zero

berfl

äche

und

stel

ltsi

eda

r.In

der

Stat

usze

ilew

ird

verf

olgt

,w

ieof

tde

rze

ntra

leK

nopf

gedr

ückt

wir

d.M

itde

nM

enüs

kann

man

das

Prog

ram

mve

rlas

sen

oder

den

erst

ellte

nD

ialo

gau

fruf

en.

Page 439: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

#!/usr/bin/python

import

gtk

import

gtk.glade

class

HelloGlade(object):

def__init__(self):

self.gladeDatei

="projekt1.glade"

self.widgets

=gtk.glade.XML(self.gladeDatei,

"fenster1")

events

={"on_fenster1_destroy"

:gtk.main_quit,

"on_quit1_activate"

:gtk.main_quit,

"on_info1_activate"

:self.info_dlg,

"on_button1_clicked"

:self.statusbar_info}

self.widgets.signal_autoconnect(events)

self.numClicked

=0

definfo_dlg(self,

widget):

self.dlg

=gtk.glade.XML(self.gladeDatei,

"dialog1")

events

={"on_closebutton1_clicked"

:self.dlg_close}

self.dlg.signal_autoconnect(events)

defdlg_close(self,

widget):

d=

self.dlg.get_widget("dialog1")

d.destroy()

Page 440: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

defstatusbar_info(self,

widget):

label

=self.widgets.get_widget("label2")

self.numClicked

+=

1text

="Es

wurde

%d

mal

geklickt"

%self.numClicked

label.set_text(text)

if

__name__==

"__main__":

h=

HelloGlade()

gtk.main()

Die

GU

I-D

atei

wir

dm

itgtk.glade.XML(datei,id)

gela

den.

idis

thi

erbe

iopt

iona

l,ka

nnal

soen

tfal

len.

Sons

tbez

eich

netd

iese

rPar

amet

erde

nN

amen

des

GU

I-el

emen

tes,

das

gela

den

wer

den

soll.

Inei

nem

Dic

tiona

ryle

gen

wir

alle

das

Fens

ter

betr

effe

nden

Cal

lbac

k-Fu

nktio

nen

mit

ihre

nzu

gehö

rige

nA

ktio

nen

an.

Wir

dbe

ispi

els-

wei

seon_info1_activate

aufg

eruf

en,

führ

tda

sin

unse

rem

Bei

spie

lda

zu,

dass

info_dlg()

eben

falls

aufg

eruf

enw

ird.

Mit

signal_autoconnect(events)

verk

nüpf

enw

irdi

eE

reig

niss

em

itun

sere

nen

tspr

eche

nden

Kla

ssen

met

hode

n.

Page 441: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Wen

nda

sHilfe-Info

-Men

übe

tätig

twird

,dan

nw

irdininfo_dlg()

der

betre

ffen

deD

ialo

gge

star

tet.

Auc

hhi

erfü

rhol

enw

irun

sdi

eB

esch

reib

ung

des

Dia

logs

aus

derG

lade

-Dat

eiun

dve

rknü

pfen

die

pass

ende

nE

reig

niss

e.So

llm

itei

nem

Klic

kau

fden

Schl

ieße

n-K

nopf

derD

ialo

gbe

ende

twer

den,

wir

ddlg_close()

aufg

eruf

en.D

asei

gent

liche

Wid

getd

iese

sD

ialo

gsw

ird

mit

get_widget(id)

erm

ittel

t,an

schl

ieße

ndw

ird

ihm

dasdestroy

-Sig

nal

mitdestroy()

gesc

hick

t.

Drü

cktd

erA

nwen

dera

ufde

nze

ntra

len

Kno

pfin

derM

itte

vom

Hau

ptfe

nste

r,w

ird

die

Met

hode

statusbar_info()

aufg

eruf

en.E

sw

ird

auch

hier

das

Labe

l-Wid

getm

itget_widget(id)

geho

lt,an

schl

ieße

ndw

irdde

rTex

tmit

set_text()

verä

nder

t.

18.5

Zus

amm

enfa

ssun

g

Anw

endu

ngen

mit

grafi

sche

nB

enut

zero

berfl

äche

nla

ssen

sich

mit

PyG

TK

leic

htsc

hrei

ben.

Indi

esem

Kap

itelh

aben

wir

die

Gru

ndla

gen

des

Lay

outs

Page 442: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

kenn

enge

lern

t,ei

nige

wen

ige

Wid

gets

vorg

este

lltun

dge

zeig

t,w

iesi

chG

UIs

mit

Gla

deer

stel

len

lass

en.

18.6

Anm

erku

ngen

Page 443: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 444: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

19Te

xtor

ient

iert

eB

enut

zero

berfl

äche

nm

itC

urse

s

Indi

esem

Kap

itelg

ehte

sum

rein

text

orie

ntie

rteB

enut

zero

berfl

äche

n,w

ieSi

esi

em

öglic

herw

eise

von

rein

text

orie

ntie

rten

Prog

ram

men

wie

mut

t,ly

nxod

erde

mM

idni

ght-

Com

man

derh

erke

nnen

.Es

wer

den

Teile

des

Cur

ses-

Mod

uls

vorg

este

llt.Z

uC

urse

sgi

btes

ein

eige

nes

herv

orra

gend

esW

ikib

ook,

näm

lich

Ncu

rses

1 .Die

serA

bsch

nitt

benu

tzte

inig

ede

rdor

tvor

gest

ellte

nId

een.

1http://de.wikibooks.org/wiki/Ncurses

433

Page 445: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

19.1

Hal

lo,W

elt!

Uns

erer

stes

Bei

spie

lerz

eugt

ein

Fens

ter,

inde

msi

chde

rhis

tori

sch

beka

nnte

Spru

chH

allo

,Wel

t!ze

igt.

Bitt

ebe

acht

enSi

e,da

ssdi

eses

Bei

spie

lFa

rben

vora

usse

tzt.

Es

wir

dni

chtg

eprü

ft,o

bih

rTer

min

alFa

rben

dars

telle

nka

nn.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

curses

#start

stdscr

=curses.initscr()

#Keine

Anzeige

gedrückter

Tasten

curses.noecho()

#Kein

line-buffer

curses.cbreak()

#Escape-Sequenzen

aktivieren

stdscr.keypad(1)

#Farben

curses.start_color()

curses.init_pair(1,

curses.COLOR_GREEN,

curses.COLOR_BLUE)

Page 446: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

curses.init_pair(2,

curses.COLOR_YELLOW,

curses.COLOR_BLACK)

#Fenster

und

Hintergrundfarben

stdscr.bkgd(curses.color_pair(1))

stdscr.refresh()

win

=curses.newwin(5,

20,

5,

5)

win.bkgd(curses.color_pair(2))

win.box()

win.addstr(2,

2,

"Hallo,

Welt!")

win.refresh()

#Warten

auf

Tastendruck

c=

stdscr.getch()

#Ende

curses.nocbreak()

stdscr.keypad(0)

curses.echo()

curses.endwin()

Page 447: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.17

Hal

loW

elt

Die

beid

enw

icht

igen

Initi

alis

ieru

ngsf

unkt

ione

nin

dies

emB

eisp

iel

sind

curses.initscr()

,m

itde

rdi

eC

urse

s-U

mge

bung

eing

eric

htet

wir

dun

dcurses.start_color()

,m

itde

rda

sPr

ogra

mm

die

Mög

-lic

hkei

ter

hält,

Farb

eda

rzus

telle

n.Fa

rben

wer

den

als

Paar

erze

ugt,

mit

Page 448: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

curses.init_pair(2,curses.COLOR_YELLOW,curses.COLOR_BLACK)

wir

dei

nPa

arm

itde

rN

umm

er2

erze

ugt,

wel

ches

gelb

auf

schw

arze

mG

rund

dars

telle

nka

nn.stdscr.bkgd(curses.color_pair(1))

refe

renz

iert

ein

solc

hes

Paar

und

legt

den

Hin

terg

rund

fürd

asTe

rmin

alfe

st.

Es

wir

dni

chts

ange

zeig

t,oh

neda

ssei

nR

efre

sh(stdscr.refresh()

)er

folg

t.

Ein

Fens

terk

ann

mitcurses.newwin(Höhe,Breite,Y0,X0)

er-

zeug

twer

den.

Die

Para

met

ersi

ndun

gew

öhnl

ich,

steh

enhi

erY

-Wer

tevo

rden

betr

effe

nden

X-W

erte

n.D

asis

tein

eB

eson

derh

eitd

erTe

rmin

al-B

iblio

thek

encu

rses

und

ncur

ses

und

war

scho

nim

mer

so.

Ein

emso

erze

ugte

nFe

nste

rkan

neb

enfa

llsei

nH

inte

rgru

ndzu

gew

iese

nw

er-

den,

zurV

ersc

höne

rung

dien

tauc

hdi

eFu

nktio

nbox()

.Sie

zeic

hnet

eine

nR

ahm

enru

ndum

das

Fens

ter.addstr(Y,X,Text)

schr

eibt

soda

nnei

-ne

nTe

xtau

fdas

Fens

ter.

Auc

hhi

erbe

nötig

tman

wie

dere

inen

Ref

resh

,um

etw

asse

hen

zukö

nnen

.Die

Ere

igni

sbeh

andl

ung

ista

nder

sal

sin

bish

erig

enN

utze

robe

rfläc

hen

rein

von

der

Tast

atur

gest

euer

t.M

ause

reig

niss

ew

erde

neb

enfa

llszu

erst

vongetch()

entg

egen

geno

mm

en.

Page 449: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Nac

hde

mde

rNut

zere

ine

Tast

edr

ückt

e,w

ird

das

Prog

ram

mfr

eund

lich

been

-de

t.H

ieri

stin

sbes

onde

recurses.endwin()

zune

nnen

,das

Geg

enst

ück

zucurses.initscr()

.

Ein

ige

deri

mQ

uellc

ode

genu

tzte

nFu

nktio

nen

habe

nw

irIh

nen

beid

erE

rläu

-te

rung

unte

rsch

lage

n.D

asw

olle

nw

irgl

eich

nach

hole

n.

19.2

Kur

zref

eren

zC

urse

s

Hie

rw

erde

nau

sgew

ählte

Funk

tione

nun

dK

onst

ante

nvo

rges

tellt

.Die

Lis

teis

tsel

bstv

erst

ändl

ich

nich

tvol

lstä

ndig

.Ein

eD

arst

ellu

ngde

rArt[attrib]

bede

utet

,das

sde

rWer

topt

iona

list

und

dam

itw

egge

lass

enw

erde

nda

rf.

19.2

.1C

urse

sFun

ktio

nen

Hie

rein

eA

uflis

tung

eini

gerg

ebrä

uchl

iche

rcur

ses-

Funk

tione

n:

Page 450: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngcb

reak

()no

cbre

ak()

ImC

Bre

ak-M

odus

wer

den

Tast

enei

nzel

nan

ge-

nom

men

,es

wir

dni

chta

ufdi

eB

estä

tigun

gdu

rch

Ret

urn

gew

arte

t.at

trib

=co

lor_

-pa

ir(F

arbn

umm

er)

init_

pair

(num

mer

,vo

rder

grun

d,hi

nter

-gr

und)

colo

r_pa

ir()

:Es

wir

dau

fein

evo

rher

mit

Farb

-nu

mm

ervo

rdefi

nier

teV

orde

r-un

dH

inte

rgru

nd-

farb

eve

rwie

sen.

Die

Attr

ibut

ew

erde

nzu

rück

ge-

gebe

n.in

it_pa

ir()

:Erz

eugt

ein

Farb

paar

aus

Vor

der-

grun

dfar

beun

dH

inte

rgru

ndfa

rbe

und

wei

stdi

ese

Kom

bina

tion

derN

umm

erzu

.num

mer

kann

ein

Wer

tzw

isch

en1

und

CO

LOR

_PA

IRS-

1se

in.

Page 451: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngdo

upda

te()

nout

refr

esh(

)re

fres

h()

Die

seG

rupp

evo

nFu

nktio

nen

küm

mer

tsic

hum

den

Ref

resh

.ref

resh

()is

tein

nout

refr

esh(

)ge

folg

tvon

doup

date

().n

outr

efre

sh()

upda

tetd

envi

rtue

llen

Bild

schi

rm,m

arki

erta

lso

den

Ber

eich

als

eine

n,de

nes

zure

fres

hen

gilt,

wäh

rend

doup

-da

te()

den

phys

ikal

isch

enB

ildsc

hirm

,als

odi

eec

hte

Anz

eige

,auf

fris

cht.

echo

()no

echo

()ec

ho()

bew

irkt

,das

sTa

sten

drüc

kean

geze

igtw

er-

den.

Die

ses

läss

tsic

hm

itno

echo

()au

ssch

alte

n.

Page 452: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngm

ouse

=ge

tmou

se()

(alle

,akt

uell)

=m

ou-

sem

ask(

neu)

vorh

er=

mou

sein

ter-

val(

neu)

getm

ouse

():B

eiei

nem

Mau

sere

igni

ska

nnm

itdi

eser

Funk

tion

derM

ausz

usta

ndal

sTu

pel(

ID,

X,Y

,unb

enut

zt,K

nopf

)ber

eitg

este

lltw

erde

n.m

ouse

mas

k():

erw

arte

tein

eM

aske

,bes

tehe

ndau

sde

nzu

beha

ndel

nden

Mau

sere

igni

ssen

.Es

wir

dei

nTu

pela

usal

len

verf

ügba

ren

Mau

sere

ig-

niss

enal

sM

aske

und

den

zule

tzta

ktiv

enzu

rück

-ge

liefe

rt.

mou

sein

terv

al()

:Set

ztei

nne

ues

Inte

rval

lin

Mil-

lisek

unde

n,w

elch

eszw

isch

enzw

eiM

aust

aste

n-dr

ücke

nve

rgeh

enda

rf,d

amit

das

Ere

igni

sno

chal

sD

oppe

lklic

ker

kann

twir

d.D

ieFu

nktio

ngi

btda

szu

letz

takt

ive

Inte

rval

lzur

ück.

bool

=ha

s_co

lors

()Tr

ue,w

enn

das

Tem

inal

Farb

enda

rste

llen

kann

.So

nstF

alse

.

Page 453: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

19.2

.2W

indo

w-F

unkt

ione

n

Ein

ige

Funk

tione

n,di

enu

rmit

eine

mW

indo

w-A

rgum

entS

inn

erge

ben:

Funk

tion

Bed

eutu

ngad

dch(

[y,x

,]Z

[,attr

ib])

adds

tr([

y,x,

]st

r[,a

ttrib

])

addc

h():

Zei

chne

tan

der(

optio

nale

n)St

elle

(y,x

)da

sei

nzel

neZ

eich

enZ.

Die

ses

Zei

chen

kann

mit

Attr

ibut

enve

rseh

enw

erde

n.ad

dstr

():S

elbi

ges

fürS

trin

gsbk

gd(Z

[,attr

])L

egtd

ieH

inte

rgru

ndfa

rbe

/Zei

chen

/Attr

ibut

efe

st.

box(

[ver

tZ,h

orZ

])be

nutz

tver

tZun

dho

rZ(b

eide

optio

nal)

umei

nen

Rah

men

umei

nFe

nste

rzu

Zei

chne

n.O

hne

dies

ePa

ram

eter

wir

dei

nL

inie

nran

dge

zeic

hnet

.cl

ear(

)L

ösch

tbei

mnä

chst

enre

fres

h()d

asko

mpl

ette

Fens

ter

clrt

oeol

()L

ösch

tvon

derm

omen

tane

nC

urso

rpos

ition

bis

zum

End

ede

rZei

le

Page 454: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Funk

tion

Bed

eutu

ngke

ypad

(val

ue)

Istv

alue

==1,

dann

wer

den

spez

ielle

Tast

enw

ieFu

nktio

nsta

sten

von

Cur

ses

als

solc

hein

terp

re-

tiert

.Mit

0sc

halte

tman

dies

esV

erha

lten

wie

der

ab.

19.2

.3K

onst

ante

n

•A

ttrib

ute,

mit

dene

nda

sV

erha

lten

von

Zei

chen

und

geän

dert

wer

den

kann

:

Kon

stan

teB

edeu

tung

A_B

LIN

KTe

xtw

ird

blin

kend

darg

este

lltA

_BO

LD

Text

wir

din

Fettd

ruck

darg

este

lltA

_NO

RM

AL

Text

wir

dw

iede

rnor

mal

darg

este

llt.

A_U

ND

ER

LIN

ETe

xtw

ird

unte

rstr

iche

nan

geze

igt

•Ta

stat

urko

nsta

nten

:

Page 455: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Kon

stan

teB

edeu

tung

KE

Y_U

P,K

EY

_-L

EFT

,KE

Y_R

IGH

T,K

EY

_DO

WN

Cur

sort

aste

n

KE

Y_F

1...K

EY

_Fn

Funk

tions

tast

enK

EY

_BA

CK

SPA

CE

Bac

kspa

ce-T

aste

KE

Y_M

OU

SEE

inM

ause

reig

nis

trat

ein

•M

ausk

onst

ante

n:

Kon

stan

teB

edeu

tung

BU

TT

ON

1_PR

ESS

ED

..B

UT

TON

4_PR

ESS

ED

Kno

pfw

urde

gedr

ückt

BU

TT

ON

1_R

EL

EA

SED

..B

UT

TON

4_R

EL

EA

SED

Kno

pfw

urde

losg

elas

sen

BU

TT

ON

1_C

LIC

KE

D..

BU

TTO

N4_

CL

ICK

ED

Kno

pfge

drüc

kun

dw

iede

rlos

gela

ssen

,in

nerh

alte

ines

mit

mou

sein

terv

al()

ein-

stel

lbar

enIn

terv

alle

s.

Page 456: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Kon

stan

teB

edeu

tung

BU

TT

ON

1_D

OU

BL

E_-

CL

ICK

ED

..B

UT

TO

N4_

-D

OU

BL

E_C

LIC

KE

D,

Dop

pelk

lick

BU

TT

ON

1_T

RIP

LE

_-C

LIC

KE

D,.

.BU

TT

ON

4_-

TR

IPL

E_C

LIC

KE

D,

3kl

icks

hint

erei

nand

er

BU

TT

ON

_SH

IFT,

BU

TT

ON

_CT

RL

,B

UT

TON

_ALT

Es

wur

dedi

eSh

ift-,

Steu

erun

gs,o

derd

ieA

lt-Ta

ste

beim

Klic

ken

gedr

ückt

.Man

beac

hte,

dass

eini

geTe

rmin

als

selb

stda

rauf

reag

iere

n,da

sPr

ogra

mm

dies

eE

reig

niss

eal

soni

chtm

itbek

omm

t.

•Fa

rbko

nsta

nten

:C

OL

OR

_BL

AC

K,

CO

LO

R_B

LU

E,

CO

LO

R_C

YA

N,

CO

LOR

_GR

EEN

,CO

LOR

_MA

GEN

TA,C

OLO

R_R

ED,C

OLO

R_W

HIT

E,C

OL

OR

_YE

LL

OW

Page 457: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

19.3

Meh

rFe

nste

r

Imfo

lgen

den

Bei

spie

lgeh

tes

umda

sL

esen

von

Log

-Dat

eien

(Sie

müs

sen

Les

erec

htda

rauf

habe

n,so

nstf

unkt

ioni

erte

sni

cht)

und

Men

üs.E

sw

erde

nau

fWun

sch

zwei

Fens

tere

rzeu

gt,e

ines

stel

ltei

nM

enü

dar,

iman

dere

nw

ird

wah

lwei

se/var/log/syslog

und

/var/log/messages

darg

e-st

ellt.

Scro

llen

kann

man

inde

nD

atei

enm

itde

nC

urso

r-Ta

sten

.Bee

ndet

wir

dm

itde

rTas

tex

.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

curses

import

linecache

def

init_curses():

stdscr

=curses.initscr()

curses.noecho()

curses.cbreak()

stdscr.keypad(1)

curses.start_color()

curses.init_pair(1,

curses.COLOR_GREEN,

curses.COLOR_BLUE)

Page 458: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

curses.init_pair(2,

curses.COLOR_YELLOW,

curses.COLOR_BLACK)

stdscr.bkgd(curses.color_pair(1))

stdscr.refresh()

returnstdscr

def

show_menu(win):

win.clear()

win.bkgd(curses.color_pair(2))

win.box()

win.addstr(1,

2,

"F1:",

curses.A_UNDERLINE)

win.addstr(1,

6,

"messages")

win.addstr(1,

20,

"F2:",

curses.A_UNDERLINE)

win.addstr(1,

24,

"syslog")

win.addstr(1,

38,

"x:",

curses.A_UNDERLINE)

win.addstr(1,

42,

"Exit")

win.refresh()

def

read_file(menu_win,

filename):

menu_win.clear()

menu_win.box()

menu_win.addstr(1,

2,

"x:",

curses.A_UNDERLINE)

menu_win.addstr(1,

5,

"Ende

->")

menu_win.addstr(1,

14,

filename)

menu_win.refresh()

file_win

=curses.newwin(22,

80,

4,

0)

Page 459: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

file_win.box()

line_start

=1

line_max

=20

whileTrue:

file_win.clear()

file_win.box()

fori

in

xrange(line_start,

line_max

+line_start):

line

=linecache.getline(filename,

i)

s=

''

iflen(line)

>60:

s=

'[%d

%s]'

%(i,

line[:60])

else: s

='[%d

%s]'

%(i,

line[:-1])

file_win.addstr(i

-line_start

+1,

2,

s)

file_win.refresh()

c=

stdscr.getch()

ifc

==

ord('x'):

break

elifc

==

curses.KEY_UP:

ifline_start

>1:

line_start

-=

1elifc

==

curses.KEY_DOWN:

line_start

+=

1

stdscr

=init_curses()

Page 460: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

mwin

=curses.newwin(3,

80,

0,

0)

while

True:

stdscr.clear()

stdscr.refresh()

show_menu(mwin)

c=

stdscr.getch()

ifc

==

ord('x'):

break

elifc

==

curses.KEY_F1:

read_file(mwin,

'/var/log/messages')

show_menu(mwin)

elifc

==

curses.KEY_F2:

read_file(mwin,

'/var/log/syslog')

show_menu(mwin)

curses.nocbreak()

stdscr.keypad(0)

curses.echo()

curses.endwin()

Page 461: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

.18

Log

date

ien

Es

wir

dei

nne

ues

Mod

ulm

itde

mN

amen

linec

ache

eing

ebun

den.

Die

ses

Mo-

dule

nthä

ltdi

eFu

nktio

nlinecache.getline(filename,i)

.Hie

r-m

itka

nnei

nebe

stim

mte

Zei

leau

sde

rDat

eiau

sgeg

eben

wer

den.

Wir

nutz

ensi

einread_file()

.

Page 462: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Inread_file()

wir

dei

neD

atei

gele

sen.

Zue

rst

wir

dda

sM

enüf

enst

erak

tual

isie

rt,d

ann

wir

dei

nne

ues

Fens

tere

rzeu

gtun

dei

neD

atei

zeile

nwei

seei

ngel

esen

.Es

wir

dda

rauf

geac

htet

,das

sm

axim

al60

Zei

chen

eine

rZ

eile

darg

este

lltw

erde

n.A

nsch

ließe

ndw

ird

eine

eige

neW

arte

schl

eife

durc

hlau

-fe

n,di

edi

eTa

stat

urei

ngab

enem

pfän

gt.B

eide

rE

inga

bevo

nx

wir

ddi

eSc

hlei

feab

gebr

oche

nun

dzu

mH

aupt

prog

ram

mzu

rück

verz

wei

gt.F

alls

eine

Cur

sorta

ste

gedr

ückt

wur

de,s

ow

irdde

rBer

eich

derL

ogda

tei,

derb

eim

näch

s-te

nD

urch

gang

gele

sen

wir

d,ne

ube

rech

net.

Hie

rist

nich

twic

htig

,wie

lang

die

Dat

eiis

t,de

nnlinecache.getline()

liefe

rtun

sei

nen

leer

enSt

ring

zurü

ck,w

enn

wir

vers

uche

n,üb

erda

sD

atei

ende

hina

uszu

lese

n.

ImH

aupt

prog

ram

mw

ird

ein

neue

sFe

nste

rstdscr

erze

ugt.

Von

dort

aus

wird

die

Hau

ptsc

hlei

feab

gear

beite

t.B

eiF1

wird

/var/log/messages

und

beiF2

/var/log/syslog

gele

sen.

Mit

xw

ird

das

Prog

ram

mab

gebr

oche

n.B

eije

dem

Dur

chga

ngw

ird

das

Men

üak

tual

isie

rtun

dda

sal

teL

og-F

enst

er,w

elch

esvi

elle

icht

noch

aufd

emB

ildsc

hirm

ersc

hein

t,ge

lösc

ht.

Page 463: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

19.4

Gro

ßeFe

nste

r

Imle

tzte

nB

eisp

iel

habe

nw

irge

sehe

n,da

sses

Müh

eko

stet

,ein

enTe

xtin

eine

mFe

nste

rdar

zust

elle

n,w

enn

die

Zei

lenl

änge

oder

die

Text

läng

egr

ößer

ista

lsdi

eFe

nste

raus

maß

e.E

sgi

btei

nen

Weg

daru

mhe

rum

.Wir

könn

enm

itC

urse

sse

hrgr

oße

Fens

ter

erze

ugen

,und

nur

eine

nTe

ilau

fde

nB

ildsc

hirm

brin

gen.

Solc

hegr

oßen

Fens

terh

eiße

nPa

dun

dsi

ndni

chta

ndi

eA

usm

aße

des

daru

nter

liege

nden

Fens

ters

gebu

nden

.Das

folg

ende

Prog

ram

mnu

tzts

olch

ein

Pad,

esis

t100

00Z

eile

nho

chun

d30

00Sp

alte

nbr

eit.

Es

wir

ddi

esm

aldi

eD

atei

/var/log/messages

gele

sen,

navi

gier

enkö

nnen

Sie

mit

alle

nvi

erC

urso

rtas

ten,

beid

erE

inga

bevo

nx

wir

dda

sPr

ogra

mm

been

det.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

curses

import

linecache

def

init_curses():

stdscr

=curses.initscr()

Page 464: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

curses.noecho()

curses.cbreak()

stdscr.keypad(1)

curses.start_color()

curses.init_pair(1,

curses.COLOR_BLACK,

curses.COLOR_BLUE)

curses.init_pair(2,

curses.COLOR_GREEN,

curses.COLOR_BLUE)

stdscr.bkgd(curses.color_pair(1))

stdscr.box()

stdscr.refresh()

returnstdscr

stdscr

=init_curses()

#Aktuelle

Screengröße

ermitteln

maxy,

maxx

=stdscr.getmaxyx()

#Großes

Pad

erzeugen

pad

=curses.newpad(10000,

3000)

for

iin

xrange(10000):

line

=linecache.getline('/var/log/messages',

i)

s=

'[%5d]

%s'

%(i,

line)

pad.addstr(i,

1,

s)

#Wir

merken

uns,

wo

wir

sind

line_start

=1

col_start

=1

Page 465: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

while

True:

#Teile

des

Pads

aufs

Display

bringen

pad.refresh(line_start,

col_start,

1,

1,

maxy-2,

maxx-2)

c=

stdscr.getch()

ifc

==

ord('x'):

break

elifc

==

curses.KEY_DOWN:

line_start

+=

1elifc

==

curses.KEY_UP:

ifline_start

>1:

line_start

-=

1elifc

==

curses.KEY_LEFT:

ifcol_start

>1:

col_start

-=

1elifc

==

curses.KEY_RIGHT:

col_start

+=

1

#ende

curses.nocbreak()

stdscr.keypad(0)

curses.echo()

curses.endwin()

Um

das

inne

rePa

dan

das

äuße

reFe

nste

ran

zupa

ssen

,fr

agen

wir

mit

stdscr.getmaxyx()

die

Aus

maß

ede

sFe

nste

rsab

.Uns

erPa

dw

ird

dann

Page 466: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

imIn

nere

nlie

gen,

umge

ben

von

eine

mR

and.

Das

eige

ntlic

hePa

dw

ird

mit

curses.newpad(10000,3000)

erze

ugt.

Es

ist1

0000

Zei

len

hoch

und

3000

Zei

len

lang

.Das

sollt

efü

rdie

seD

atei

reic

hen.

Mit

ders

chon

beka

nnte

nM

etho

dew

irdda

sFen

ster

mit

dem

Dat

eiin

halt

gefü

llt.N

euis

tnoc

h,da

ssw

irle

-di

glic

hei

nen

Aus

schn

ittau

sdem

Pad

aufd

enB

ildsc

hirm

brin

gen.

Die

serle

digt

pad.refresh(PadStartZeile,PadStartSpalte,WinY,WinX,WinBreite,WinHöhe)

.H

ierb

eisi

nd"Win*

"-A

rgum

ente

die

Aus

maß

ede

sum

gebe

nden

Fens

ters

."PadStartZeile

"un

d"PadStartSpalte

"hi

ngeg

ensi

ndde

rjen

ige

Urs

prun

g,de

rim

inne

ren

des

Pads

liegt

und

inde

rlin

ken

ober

enE

cke

des

Fens

ters

zuse

hen

sein

soll.

Bei

mD

ruck

aufe

ine

Cur

sor-

Tast

ew

erde

ndi

ese

Wer

teen

tspr

eche

ndm

odifi

zier

t,da

nnw

ird

das

Pad

neu

geze

ichn

et.E

sw

ird

also

inne

rhal

bde

sPa

dsge

scro

llt.

Page 467: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

19.5

Mau

sere

igni

sse

Auf

Mau

sere

igni

sse

sind

wir

bish

erno

chni

chte

inge

gang

en.G

rund

genu

g,da

shi

erin

eine

mkl

eine

nA

bsch

nitt

nach

zuho

len.

Mau

sere

igni

sse

wer

den

inde

rH

aupt

schl

eife

eben

sobe

arbe

itet

wie

Tast

en,

die

spez

ielle

Tast

eis

tcurses.KEY_MOUSE

.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

curses

import

linecache

def

init_curses():

stdscr

=curses.initscr()

curses.noecho()

curses.cbreak()

stdscr.keypad(1)

curses.start_color()

curses.init_pair(1,

curses.COLOR_BLACK,

curses.COLOR_BLUE)

stdscr.bkgd(curses.color_pair(1))

stdscr.box()

stdscr.refresh()

Page 468: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

returnstdscr

stdscr

=init_curses()

#Maus

initialisieren

avail,

oldmask

=curses.mousemask(curses.BUTTON1_PRESSED)

curses.mousemask(avail)

while

True:

c=

stdscr.getch()

ifc

==

ord('x'):

break

elifc

==

curses.KEY_MOUSE:

id,

x,

y,

z,

button

=curses.getmouse()

s=

"Mouse-Ereignis

bei

(%d

;%d

;%d),

ID=

%d,

button

=%d"

%(x,

y,

z,

id,

button)

stdscr.addstr(1,

1,

s)

stdscr.clrtoeol()

stdscr.refresh()

#ende

curses.nocbreak()

stdscr.keypad(0)

curses.echo()

curses.endwin()

Page 469: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Dam

itau

fMau

sere

igni

sse

über

haup

trea

gier

twer

den

kann

,mus

sei

neM

aus-

Mas

keer

stel

ltw

erde

n.D

ieFu

nktio

ncurses.mousemask()

erw

arte

tein

eso

lche

Mas

keun

dlie

fert

ein

Tupe

laus

alle

nve

rfüg

bare

nM

ause

reig

niss

enun

dde

rlet

zten

Mas

kezu

rück

.Wir

wol

len

wir

klic

hal

leE

reig

niss

ebe

hand

elt

wis

sen

und

nutz

enei

nen

zwei

ten

Auf

rufd

iese

rFun

ktio

n,um

das

mitz

utei

len.

curses.getmouse()

liefe

rtun

sei

nTu

pelm

itde

nbe

nötig

ten

Mau

sinf

or-

mat

ione

n.D

iese

wer

den

aufd

emB

ildsc

hirm

darg

este

llt.

19.6

Text

box

Cur

ses

enth

ält

eine

nru

dim

entä

ren

Edi

tor,

den

man

nutz

enka

nn,

umin

-ne

rhal

bei

nes

Fens

ters

Text

zusc

hrei

ben.

Er

wir

dei

ngeb

unde

ndu

rch

curses.textpad.Textbox(Fenster)

und

bein

halte

tei

neM

etho

deedit()

,um

Text

entg

egen

zune

hmen

.Die

seM

etho

deka

nnm

itei

nem

Valid

a-to

rzum

Filte

rnvo

nTa

sten

drüc

ken

vers

ehen

wer

den.

Das

folg

ende

Prog

ram

mde

mon

stri

ert,

wie

man

dies

enE

dito

rein

bind

etun

dde

nei

ngeg

eben

enTe

xtin

Page 470: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

eine

man

dere

nFe

nste

rdar

stel

lt.B

eend

etw

irdde

rEdi

torm

itSTRG+G

.Dan

nw

irdim

ande

ren

Fens

terd

erei

ngeg

eben

eTe

xtda

rges

tellt

,das

Prog

ram

mka

nnan

schl

ieße

ndm

itei

nem

Tast

endr

uck

been

detw

erde

n.

#!/usr/bin/python

#-*-

coding:

utf-8

-*-

import

curses

import

curses.textpad

#Initialisieren

stdscr

=curses.initscr()

curses.noecho()

curses.cbreak()

stdscr.keypad(1)

curses.start_color()

curses.init_pair(1,

curses.COLOR_GREEN,

curses.COLOR_BLUE)

curses.init_pair(2,

curses.COLOR_YELLOW,

curses.COLOR_BLACK)

stdscr.bkgd(curses.color_pair(1))

stdscr.refresh()

#Edit-Fenster

win1

=curses.newwin(20,

40,

10,

5)

Page 471: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

win1.bkgd(curses.color_pair(2))

#Darstellungsfenster

win2

=curses.newwin(20,

40,

10,

50)

win2.bkgd(curses.color_pair(2))

win2.refresh()

#Textbox

textbox

=curses.textpad.Textbox(win1)

text

=textbox.edit()

#Text

übernehmen

win2.addstr(0,

0,

text)

win2.refresh()

#Ende

c=

stdscr.getch()

curses.nocbreak()

stdscr.keypad(0)

curses.echo()

curses.endwin()

Page 472: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

19.7

Zus

amm

enfa

ssun

g

Sie

habe

nin

dies

emK

apite

lein

engr

oben

Übe

rblic

küb

erei

nige

ausg

ewäh

lteFä

higk

eite

nvo

nC

urse

ser

halte

n.C

urse

sse

lbst

kann

nurs

ehre

infa

che

Din

ge,

wie

Rec

htec

keal

sFe

nste

rver

wal

ten

und

aufT

aste

ndrü

cke

reag

iere

n.D

afür

sind

mit

Cur

ses

gesc

hrie

bene

Obe

rfläc

hen

schn

elle

ral

sgr

afisc

he,w

asab

erau

chke

inK

unst

stüc

kis

t.A

lsA

usbl

ick

könn

enw

irIh

nen

das

Mod

ulU

rWid

2

nenn

en,w

elch

esei

nre

chtv

olls

tänd

iges

TU

I-To

olki

tdar

stel

ltun

dau

fCur

ses

basi

ert.

2http://excess.org/urwid/

Page 473: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 474: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

20W

eite

rfüh

rend

eIn

form

atio

nen

Bitt

ebi

sau

fbe

grün

dbar

eA

usna

hmen

nich

tm

ehr

als

2L

inks

pro

The

ma.

Die

sso

llke

ine

Lin

ksam

mlu

ngw

erde

n,so

nder

nda

sB

uch

sinn

voll

ergä

nzen

.Vo

rhan

dene

Wik

ibüc

hers

olle

nam

Anf

ang

derK

apite

lode

rin

derP

roje

ktbe

-sc

hrei

bung

steh

en.B

esse

reV

erw

eise

solle

nw

enig

erau

ssag

ekrä

ftig

eL

inks

ablö

sen.

20.1

Ein

führ

ung,

erst

eSc

hritt

e

(Allg

emei

neE

infü

hrun

gen)

463

Page 475: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

•ht

tp://

dive

into

pyth

on.o

rg/to

c/in

dex.

htm

l1en

glis

ch,B

eisp

iele

20.2

Mod

ule

(Mitg

elie

fert

eM

odul

e)

•ht

tp://

docs

.pyt

hon.

org/

mod

inde

x.ht

ml2

Lis

tevo

nM

odul

en,e

nglis

ch,B

ei-

spie

le

1http://diveintopython.org/toc/index.html

2http://docs.python.org/modindex.html

Page 476: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

20.3

Dat

eien

,I/O

•ht

tp://

ww

w.jo

hnny

-lin

.com

/cda

t_tip

s/tip

s_fil

eio/

bin_

arra

y.ht

ml3

engl

isch

,ei

nles

enei

nes

Arr

ays

•ht

tp://

ww

w.fr

eene

tpag

es.c

o.uk

/hp/

alan

.gau

ld/tu

tfile

s.ht

m4

engl

isch

,Dat

eibe

-ha

ndlu

ng

20.4

XM

L

•ht

tp://

code

spea

k.ne

t/lxm

l/5Py

thon

-Im

plem

enta

tion

von

libX

ML

26 ,en

g-lis

ch,B

eisp

iele

3http://www.johnny-lin.com/cdat_tips/tips_fileio/bin_array.

html

4http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm

5http://codespeak.net/lxml/

6http://xmlsoft.org/

Page 477: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

20.5

Dat

enba

nken

•ht

tp://

wik

i.pyt

hon.

org/

moi

n/M

ySQ

L7

-Lin

ksam

mlu

ng,e

nglis

ch•

http

://w

iki.p

ytho

n.or

g/m

oin/

Post

greS

QL

8-L

inks

amm

lung

,eng

lisch

20.6

PyG

ame

•ht

tp://

ww

w.p

ytho

n-fo

rum

.de/

topi

c-13

367.

htm

l9Tu

tori

alim

Pyth

on-F

orum

7http://wiki.python.org/moin/MySQL

8http://wiki.python.org/moin/PostgreSQL

9http://www.python-forum.de/topic-13367.html

Page 478: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

20.7

Qt

•ht

tp://

zetc

ode.

com

/tuto

rial

s/py

qt4/

10Tu

tori

al,e

nglis

ch,B

eisp

iele

•ht

tp://

ww

w.c

omm

andp

rom

pt.c

om/c

omm

unity

/pyq

t/11Tu

tori

al,

engl

isch

,B

eisp

iele

20.8

wxP

ytho

n

•ht

tp://

ww

w.z

etco

de.c

om/w

xpyt

hon/

12Tu

tori

al,e

nglis

ch•

http

://w

ww

.wxp

ytho

n.or

g/do

cs/a

pi/13

wxP

ytho

nA

PI,e

nglis

ch

10http://zetcode.com/tutorials/pyqt4/

11http://www.commandprompt.com/community/pyqt/

12http://www.zetcode.com/wxpython/

13http://www.wxpython.org/docs/api/

Page 479: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

20.9

PyG

TK

•ht

tp://

ww

w.p

ygtk

.org

/14Tu

tori

alun

dR

efer

enzd

okum

enta

tion,

engl

isch

20.1

0C

urse

s

•ht

tp://

docs

.pyt

hon.

org/

dev/

how

to/c

urse

s.ht

ml15

How

To,e

nglis

ch

20.1

1So

nstig

es

•ht

tp://

ww

w.p

ytho

n-fo

rum

.de/

16Py

thon

-For

um

14http://www.pygtk.org/

15http://docs.python.org/dev/howto/curses.html

16http://www.python-forum.de/

Page 480: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

•ht

tp://

ww

w.p

ytho

ncha

lleng

e.co

m/17

Prog

ram

mie

rauf

gabe

n,en

glis

ch,W

ett-

bew

erb

17http://www.pythonchallenge.com/

Page 481: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 482: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

21C

ontr

ibut

ors

Edi

tsU

ser

5A

rneB

ab1

4D

erSa

scha

2

40D

irk

Hue

nnig

er3

7Fi

xit4

1http://de.wikibooks.org/w/index.php?title=Benutzer:ArneBab

2http://de.wikibooks.org/w/index.php?title=Benutzer:

DerSascha

3http://de.wikibooks.org/w/index.php?title=Benutzer:

Dirk_Huenniger

4http://de.wikibooks.org/w/index.php?title=Benutzer:Fixit

471

Page 483: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

1Fr

itzth

ecat

5

1H

ooo6

1Ir

eas7

3Ja

n8

1K

lart

ext9

18K

laus

Eif

ert10

1L

ivin

gSha

dow

-SU

L11

5http://de.wikibooks.org/w/index.php?title=Benutzer:

Fritzthecat

6http://de.wikibooks.org/w/index.php?title=Benutzer:Hooo

7http://de.wikibooks.org/w/index.php?title=Benutzer:Ireas

8http://de.wikibooks.org/w/index.php?title=Benutzer:Jan

9http://de.wikibooks.org/w/index.php?title=Benutzer:

Klartext

10http://de.wikibooks.org/w/index.php?title=Benutzer:

Klaus_Eifert

11http://de.wikibooks.org/w/index.php?title=Benutzer:

LivingShadow-SUL

Page 484: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

3M

icha

elFr

ey12

1M

jcha

el13

1M

oBde

r1.14

1N

ils-H

ero15

18N

koeh

ring

16

1Pi

rad17

102

Schm

idt2

18

12http://de.wikibooks.org/w/index.php?title=Benutzer:

MichaelFrey

13http://de.wikibooks.org/w/index.php?title=Benutzer:Mjchael

14http://de.wikibooks.org/w/index.php?title=Benutzer:

MoB_der_1.

15http://de.wikibooks.org/w/index.php?title=Benutzer:

Nils-Hero

16http://de.wikibooks.org/w/index.php?title=Benutzer:

Nkoehring

17http://de.wikibooks.org/w/index.php?title=Benutzer:Pirad

18http://de.wikibooks.org/w/index.php?title=Benutzer:

Schmidt2

Page 485: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

1Sc

oder

19

1Se

pp20

1Sh

oul21

4Sp

eck-

Mad

e22

1St

efan

80h23

300

Tand

ar24

3T

hira

fydi

on25

19http://de.wikibooks.org/w/index.php?title=Benutzer:Scoder

20http://de.wikibooks.org/w/index.php?title=Benutzer:Sepp

21http://de.wikibooks.org/w/index.php?title=Benutzer:Shoul

22http://de.wikibooks.org/w/index.php?title=Benutzer:

Speck-Made

23http://de.wikibooks.org/w/index.php?title=Benutzer:

Stefan80h

24http://de.wikibooks.org/w/index.php?title=Benutzer:Tandar

25http://de.wikibooks.org/w/index.php?title=Benutzer:

Thirafydion

Page 486: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

1Tu

relio

n26

27

26http://de.wikibooks.org/w/index.php?title=Benutzer:

Turelion

27http://de.wikibooks.org/w/index.php?title=Benutzer:%D7%90

Page 487: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477
Page 488: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Abb

ildun

gsve

rzei

chni

s

•G

FDL

:Gnu

Free

Doc

umen

tatio

nL

icen

se.http://www.gnu.org/

licenses/fdl.html

•cc

-by-

sa-3

.0:C

reat

ive

Com

mon

sA

ttrib

utio

nSh

areA

like

3.0

Lic

ense

.http://creativecommons.org/licenses/by-sa/3.0/

•cc

-by-

sa-2

.5:C

reat

ive

Com

mon

sA

ttrib

utio

nSh

areA

like

2.5

Lic

ense

.http://creativecommons.org/licenses/by-sa/2.5/

•cc

-by-

sa-2

.0:C

reat

ive

Com

mon

sA

ttrib

utio

nSh

areA

like

2.0

Lic

ense

.http://creativecommons.org/licenses/by-sa/2.0/

477

Page 489: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

•cc

-by-

sa-1

.0:C

reat

ive

Com

mon

sA

ttrib

utio

nSh

areA

like

1.0

Lic

ense

.http://creativecommons.org/licenses/by-sa/1.0/

•cc

-by-

2.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

2.0

Lic

ense

.http://

creativecommons.org/licenses/by/2.0/

•cc

-by-

2.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

2.0

Lic

ense

.http://

creativecommons.org/licenses/by/2.0/deed.en

•cc

-by-

2.5:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

2.5

Lic

ense

.http://

creativecommons.org/licenses/by/2.5/deed.en

•cc

-by-

3.0:

Cre

ativ

eC

omm

ons

Attr

ibut

ion

3.0

Lic

ense

.http://

creativecommons.org/licenses/by/3.0/deed.en

•G

PL:

GN

UG

ener

alPu

blic

Lic

ense

.http://www.gnu.org/

licenses/gpl-2.0.txt

•L

GPL

:G

NU

Les

ser

Gen

eral

Publ

icL

icen

se.http://www.gnu.

org/licenses/lgpl.html

Page 490: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

•PD

:Thi

sim

age

isin

the

publ

icdo

mai

n.

•A

TT

R:

The

copy

righ

tho

lder

ofth

isfil

eal

low

san

yone

tous

eit

for

any

purp

ose,

prov

ided

that

the

copy

righ

thol

der

ispr

oper

lyat

trib

uted

.R

edis

trib

utio

n,de

rivat

ive

wor

k,co

mm

erci

alus

e,an

dal

loth

erus

eis

perm

itted

.

•EU

RO

:Thi

sis

the

com

mon

(rev

erse

)fac

eof

aeu

roco

in.T

heco

pyrig

hton

the

desi

gnof

the

com

mon

face

ofth

eeu

roco

ins

belo

ngs

toth

eE

urop

ean

Com

mis

sion

.Aut

hori

sed

isre

prod

uctio

nin

afo

rmat

with

out

relie

f(dr

awin

gs,p

aint

ings

,film

s)pr

ovid

edth

eyar

eno

tdet

rim

enta

lto

the

imag

eof

the

euro

.

•L

FK:

Liz

enz

Frei

eK

unst

.http://artlibre.org/licence/

lal/de

•C

FR:C

opyr

ight

free

use.

•E

PL:E

clip

sePu

blic

Lic

ense

.http://www.eclipse.org/org/

documents/epl-v10.php

Page 491: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Cop

ies

ofth

eG

PL,t

heL

GPL

asw

ell

asa

GFD

Lar

ein

clud

edin

chap

ter

Lic

ense

s28.P

leas

eno

teth

atim

ages

inth

epu

blic

dom

ain

dono

treq

uire

attr

i-bu

tion.

You

may

clic

kon

the

imag

enu

mbe

rsin

the

follo

win

gta

ble

toop

enth

ew

ebpa

geof

the

imag

esin

your

web

brow

er.

28K

apite

l22

aufS

eite

483

Page 494: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

22L

icen

ses

22.1

GN

UG

EN

ER

AL

PUB

LIC

LIC

EN

SEV

ersi

on3,

29Ju

ne20

07

Cop

yrig

ht©

2007

Free

Soft

war

eFo

unda

tion,

Inc.

<http

://fs

f.org

/>

Eve

ryon

eis

perm

itted

toco

pyan

ddi

stri

bute

verb

atim

copi

esof

this

licen

sedo

cum

ent,

but

chan

ging

itis

not

allo

wed

.Pr

eam

ble

The

GN

UG

ener

alPu

blic

Li-

cens

eis

afr

ee,c

opyl

eft

licen

sefo

rso

ftw

are

and

othe

rki

nds

ofw

orks

.

The

licen

ses

for

mos

tso

ftw

are

and

othe

rpra

ctic

alw

orks

are

de-

sign

edto

take

away

your

free

-do

mto

shar

ean

dch

ange

the

wor

ks.

By

cont

rast

,th

eG

NU

Gen

eral

Publ

icL

icen

seis

inte

n-de

dto

guar

ante

eyo

urfr

eedo

mto

shar

ean

dch

ange

all

vers

i-on

sof

apr

ogra

m–t

om

ake

su-

reit

rem

ains

free

soft

war

efo

ral

lits

user

s.W

e,th

eFr

eeSo

ft-

war

eFo

unda

tion,

use

the

GN

UG

ener

alPu

blic

Lic

ense

form

ost

ofou

rso

ftw

are;

itap

plie

sal

soto

any

othe

rw

ork

rele

ased

this

way

byits

auth

ors.

You

can

app-

lyit

toyo

urpr

ogra

ms,

too.

Whe

nw

esp

eak

offr

eeso

ftw

are,

we

are

refe

rrin

gto

free

dom

,not

pric

e.O

urG

ener

alPu

blic

Li-

cens

esar

ede

sign

edto

mak

esu

-re

that

you

have

the

free

dom

todi

stri

bute

copi

esof

free

soft

-w

are

(and

char

gefo

rth

emif

you

wis

h),t

haty

oure

ceiv

eso

ur-

ceco

deor

can

get

itif

you

wan

tit,

that

you

can

chan

geth

eso

ftw

are

orus

epi

eces

ofit

inne

wfr

eepr

ogra

ms,

and

that

you

know

you

can

doth

ese

thin

gs.

Topr

otec

tyou

rri

ghts

,we

need

topr

even

tot

hers

from

deny

ing

you

thes

eri

ghts

oras

king

you

tosu

rren

der

the

righ

ts.T

here

fo-

re,

you

have

cert

ain

resp

onsi

bi-

litie

sif

you

dist

ribu

teco

pies

ofth

eso

ftw

are,

orif

you

mod

ify

it:re

spon

sibi

litie

sto

resp

ectt

hefr

eedo

mof

othe

rs.

For

exam

ple,

ifyo

udi

stri

bute

copi

esof

such

apr

ogra

m,w

he-

ther

grat

isor

fora

fee,

you

mus

tpa

sson

toth

ere

cipi

ents

the

sam

efr

eedo

ms

that

you

rece

i-ve

d.Y

oum

ust

mak

esu

reth

at

483

Page 495: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

they

,to

o,re

ceiv

eor

can

get

the

sour

ceco

de.A

ndyo

um

ust

show

them

thes

ete

rms

soth

eykn

owth

eirr

ight

s.

Dev

elop

ers

that

use

the

GN

UG

PLpr

otec

tyo

urri

ghts

with

two

step

s:(1

)as

sert

copy

righ

ton

the

soft

war

e,an

d(2

)of

fer

you

this

Lic

ense

givi

ngyo

ule

-ga

lper

mis

sion

toco

py,d

istr

ibu-

tean

d/or

mod

ify

it.

Fort

hede

velo

pers

’and

auth

ors’

prot

ectio

n,th

eG

PLcl

earl

yex

-pl

ains

that

ther

eis

now

arra

n-ty

for

this

free

soft

war

e.Fo

rbo

thus

ers’

and

auth

ors’

sake

,th

eG

PLre

quir

esth

atm

odifi

edve

rsio

nsbe

mar

ked

asch

ange

d,so

that

thei

rpr

oble

ms

will

not

beat

trib

uted

erro

neou

sly

toau

t-ho

rsof

prev

ious

vers

ions

.

Som

ede

vice

sar

ede

sign

edto

deny

user

sac

cess

toin

stal

lor

run

mod

ified

vers

ions

ofth

eso

ftw

are

insi

deth

em,

alth

ough

the

man

ufac

ture

rcan

doso

.Thi

sis

fund

amen

tally

inco

mpa

tible

with

the

aim

ofpr

otec

ting

user

s’fr

eedo

mto

chan

geth

eso

ftw

are.

The

syst

emat

icpa

ttern

ofsu

chab

use

occu

rsin

the

area

of

prod

ucts

for

indi

vidu

als

tous

e,w

hich

ispr

ecis

ely

whe

reit

ism

ost

unac

cept

able

.T

here

fore

,w

eha

vede

sign

edth

isve

rsio

nof

the

GPL

topr

ohib

itth

epr

ac-

tice

for

thos

epr

oduc

ts.

Ifsu

chpr

oble

ms

aris

esu

bsta

ntia

llyin

othe

rdo

mai

ns,

we

stan

dre

ady

toex

tend

this

prov

isio

nto

tho-

sedo

mai

nsin

futu

reve

rsio

nsof

the

GPL

,as

need

edto

prot

ect

the

free

dom

ofus

ers.

Fina

lly,e

very

prog

ram

isth

rea-

tene

dco

nsta

ntly

byso

ftw

are

pa-

tent

s.St

ates

shou

ldno

tal

low

pate

nts

tore

stri

ctde

velo

pmen

tan

dus

eof

soft

war

eon

gene

ral-

purp

ose

com

pute

rs,

but

inth

o-se

that

do,w

ew

ish

toav

oid

the

spec

ial

dang

erth

atpa

tent

sap

-pl

ied

toa

free

prog

ram

coul

dm

ake

itef

fect

ivel

ypr

opri

etar

y.To

prev

ent

this

,th

eG

PLas

su-

res

that

pate

nts

cann

otbe

used

tore

nder

the

prog

ram

non-

free

.

The

prec

ise

term

san

dco

n-di

tions

for

copy

ing,

dist

ribu

-tio

nan

dm

odifi

catio

nfo

llow

.T

ER

MS

AN

DC

ON

DIT

ION

S0.

Defi

nitio

ns.

“Thi

sL

icen

se”

refe

rsto

vers

ion

3of

the

GN

UG

ener

alPu

blic

Li-

cens

e.

“Cop

yrig

ht”

also

mea

nsco

pyri

ght-

like

law

sth

atap

-pl

yto

othe

rki

nds

ofw

orks

,su

chas

sem

icon

duct

orm

asks

.

“The

Prog

ram

”re

fers

toan

yco

-py

righ

tabl

ew

ork

licen

sed

unde

rth

isL

icen

se.

Eac

hlic

ense

eis

addr

esse

das

“you

”.“L

icen

sees

”an

d“r

ecip

ient

s”m

aybe

indi

vi-

dual

sor

orga

niza

tions

.

To“m

odif

y”a

wor

km

eans

toco

pyfr

omor

adap

tal

lor

part

ofth

ew

ork

ina

fash

ion

requ

i-ri

ngco

pyri

ghtp

erm

issi

on,o

ther

than

the

mak

ing

ofan

exac

tco

py.T

here

sulti

ngw

ork

isca

l-le

da

“mod

ified

vers

ion”

ofth

eea

rlie

rw

ork

ora

wor

k“b

ased

on”

the

earl

ierw

ork.

A“c

over

edw

ork”

mea

nsei

ther

the

unm

odifi

edPr

ogra

mor

aw

ork

base

don

the

Prog

ram

.

To“p

ropa

gate

”a

wor

km

eans

todo

anyt

hing

with

itth

at,

wi-

thou

tpe

rmis

sion

,w

ould

mak

eyo

udi

rect

lyor

seco

ndar

ilylia

-

ble

for

infr

inge

men

tun

der

ap-

plic

able

copy

righ

tla

w,

exce

ptex

ecut

ing

iton

aco

mpu

ter

orm

odif

ying

apr

ivat

eco

py.

Pro-

paga

tion

incl

udes

copy

ing,

dis-

trib

utio

n(w

ithor

with

out

mo-

dific

atio

n),

mak

ing

avai

labl

eto

the

publ

ic,

and

inso

me

coun

-tr

ies

othe

ract

iviti

esas

wel

l.

To“c

onve

y”a

wor

km

eans

any

kind

ofpr

opag

atio

nth

aten

able

sot

her

part

ies

tom

ake

orre

cei-

veco

pies

.Mer

ein

tera

ctio

nw

itha

user

thro

ugh

aco

mpu

ter

net-

wor

k,w

ithno

tran

sfer

ofa

copy

,is

notc

onve

ying

.

An

inte

ract

ive

user

inte

rfac

edi

s-pl

ays

“App

ropr

iate

Leg

alN

oti-

ces”

toth

eex

tent

that

itin

clu-

des

aco

nven

ient

and

prom

inen

t-ly

visi

ble

feat

ure

that

(1)

dis-

play

san

appr

opri

ate

copy

righ

tno

tice,

and

(2)t

ells

the

user

that

ther

eis

now

arra

nty

fort

hew

ork

(exc

eptt

oth

eex

tent

that

war

ran-

ties

are

prov

ided

),th

atlic

ense

esm

ayco

nvey

the

wor

kun

dert

his

Lic

ense

,and

how

tovi

ewa

copy

ofth

isL

icen

se.

Ifth

ein

terf

ace

pres

ents

alis

tof

user

com

man

-ds

orop

tions

,suc

has

am

enu,

a

Page 496: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

prom

inen

tite

min

the

listm

eets

this

crite

rion

.1.S

ourc

eC

ode.

The

“sou

rce

code

”fo

ra

wor

km

eans

the

pref

erre

dfo

rmof

the

wor

kfo

rm

akin

gm

odifi

catio

nsto

it.“O

bjec

tco

de”

mea

nsan

yno

n-so

urce

form

ofa

wor

k.

A“S

tand

ard

Inte

rfac

e”m

eans

anin

terf

ace

that

eith

eris

anof

-fic

ials

tand

ard

defin

edby

are

co-

gniz

edst

anda

rds

body

,or,

inth

eca

seof

inte

rfac

essp

ecifi

edfo

ra

part

icul

arpr

ogra

mm

ing

lan-

guag

e,on

eth

atis

wid

ely

used

amon

gde

velo

pers

wor

king

inth

atla

ngua

ge.

The

“Sys

tem

Lib

rari

es”

ofan

exec

utab

lew

ork

incl

ude

any-

thin

g,ot

her

than

the

wor

kas

aw

hole

,tha

t(a)

isin

clud

edin

the

norm

alfo

rmof

pack

agin

ga

Ma-

jorC

ompo

nent

,but

whi

chis

not

part

ofth

atM

ajor

Com

pone

nt,

and

(b)

serv

eson

lyto

enab

leus

eof

the

wor

kw

ithth

atM

ajor

Com

pone

nt,

orto

impl

emen

ta

Stan

dard

Inte

rfac

efo

rw

hich

anim

plem

enta

tion

isav

aila

ble

toth

epu

blic

inso

urce

code

form

.A

“Maj

orC

ompo

nent

”,in

this

cont

ext,

mea

nsa

maj

ores

sent

i-

alco

mpo

nent

(ker

nel,

win

dow

syst

em,a

ndso

on)

ofth

esp

eci-

ficop

erat

ing

syst

em(i

fan

y)on

whi

chth

eex

ecut

able

wor

kru

ns,

ora

com

pile

rus

edto

prod

uce

the

wor

k,or

anob

ject

code

in-

terp

rete

ruse

dto

run

it.

The

“Cor

resp

ondi

ngSo

urce

”fo

ra

wor

kin

obje

ctco

defo

rmm

eans

all

the

sour

ceco

dene

e-de

dto

gene

rate

,ins

tall,

and

(for

anex

ecut

able

wor

k)ru

nth

eob

ject

code

and

tom

odif

yth

ew

ork,

incl

udin

gsc

ript

sto

con-

trol

thos

eac

tiviti

es.

How

ever

,it

does

not

incl

ude

the

wor

k’s

Syst

emL

ibra

ries

,or

gene

ral-

purp

ose

tool

sor

gene

rally

avai

labl

efr

eepr

ogra

ms

whi

char

eus

edun

mod

ified

inpe

rfor

-m

ing

thos

eac

tiviti

esbu

tw

hich

are

not

part

ofth

ew

ork.

For

exam

ple,

Cor

resp

ondi

ngSo

urce

incl

udes

inte

rfac

ede

finiti

onfil

esas

soci

ated

with

sour

cefil

esfo

rth

ew

ork,

and

the

sour

ceco

defo

rsha

red

libra

ries

and

dy-

nam

ical

lylin

ked

subp

rogr

ams

that

the

wor

kis

spec

ifica

llyde

sign

edto

requ

ire,

such

asby

intim

ate

data

com

mun

icat

ion

orco

ntro

lflo

wbe

twee

nth

ose

subp

rogr

ams

and

othe

rpa

rts

ofth

ew

ork.

The

Cor

resp

ondi

ngSo

urce

need

not

incl

ude

anyt

hing

that

user

sca

nre

gene

rate

auto

ma-

tical

lyfr

omot

her

part

sof

the

Cor

resp

ondi

ngSo

urce

.

The

Cor

resp

ondi

ngSo

urce

fora

wor

kin

sour

ceco

defo

rmis

that

sam

ew

ork.

2.B

asic

Perm

issi

-on

s.

All

righ

tsgr

ante

dun

der

this

Li-

cens

ear

egr

ante

dfo

rthe

term

ofco

pyri

ght

onth

ePr

ogra

m,

and

are

irre

voca

ble

prov

ided

the

sta-

ted

cond

ition

sar

em

et.T

his

Li-

cens

eex

plic

itly

affir

ms

your

un-

limite

dpe

rmis

sion

toru

nth

eun

mod

ified

Prog

ram

.T

heou

t-pu

tfr

omru

nnin

ga

cove

red

wor

kis

cove

red

byth

isL

icen

-se

only

ifth

eou

tput

,gi

ven

itsco

nten

t,co

nstit

utes

aco

vere

dw

ork.

Thi

sL

icen

seac

know

led-

ges

your

righ

tsof

fair

use

orot

here

quiv

alen

t,as

prov

ided

byco

pyri

ghtl

aw.

You

may

mak

e,ru

nan

dpr

opa-

gate

cove

red

wor

ksth

atyo

udo

not

conv

ey,

with

out

cond

ition

s

solo

ngas

your

licen

seot

herw

i-se

rem

ains

info

rce.

You

may

conv

eyco

vere

dw

orks

toot

hers

for

the

sole

purp

ose

ofha

ving

them

mak

em

odifi

catio

nsex

clu-

sive

lyfo

ryo

u,or

prov

ide

you

with

faci

litie

sfo

rru

nnin

gth

ose

wor

ks,

prov

ided

that

you

com

-pl

yw

ithth

ete

rms

ofth

isL

icen

-se

inco

nvey

ing

all

mat

eria

lfo

rw

hich

you

dono

tco

ntro

lco

py-

righ

t.T

hose

thus

mak

ing

orru

n-ni

ngth

eco

vere

dw

orks

for

you

mus

tdo

soex

clus

ivel

yon

your

beha

lf,u

nder

your

dire

ctio

nan

dco

ntro

l,on

term

sth

atpr

ohib

itth

emfr

omm

akin

gan

yco

pies

ofyo

urco

pyri

ghte

dm

ater

ial

outs

-id

eth

eirr

elat

ions

hip

with

you.

Con

veyi

ngun

der

any

othe

rci

rcum

stan

ces

ispe

rmitt

edso

lely

unde

rth

eco

nditi

ons

stat

edbe

low

.Su

blic

ensi

ngis

not

allo

wed

;se

ctio

n10

mak

esit

unne

cess

ary.

3.Pr

otec

ting

Use

rs’

Leg

alR

ight

sFr

omA

nti-

Cir

cum

vent

ion

Law

.

No

cove

red

wor

ksh

all

bede

-em

edpa

rtof

anef

fect

ive

tech

-no

logi

calm

easu

reun

dera

nyap

-pl

icab

lela

wfu

lfilli

ngob

ligat

i-on

sun

der

artic

le11

ofth

eW

I-

Page 497: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

POco

pyri

ghtt

reat

yad

opte

don

20D

ecem

ber

1996

,or

sim

ilar

law

spr

ohib

iting

orre

stri

ctin

gci

rcum

vent

ion

ofsu

chm

easu

-re

s.

Whe

nyo

uco

nvey

aco

ver-

edw

ork,

you

wai

vean

yle

gal

pow

erto

forb

idci

rcum

vent

ion

ofte

chno

logi

calm

easu

res

toth

eex

tent

such

circ

umve

ntio

nis

ef-

fect

edby

exer

cisi

ngri

ghts

un-

der

this

Lic

ense

with

resp

ect

toth

eco

vere

dw

ork,

and

you

disc

laim

any

inte

ntio

nto

limit

oper

atio

nor

mod

ifica

tion

ofth

ew

ork

asa

mea

nsof

enfo

rcin

g,ag

ains

tth

ew

ork’

sus

ers,

your

orth

ird

part

ies’

lega

lri

ghts

tofo

rbid

circ

umve

ntio

nof

tech

no-

logi

cal

mea

sure

s.4.

Con

veyi

ngV

erba

timC

opie

s.

You

may

conv

eyve

rbat

imco

-pi

esof

the

Prog

ram

’sso

urce

code

asyo

ure

ceiv

eit,

inan

ym

ediu

m,p

rovi

ded

that

you

con-

spic

uous

lyan

dap

prop

riat

ely

pu-

blis

hon

each

copy

anap

prop

ria-

teco

pyri

ght

notic

e;ke

epin

tact

all

notic

esst

atin

gth

atth

isL

i-ce

nse

and

any

non-

perm

issi

vete

rms

adde

din

acco

rdw

ithse

c-tio

n7

appl

yto

the

code

;kee

pin

-

tact

alln

otic

esof

the

abse

nce

ofan

yw

arra

nty;

and

give

allr

ecip

i-en

tsa

copy

ofth

isL

icen

seal

ong

with

the

Prog

ram

.

You

may

char

gean

ypr

ice

orno

pric

efo

reac

hco

pyth

atyo

uco

n-ve

y,an

dyo

um

ayof

fer

supp

ort

orw

arra

nty

prot

ectio

nfo

ra

fee.

5.C

onve

ying

Mod

ified

Sour

ceV

ersi

ons.

You

may

conv

eya

wor

kba

sed

onth

ePr

ogra

m,o

rthe

mod

ifica

-tio

nsto

prod

uce

itfr

omth

ePr

o-gr

am,i

nth

efo

rmof

sour

ceco

deun

dert

hete

rmso

fsec

tion

4,pr

o-vi

ded

that

you

also

mee

tal

lof

thes

eco

nditi

ons:

*a)

The

wor

km

ustc

arry

prom

i-ne

ntno

tices

stat

ing

that

you

mo-

difie

dit,

and

givi

nga

rele

vant

date

.*

b)T

hew

ork

mus

tca

r-ry

prom

inen

tnot

ices

stat

ing

that

itis

rele

ased

unde

rth

isL

icen

-se

and

any

cond

ition

sad

ded

un-

der

sect

ion

7.T

his

requ

irem

ent

mod

ifies

the

requ

irem

enti

nse

c-tio

n4

to“k

eep

inta

ctal

lno

ti-ce

s”.*

c)Y

oum

ust

licen

seth

een

tire

wor

k,as

aw

hole

,un

der

this

Lic

ense

toan

yone

who

co-

mes

into

poss

essi

onof

aco

py.

Thi

sL

icen

sew

illth

eref

ore

ap-

ply,

alon

gw

ithan

yap

plic

able

sect

ion

7ad

ditio

nalt

erm

s,to

the

who

leof

the

wor

k,an

dal

lits

part

s,re

gard

less

ofho

wth

eyar

epa

ckag

ed.T

hisL

icen

segi

vesn

ope

rmis

sion

tolic

ense

the

wor

kin

any

othe

rw

ay,

but

itdo

esno

tin

valid

ate

such

perm

issi

onif

you

have

sepa

rate

lyre

ceiv

edit.

*d)

Ifth

ew

ork

has

inte

rac-

tive

user

inte

rfac

es,

each

mus

tdi

spla

yA

ppro

pria

teL

egal

Not

i-ce

s;ho

wev

er,i

fthe

Prog

ram

has

inte

ract

ive

inte

rfac

esth

atdo

not

disp

lay

App

ropr

iate

Leg

alN

oti-

ces,

your

wor

kne

edno

tm

ake

them

doso

.

Aco

mpi

latio

nof

aco

vere

dw

ork

with

othe

rsep

arat

ean

din

-de

pend

entw

orks

,whi

char

eno

tby

thei

rnat

ure

exte

nsio

nsof

the

cove

red

wor

k,an

dw

hich

are

not

com

bine

dw

ithit

such

asto

form

ala

rger

prog

ram

,in

oron

avo

-lu

me

ofa

stor

age

ordi

stri

butio

nm

ediu

m,

isca

lled

an“a

ggre

ga-

te”

ifth

eco

mpi

latio

nan

dits

re-

sulti

ngco

pyri

ghta

reno

tuse

dto

limit

the

acce

ssor

lega

lrig

htso

fth

eco

mpi

latio

n’s

user

sbe

yond

wha

tth

ein

divi

dual

wor

kspe

r-m

it.In

clus

ion

ofa

cove

red

wor

k

inan

aggr

egat

edo

esno

tca

use

this

Lic

ense

toap

ply

toth

eot

her

part

sof

the

aggr

egat

e.6.

Con

-ve

ying

Non

-Sou

rce

Form

s.

You

may

conv

eya

cove

red

wor

kin

obje

ctco

defo

rmun

-de

rth

ete

rms

ofse

ctio

ns4

and

5,pr

ovid

edth

atyo

ual

soco

n-ve

yth

em

achi

ne-r

eada

ble

Cor

-re

spon

ding

Sour

ceun

der

the

term

sof

this

Lic

ense

,in

one

ofth

ese

way

s:

*a)

Con

vey

the

obje

ctco

dein

,or

embo

died

in,a

phys

ical

pro-

duct

(inc

ludi

nga

phys

ical

dist

ri-

butio

nm

ediu

m),

acco

mpa

nied

byth

eC

orre

spon

ding

Sour

cefi-

xed

ona

dura

ble

phys

ical

me-

dium

cust

omar

ilyus

edfo

rso

ft-

war

ein

terc

hang

e.*

b)C

onve

yth

eob

ject

code

in,o

rem

bodi

edin

,aph

ysic

alpr

oduc

t(in

clud

ing

aph

ysic

aldi

stri

butio

nm

ediu

m),

acco

mpa

nied

bya

wri

tten

of-

fer,

valid

for

atle

astt

hree

year

san

dva

lidfo

ras

long

asyo

uof

-fe

rsp

are

part

sor

cust

omer

sup-

port

for

that

prod

uct

mod

el,

togi

vean

yone

who

poss

esse

sth

eob

ject

code

eith

er(1

)a

copy

ofth

eC

orre

spon

ding

Sour

cefo

ral

lth

eso

ftw

are

inth

epr

oduc

t

Page 498: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

that

isco

vere

dby

this

Lic

ense

,on

adu

rabl

eph

ysic

alm

ediu

mcu

stom

arily

used

for

soft

war

ein

terc

hang

e,fo

ra

pric

eno

mo-

reth

anyo

urre

ason

able

cost

ofph

ysic

ally

perf

orm

ing

this

con-

veyi

ngof

sour

ce,

or(2

)ac

cess

toco

pyth

eC

orre

spon

ding

Sour

-ce

from

ane

twor

kse

rver

atno

char

ge.

*c)

Con

vey

indi

vidu

alco

pies

ofth

eob

ject

code

with

aco

pyof

the

wri

tten

offe

rto

pro-

vide

the

Cor

resp

ondi

ngSo

urce

.T

his

alte

rnat

ive

isal

low

edon

-ly

occa

sion

ally

and

nonc

omm

er-

cial

ly,a

ndon

lyif

you

rece

ived

the

obje

ctco

dew

ithsu

chan

of-

fer,

inac

cord

with

subs

ectio

n6b

.*d)

Con

vey

the

obje

ctco

deby

offe

ring

acce

ssfr

oma

de-

sign

ated

plac

e(g

ratis

orfo

ra

char

ge),

and

offe

requ

ival

enta

c-ce

ssto

the

Cor

resp

ondi

ngSo

ur-

cein

the

sam

ew

ayth

roug

hth

esa

me

plac

eat

nofu

rthe

rch

arge

.Y

oune

edno

tre

quir

ere

cipi

ents

toco

pyth

eC

orre

spon

ding

Sour

-ce

alon

gw

ithth

eob

ject

code

.If

the

plac

eto

copy

the

obje

ctco

deis

ane

twor

kse

rver

,th

eC

orre

spon

ding

Sour

cem

aybe

ona

diff

eren

tse

rver

(ope

rate

dby

you

ora

thir

dpa

rty)

that

sup-

port

seq

uiva

lent

copy

ing

faci

li-

ties,

prov

ided

you

mai

ntai

ncl

e-ar

dire

ctio

nsne

xtto

the

obje

ctco

desa

ying

whe

reto

find

the

Cor

resp

ondi

ngSo

urce

.R

egar

d-le

ssof

wha

tser

verh

osts

the

Cor

-re

spon

ding

Sour

ce,

you

rem

ain

oblig

ated

toen

sure

that

itis

avai

labl

efo

ras

long

asne

eded

tosa

tisfy

thes

ere

quir

emen

ts.

*e)

Con

vey

the

obje

ctco

deus

ing

peer

-to-

peer

tran

smis

sion

,pr

o-vi

ded

you

info

rmot

her

peer

sw

here

the

obje

ctco

dean

dC

orre

-sp

ondi

ngSo

urce

ofth

ew

ork

are

bein

gof

fere

dto

the

gene

ralp

u-bl

icat

noch

arge

unde

rsu

bsec

-tio

n6d

.

Ase

para

ble

port

ion

ofth

eob

-je

ctco

de,

who

seso

urce

code

isex

clud

edfr

omth

eC

orre

spon

-di

ngSo

urce

asa

Syst

emL

ibra

ry,

need

notb

ein

clud

edin

conv

ey-

ing

the

obje

ctco

dew

ork.

A“U

ser

Prod

uct”

isei

ther

(1)

a“c

onsu

mer

prod

uct”

,whi

chm

e-an

san

yta

ngib

lepe

rson

alpr

o-pe

rty

whi

chis

norm

ally

used

for

pers

onal

,fa

mily

,or

hous

ehol

dpu

rpos

es,

or(2

)an

ythi

ngde

si-

gned

orso

ldfo

rin

corp

orat

ion

into

adw

ellin

g.In

dete

rmin

ing

whe

ther

apr

oduc

tis

aco

nsum

er

prod

uct,

doub

tful

case

ssh

allb

ere

solv

edin

favo

rof

cove

rage

.Fo

ra

part

icul

arpr

oduc

tre

cei-

ved

bya

part

icul

arus

er,

“nor

-m

ally

used

”re

fers

toa

typi

cal

orco

mm

onus

eof

that

clas

sof

prod

uct,

rega

rdle

ssof

the

stat

usof

the

part

icul

arus

eror

ofth

ew

ayin

whi

chth

epa

rtic

ular

user

actu

ally

uses

,or

expe

cts

oris

expe

cted

tous

e,th

epr

oduc

t.A

prod

uct

isa

cons

umer

prod

uct

rega

rdle

ssof

whe

ther

the

pro-

duct

hass

ubst

antia

lcom

mer

cial

,in

dust

rial

orno

n-co

nsum

erus

es,

unle

sssu

chus

esre

pres

ent

the

only

sign

ifica

ntm

ode

ofus

eof

the

prod

uct.

“Ins

talla

tion

Info

rmat

ion”

for

aU

ser

Prod

uct

mea

nsan

ym

e-th

ods,

proc

edur

es,a

utho

riza

tion

keys

,oro

ther

info

rmat

ion

requ

i-re

dto

inst

alla

ndex

ecut

em

odi-

fied

vers

ions

ofa

cove

red

wor

kin

that

Use

rPr

oduc

tfr

oma

mod

ified

vers

ion

ofits

Cor

re-

spon

ding

Sour

ce.

The

info

rma-

tion

mus

tsu

ffice

toen

sure

that

the

cont

inue

dfu

nctio

ning

ofth

em

odifi

edob

ject

code

isin

noca

-se

prev

ente

dor

inte

rfer

edw

ithso

lely

beca

use

mod

ifica

tion

has

been

mad

e.

Ifyo

uco

nvey

anob

ject

code

wor

kun

der

this

sect

ion

in,

orw

ith,

orsp

ecifi

cally

for

use

in,

aU

ser

Prod

uct,

and

the

conv

ey-

ing

occu

rsas

part

ofa

tran

sac-

tion

inw

hich

the

righ

tofp

osse

s-si

onan

dus

eof

the

Use

rPro

duct

istr

ansf

erre

dto

the

reci

pien

tin

perp

etui

tyor

fora

fixed

term

(re-

gard

less

ofho

wth

etr

ansa

ctio

nis

char

acte

rize

d),t

heC

orre

spon

-di

ngSo

urce

conv

eyed

unde

rthi

sse

ctio

nm

ustb

eac

com

pani

edby

the

Inst

alla

tion

Info

rmat

ion.

But

this

requ

irem

entd

oes

nota

pply

ifne

ither

you

nora

nyth

ird

part

yre

tain

sth

eab

ility

toin

stal

lm

o-di

fied

obje

ctco

deon

the

Use

rPr

oduc

t(f

orex

ampl

e,th

ew

ork

has

been

inst

alle

din

RO

M).

The

requ

irem

ent

topr

ovid

eIn

-st

alla

tion

Info

rmat

ion

does

not

incl

ude

are

quir

emen

tto

cont

i-nu

eto

prov

ide

supp

ort

serv

ice,

war

rant

y,or

upda

tes

for

aw

ork

that

has

been

mod

ified

orin

stal

-le

dby

the

reci

pien

t,or

for

the

Use

rPr

oduc

tin

whi

chit

has

been

mod

ified

orin

stal

led.

Ac-

cess

toa

netw

ork

may

bede

nied

whe

nth

em

odifi

catio

nits

elfm

a-te

rial

lyan

dad

vers

ely

affe

ctst

heop

erat

ion

ofth

ene

twor

kor

vio-

Page 499: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

late

sth

eru

les

and

prot

ocol

sfo

rco

mm

unic

atio

nac

ross

the

net-

wor

k.

Cor

resp

ondi

ngSo

urce

conv

ey-

ed,

and

Inst

alla

tion

Info

rmat

i-on

prov

ided

,in

acco

rdw

ithth

isse

ctio

nm

ust

bein

afo

r-m

atth

atis

publ

icly

docu

men

-te

d(a

ndw

ithan

impl

emen

tatio

nav

aila

ble

toth

epu

blic

inso

urce

code

form

),an

dm

ustr

equi

reno

spec

ial

pass

wor

dor

key

for

un-

pack

ing,

read

ing

orco

pyin

g.7.

Add

ition

alTe

rms.

“Add

ition

alpe

rmis

sion

s”ar

ete

rms

that

supp

lem

entt

hete

rms

ofth

isL

icen

seby

mak

ing

exce

ptio

nsfr

omon

eor

mor

eof

itsco

nditi

ons.

Add

ition

alpe

rmis

sion

sth

atar

eap

plic

able

toth

een

tire

Prog

ram

shal

lbe

trea

ted

asth

ough

they

wer

ein

clud

edin

this

Lic

ense

,to

the

exte

ntth

atth

eyar

eva

lidun

der

appl

icab

lela

w.

Ifad

ditio

nal

perm

issi

ons

appl

yon

lyto

part

ofth

ePr

ogra

m,

that

part

may

beus

edse

para

tely

unde

rth

ose

perm

issi

ons,

but

the

entir

ePr

ogra

mre

mai

nsgo

vern

edby

this

Lic

ense

with

out

rega

rdto

the

addi

tiona

lper

mis

sion

s.

Whe

nyo

uco

nvey

aco

pyof

aco

-ve

red

wor

k,yo

um

ayat

your

op-

tion

rem

ove

any

addi

tiona

lpe

r-m

issi

onsf

rom

that

copy

,orf

rom

any

part

ofit.

(Add

ition

alpe

r-m

issi

ons

may

bew

ritte

nto

re-

quir

eth

eir

own

rem

oval

ince

r-ta

inca

ses

whe

nyo

um

odif

yth

ew

ork.

)You

may

plac

ead

ditio

nal

perm

issi

ons

onm

ater

ial,

adde

dby

you

toa

cove

red

wor

k,fo

rw

hich

you

have

orca

ngi

veap

-pr

opri

ate

copy

righ

tper

mis

sion

.

Not

with

stan

ding

any

othe

rpr

o-vi

sion

ofth

isL

icen

se,f

orm

ate-

rial

you

add

toa

cove

red

wor

k,yo

um

ay(i

fau

thor

ized

byth

eco

pyri

ghth

olde

rsof

that

mat

eri-

al)

supp

lem

entt

hete

rms

ofth

isL

icen

sew

ithte

rms:

*a)

Dis

clai

min

gw

arra

nty

orli-

miti

nglia

bilit

ydi

ffer

ently

from

the

term

sof

sect

ions

15an

d16

ofth

isL

icen

se;

or*

b)R

equi

-ri

ngpr

eser

vatio

nof

spec

ified

re-

ason

able

lega

lnot

ices

orau

thor

attr

ibut

ions

inth

atm

ater

ial

orin

the

App

ropr

iate

Leg

alN

oti-

ces

disp

laye

dby

wor

ksco

ntai

-ni

ngit;

or*

c)Pr

ohib

iting

mis

re-

pres

enta

tion

ofth

eor

igin

ofth

atm

ater

ial,

orre

quir

ing

that

mod

i-

fied

vers

ions

ofsu

chm

ater

ialb

em

arke

din

reas

onab

lew

ays

asdi

ffer

entf

rom

the

orig

inal

vers

i-on

;or

*d)

Lim

iting

the

use

for

publ

icity

purp

oses

ofna

mes

oflic

enso

rsor

auth

ors

ofth

em

ate-

rial

;or

*e)

Dec

linin

gto

gran

tri

ghts

unde

rtr

adem

ark

law

for

use

ofso

me

trad

ena

mes

,tra

de-

mar

ks,o

rse

rvic

em

arks

;or

*f)

Req

uiri

ngin

dem

nific

atio

nof

li-ce

nsor

san

dau

thor

sof

that

ma-

teri

alby

anyo

new

hoco

nvey

sth

em

ater

ial

(or

mod

ified

vers

i-on

sof

it)w

ithco

ntra

ctua

las

-su

mpt

ions

oflia

bilit

yto

the

reci

-pi

ent,

fora

nylia

bilit

yth

atth

ese

cont

ract

uala

ssum

ptio

nsdi

rect

lyim

pose

onth

ose

licen

sors

and

auth

ors.

All

othe

rno

n-pe

rmis

sive

ad-

ditio

nal

term

sar

eco

nsid

ered

“fur

ther

rest

rict

ions

”w

ithin

the

mea

ning

ofse

ctio

n10

.If

the

Prog

ram

asyo

ure

ceiv

edit,

oran

ypa

rtof

it,co

ntai

nsa

notic

est

atin

gth

atit

isgo

vern

edby

this

Lic

ense

alon

gw

itha

term

that

isa

furt

her

rest

rict

ion,

you

may

rem

ove

that

term

.If

alic

ense

docu

men

tco

ntai

nsa

furt

her

re-

stri

ctio

nbu

tper

mits

relic

ensi

ngor

conv

eyin

gun

der

this

Lic

en-

se,

you

may

add

toa

cove

red

wor

km

ater

ial

gove

rned

byth

ete

rms

ofth

atlic

ense

docu

men

t,pr

ovid

edth

atth

efu

rthe

rre

stri

c-tio

ndo

esno

tsu

rviv

esu

chre

li-ce

nsin

gor

conv

eyin

g.

Ifyo

uad

dte

rms

toa

cove

red

wor

kin

acco

rdw

ithth

isse

ctio

n,yo

um

ust

plac

e,in

the

rele

vant

sour

cefil

es,

ast

atem

ent

ofth

ead

ditio

nal

term

sth

atap

ply

toth

ose

files

,or

ano

tice

indi

ca-

ting

whe

reto

find

the

appl

icab

lete

rms.

Add

ition

alte

rms,

perm

issi

veor

non-

perm

issi

ve,

may

best

ated

inth

efo

rmof

ase

para

tely

wri

t-te

nlic

ense

,or

stat

edas

exce

pti-

ons;

the

abov

ere

quir

emen

tsap

-pl

yei

ther

way

.8.T

erm

inat

ion.

You

may

notp

ropa

gate

orm

odi-

fya

cove

red

wor

kex

cept

asex

-pr

essl

ypr

ovid

edun

der

this

Li-

cens

e.A

nyat

tem

ptot

herw

ise

topr

opag

ate

orm

odif

yit

isvo

id,

and

will

auto

mat

ical

lyte

rmin

a-te

your

righ

tsun

der

this

Lic

en-

se(i

nclu

ding

any

pate

ntlic

en-

ses

gran

ted

unde

rthe

thir

dpa

ra-

grap

hof

sect

ion

11).

Page 500: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

How

ever

,if

you

ceas

eal

lvio

la-

tion

ofth

isL

icen

se,

then

your

licen

sefr

oma

part

icul

arco

py-

righ

thol

deri

sre

inst

ated

(a)p

ro-

visi

onal

ly,

unle

ssan

dun

tilth

eco

pyri

ght

hold

erex

plic

itly

and

final

lyte

rmin

ates

your

licen

se,

and

(b)p

erm

anen

tly,i

fthe

copy

-ri

ght

hold

erfa

ilsto

notif

yyo

uof

the

viol

atio

nby

som

ere

a-so

nabl

em

eans

prio

rto

60da

ysaf

tert

hece

ssat

ion.

Mor

eove

r,yo

urlic

ense

from

apa

rtic

ular

copy

righ

thol

deri

sre

-in

stat

edpe

rman

ently

ifth

eco

py-

righ

tho

lder

notifi

esyo

uof

the

viol

atio

nby

som

ere

ason

able

mea

ns,t

his

isth

efir

sttim

eyo

uha

vere

ceiv

edno

tice

ofvi

olat

i-on

ofth

isL

icen

se(f

oran

yw

ork)

from

that

copy

righ

tho

lder

,and

you

cure

the

viol

atio

npr

ior

to30

days

afte

ryou

rrec

eipt

ofth

eno

tice.

Term

inat

ion

ofyo

urri

ghts

un-

der

this

sect

ion

does

not

term

i-na

teth

elic

ense

sof

part

ies

who

have

rece

ived

copi

esor

righ

tsfr

omyo

uun

der

this

Lic

ense

.If

your

righ

tsha

vebe

ente

rmin

a-te

dan

dno

tpe

rman

ently

rein

s-ta

ted,

you

dono

tqu

alif

yto

re-

ceiv

ene

wlic

ense

sfo

rth

esa

me

mat

eria

lund

erse

ctio

n10

.9.A

c-ce

ptan

ceN

otR

equi

red

for

Ha-

ving

Cop

ies.

You

are

not

requ

ired

toac

cept

this

Lic

ense

inor

der

tore

ceiv

eor

run

aco

pyof

the

Prog

ram

.A

ncill

ary

prop

agat

ion

ofa

co-

vere

dw

ork

occu

rrin

gso

lely

asa

cons

eque

nce

ofus

ing

peer

-to-

peer

tran

smis

sion

tore

ceiv

ea

copy

likew

ise

does

not

requ

ire

acce

ptan

ce.

How

ever

,no

thin

got

her

than

this

Lic

ense

gran

tsyo

upe

rmis

sion

topr

opag

ate

orm

odif

yan

yco

vere

dw

ork.

The

-se

actio

nsin

frin

geco

pyri

ght

ifyo

udo

not

acce

ptth

isL

icen

se.

The

refo

re,b

ym

odif

ying

orpr

o-pa

gatin

ga

cove

red

wor

k,yo

uin

-di

cate

your

acce

ptan

ceof

this

Lic

ense

todo

so.1

0.A

utom

atic

Lic

ensi

ngof

Dow

nstr

eam

Rec

i-pi

ents

.

Eac

htim

eyo

uco

nvey

aco

ver-

edw

ork,

the

reci

pien

taut

omat

i-ca

llyre

ceiv

esa

licen

sefr

omth

eor

igin

allic

enso

rs,t

oru

n,m

odi-

fyan

dpr

opag

ate

that

wor

k,su

b-je

ctto

this

Lic

ense

.You

are

not

resp

onsi

ble

for

enfo

rcin

gco

mp-

lianc

eby

thir

dpa

rtie

sw

ithth

isL

icen

se.

An

“ent

itytr

ansa

ctio

n”is

atr

an-

sact

ion

tran

sfer

ring

cont

rol

ofan

orga

niza

tion,

orsu

bsta

ntia

l-ly

all

asse

tsof

one,

orsu

bdi-

vidi

ngan

orga

niza

tion,

orm

er-

ging

orga

niza

tions

.If

prop

aga-

tion

ofa

cove

red

wor

kre

sults

from

anen

tity

tran

sact

ion,

each

part

yto

that

tran

sact

ion

who

re-

ceiv

esa

copy

ofth

ew

ork

also

rece

ives

wha

teve

rlic

ense

sto

the

wor

kth

epa

rty’

spr

edec

esso

rin

inte

rest

had

orco

uld

give

unde

rth

epr

evio

uspa

ragr

aph,

plus

ari

ght

topo

sses

sion

ofth

eC

or-

resp

ondi

ngSo

urce

ofth

ew

ork

from

the

pred

eces

sori

nin

tere

st,

ifth

epr

edec

esso

rha

sit

orca

nge

titw

ithre

ason

able

effo

rts.

You

may

not

impo

sean

yfu

r-th

erre

stri

ctio

nson

the

exer

cise

ofth

eri

ghts

gran

ted

oraf

firm

edun

der

this

Lic

ense

.Fo

rex

amp-

le,y

oum

ayno

tim

pose

alic

en-

sefe

e,ro

yalty

,or

othe

rch

arge

fore

xerc

ise

ofri

ghts

gran

ted

un-

der

this

Lic

ense

,an

dyo

um

ayno

tin

itiat

elit

igat

ion

(inc

ludi

nga

cros

s-cl

aim

orco

unte

rcla

imin

ala

wsu

it)al

legi

ngth

atan

ypa

-

tent

clai

mis

infr

inge

dby

ma-

king

,usi

ng,s

ellin

g,of

feri

ngfo

rsa

le,

orim

port

ing

the

Prog

ram

oran

ypo

rtio

nof

it.11

.Pat

ents

.

A“c

ontr

ibut

or”

isa

copy

righ

tho

lder

who

auth

oriz

esus

eun

der

this

Lic

ense

ofth

ePr

ogra

mor

aw

ork

onw

hich

the

Prog

ram

isba

sed.

The

wor

kth

uslic

ense

dis

calle

dth

eco

ntri

buto

r’s

“con

tri-

buto

rver

sion

”.

Aco

ntri

buto

r’s

“ess

entia

lpat

ent

clai

ms”

are

allp

aten

tcla

ims

ow-

ned

orco

ntro

lled

byth

eco

nt-

ribu

tor,

whe

ther

alre

ady

acqu

i-re

dor

here

afte

rac

quir

ed,

that

wou

ldbe

infr

inge

dby

som

em

anne

r,pe

rmitt

edby

this

Lic

en-

se,o

fm

akin

g,us

ing,

orse

lling

itsco

ntri

buto

rve

rsio

n,bu

tdo

not

incl

ude

clai

ms

that

wou

ldbe

infr

inge

don

lyas

aco

nse-

quen

ceof

furt

her

mod

ifica

tion

ofth

eco

ntri

buto

rve

rsio

n.Fo

rpu

rpos

esof

this

defin

ition

,“co

n-tr

ol”

incl

udes

the

righ

tto

gran

tpa

tent

subl

icen

ses

ina

man

ner

cons

iste

ntw

ithth

ere

quir

emen

tsof

this

Lic

ense

.

Eac

hco

ntri

buto

rgr

ants

you

ano

n-ex

clus

ive,

wor

ldw

ide,

Page 501: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

roya

lty-f

ree

pate

ntlic

ense

un-

der

the

cont

ribu

tor’

ses

sent

ial

pate

ntcl

aim

s,to

mak

e,us

e,se

ll,of

fer

for

sale

,im

port

and

othe

r-w

ise

run,

mod

ify

and

prop

agat

eth

eco

nten

tsof

itsco

ntri

buto

rve

rsio

n.

Inth

efo

llow

ing

thre

epa

ra-

grap

hs,

a“p

aten

tlic

ense

”is

any

expr

ess

agre

emen

tor

com

-m

itmen

t,ho

wev

erde

nom

inat

ed,

nott

oen

forc

ea

pate

nt(s

uch

asan

expr

ess

perm

issi

onto

prac

-tic

ea

pate

ntor

cove

nant

not

tosu

efo

rpa

tent

infr

inge

men

t).T

o“g

rant

”su

cha

pate

ntlic

ense

toa

part

ym

eans

tom

ake

such

anag

reem

ent

orco

mm

itmen

tno

tto

enfo

rce

apa

tent

agai

nst

the

part

y.

Ifyo

uco

nvey

aco

vere

dw

ork,

know

ingl

yre

lyin

gon

apa

tent

licen

se,

and

the

Cor

resp

ondi

ngSo

urce

ofth

ew

ork

isno

tava

il-ab

lefo

ran

yone

toco

py,

free

ofch

arge

and

unde

rth

ete

rms

ofth

isL

icen

se,

thro

ugh

apu

-bl

icly

avai

labl

ene

twor

kse

rver

orot

her

read

ilyac

cess

ible

me-

ans,

then

you

mus

tei

ther

(1)

caus

eth

eC

orre

spon

ding

Sour

-ce

tobe

soav

aila

ble,

or(2

)ar

-

rang

eto

depr

ive

your

self

ofth

ebe

nefit

ofth

epa

tent

licen

sefo

rth

ispa

rtic

ular

wor

k,or

(3)a

rran

-ge

,in

am

anne

rco

nsis

tent

with

the

requ

irem

ents

ofth

isL

icen

-se

,to

exte

ndth

epa

tent

licen

seto

dow

nstr

eam

reci

pien

ts.“

Kno

-w

ingl

yre

lyin

g”m

eans

you

ha-

veac

tual

know

ledg

eth

at,b

utfo

rth

epa

tent

licen

se,y

our

conv

ey-

ing

the

cove

red

wor

kin

aco

un-

try,

oryo

urre

cipi

ent’s

use

ofth

eco

vere

dw

ork

ina

coun

try,

wou

ldin

frin

geon

eor

mor

eid

en-

tifiab

lepa

tent

sin

that

coun

try

that

you

have

reas

onto

belie

vear

eva

lid.

If,p

ursu

ant

toor

inco

nnec

tion

with

asi

ngle

tran

sact

ion

orar

-ra

ngem

ent,

you

conv

ey,

orpr

o-pa

gate

bypr

ocur

ing

conv

eyan

ceof

,aco

vere

dw

ork,

and

gran

tapa

tent

licen

seto

som

eof

the

par-

ties

rece

ivin

gth

eco

vere

dw

ork

auth

oriz

ing

them

tous

e,pr

opa-

gate

,m

odif

yor

conv

eya

spe-

cific

copy

ofth

eco

vere

dw

ork,

then

the

pate

ntlic

ense

you

gran

tis

auto

mat

ical

lyex

tend

edto

all

reci

pien

tsof

the

cove

red

wor

kan

dw

orks

base

don

it.

Apa

tent

licen

seis

“dis

crim

ina-

tory

”if

itdo

esno

tin

clud

ew

i-th

inth

esc

ope

ofits

cove

rage

,pr

ohib

itsth

eex

erci

seof

,or

isco

nditi

oned

onth

eno

n-ex

erci

seof

one

orm

ore

ofth

eri

ghts

that

are

spec

ifica

llygr

ante

dun

der

this

Lic

ense

.Y

oum

ayno

tco

n-ve

ya

cove

red

wor

kif

you

are

apa

rty

toan

arra

ngem

ent

with

ath

ird

part

yth

atis

inth

ebu

sine

ssof

dist

ribu

ting

soft

war

e,un

der

whi

chyo

um

ake

paym

entt

oth

eth

ird

part

yba

sed

onth

eex

tent

ofyo

urac

tivity

ofco

nvey

ing

the

wor

k,an

dun

derw

hich

the

thir

dpa

rty

gran

ts,

toan

yof

the

par-

ties

who

wou

ldre

ceiv

eth

eco

-ve

red

wor

kfr

omyo

u,a

disc

rim

i-na

tory

pate

ntlic

ense

(a)

inco

n-ne

ctio

nw

ithco

pies

ofth

eco

-ve

red

wor

kco

nvey

edby

you

(or

copi

esm

ade

from

thos

eco

pies

),or

(b)

prim

arily

for

and

inco

n-ne

ctio

nw

ithsp

ecifi

cpr

oduc

tsor

com

pila

tions

that

cont

ain

the

co-

vere

dw

ork,

unle

ssyo

uen

tere

din

toth

atar

rang

emen

t,or

that

pa-

tent

licen

sew

asgr

ante

d,pr

iort

o28

Mar

ch20

07.

Not

hing

inth

isL

icen

sesh

all

beco

nstr

ued

asex

clud

ing

orli-

miti

ngan

yim

plie

dlic

ense

or

othe

rde

fens

esto

infr

inge

men

tth

atm

ayot

herw

ise

beav

aila

ble

toyo

uun

der

appl

icab

lepa

tent

law

.12.

No

Surr

ende

rofO

ther

s’Fr

eedo

m.

Ifco

nditi

ons

are

impo

sed

onyo

u(w

heth

erby

cour

tor

der,

agre

emen

tor

othe

rwis

e)th

atco

ntra

dict

the

cond

ition

sof

this

Lic

ense

,the

ydo

note

xcus

eyo

ufr

omth

eco

nditi

ons

ofth

isL

i-ce

nse.

Ifyo

uca

nnot

conv

eya

cove

red

wor

kso

asto

satis

fysi

mul

tane

ousl

yyo

urob

ligat

ions

unde

rthi

sLic

ense

and

any

othe

rpe

rtin

ent

oblig

atio

ns,

then

asa

cons

eque

nce

you

may

not

con-

vey

itat

all.

For

exam

ple,

ifyo

uag

ree

tote

rms

that

oblig

a-te

you

toco

llect

aro

yalty

for

furt

her

conv

eyin

gfr

omth

ose

tow

hom

you

conv

eyth

ePr

ogra

m,

the

only

way

you

coul

dsa

tisfy

both

thos

ete

rms

and

this

Lic

en-

sew

ould

beto

refr

ain

entir

ely

from

conv

eyin

gth

ePr

ogra

m.1

3.U

sew

ithth

eG

NU

Aff

ero

Gen

e-ra

lPub

licL

icen

se.

Not

with

stan

ding

any

othe

rpr

o-vi

sion

ofth

isL

icen

se,

you

ha-

vepe

rmis

sion

tolin

kor

com

-bi

nean

yco

vere

dw

ork

with

a

Page 502: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

wor

klic

ense

dun

der

vers

ion

3of

the

GN

UA

ffer

oG

ener

alPu

-bl

icL

icen

sein

toa

sing

leco

mbi

-ne

dw

ork,

and

toco

nvey

the

re-

sulti

ngw

ork.

The

term

sof

this

Lic

ense

will

cont

inue

toap

ply

toth

epa

rtw

hich

isth

eco

ver-

edw

ork,

but

the

spec

ial

requ

i-re

men

tsof

the

GN

UA

ffer

oG

e-ne

ralP

ublic

Lic

ense

,sec

tion

13,

conc

erni

ngin

tera

ctio

nth

roug

ha

netw

ork

will

appl

yto

the

com

-bi

natio

nas

such

.14

.R

evis

edV

ersi

ons

ofth

isL

icen

se.

The

Free

Soft

war

eFo

unda

tion

may

publ

ish

revi

sed

and/

orne

wve

rsio

nsof

the

GN

UG

ener

alPu

blic

Lic

ense

from

time

totim

e.Su

chne

wve

rsio

nsw

illbe

sim

ilar

insp

irit

toth

epr

esen

tve

rsio

n,bu

tmay

diff

erin

deta

ilto

addr

ess

new

prob

lem

sor

con-

cern

s.

Eac

hve

rsio

nis

give

na

dist

in-

guis

hing

vers

ion

num

ber.

Ifth

ePr

ogra

msp

ecifi

esth

ata

cert

ain

num

bere

dve

rsio

nof

the

GN

UG

ener

alPu

blic

Lic

ense

“or

any

late

rve

rsio

n”ap

plie

sto

it,yo

uha

veth

eop

tion

offo

llow

ing

the

term

san

dco

nditi

ons

eith

erof

that

num

bere

dve

rsio

nor

ofan

y

late

rve

rsio

npu

blis

hed

byth

eFr

eeSo

ftw

are

Foun

datio

n.If

the

Prog

ram

does

not

spec

ify

ave

rsio

nnu

mbe

roft

heG

NU

Ge-

nera

lPu

blic

Lic

ense

,yo

um

aych

oose

any

vers

ion

ever

publ

is-

hed

byth

eFr

eeSo

ftw

are

Foun

-da

tion.

Ifth

ePr

ogra

msp

ecifi

esth

ata

prox

yca

nde

cide

whi

chfu

ture

vers

ions

ofth

eG

NU

Gen

eral

Publ

icL

icen

seca

nbe

used

,tha

tpr

oxy’

spu

blic

stat

emen

tof

ac-

cept

ance

ofa

vers

ion

perm

an-

ently

auth

oriz

esyo

uto

choo

seth

atve

rsio

nfo

rthe

Prog

ram

.

Lat

erlic

ense

vers

ions

may

give

you

addi

tiona

lor

diff

eren

tpe

r-m

issi

ons.

How

ever

,no

addi

tio-

nal

oblig

atio

nsar

eim

pose

don

any

auth

oror

copy

righ

tho

lder

asa

resu

ltof

your

choo

sing

tofo

llow

ala

ter

vers

ion.

15.

Dis

-cl

aim

erof

War

rant

y.

TH

ER

EIS

NO

WA

RR

AN

TY

FOR

TH

EPR

OG

RA

M,

TOT

HE

EX

TE

NT

PER

MIT

TE

DB

YA

PPL

ICA

BL

EL

AW

.E

X-

CE

PTW

HE

NO

TH

ER

WIS

EST

AT

ED

INW

RIT

ING

TH

EC

OPY

RIG

HT

HO

LD

ER

S

AN

D/O

RO

TH

ER

PAR

TIE

SPR

OV

IDE

TH

EPR

OG

RA

M“A

SIS

”W

ITH

OU

TW

AR

-R

AN

TY

OF

AN

YK

IND

,E

ITH

ER

EX

PRE

SSE

DO

RIM

PLIE

D,

INC

LU

DIN

G,

BU

TN

OT

LIM

ITE

DTO

,T

HE

IMPL

IED

WA

RR

AN

TIE

SO

FM

ER

CH

AN

TAB

ILIT

YA

ND

FIT

NE

SSFO

RA

PAR

-T

ICU

LA

RPU

RPO

SE.

TH

EE

NT

IRE

RIS

KA

STO

TH

EQ

UA

LIT

YA

ND

PER

FOR

-M

AN

CE

OF

TH

EPR

OG

RA

MIS

WIT

HY

OU

.SH

OU

LD

TH

EPR

OG

RA

MPR

OV

ED

EFE

C-

TIV

E,

YO

UA

SSU

ME

TH

EC

OST

OF

AL

LN

EC

ESS

ARY

SERV

ICIN

G,

RE

PAIR

OR

CO

RR

EC

TIO

N.1

6.L

imita

tion

ofL

iabi

lity.

INN

OE

VE

NT

UN

LE

SSR

EQ

UIR

ED

BY

APP

LIC

A-

BL

EL

AW

OR

AG

RE

ED

TOIN

WR

ITIN

GW

ILL

AN

YC

OPY

RIG

HT

HO

LD

ER

,O

RA

NY

OT

HE

RPA

RT

YW

HO

MO

DIF

IES

AN

D/O

RC

ON

VE

YS

TH

EPR

OG

RA

MA

SPE

RM

ITT

ED

AB

OV

E,

BE

LIA

BL

ETO

YO

UFO

RD

AM

AG

ES,

INC

LU

DIN

GA

NY

GE

NE

RA

L,

SPE

CIA

L,

INC

IDE

NTA

LO

RC

ON

-SE

QU

EN

TIA

LD

AM

AG

ES

AR

ISIN

GO

UT

OF

TH

EU

SEO

RIN

AB

ILIT

YTO

USE

TH

EPR

OG

RA

M(I

NC

LU

DIN

GB

UT

NO

TL

IMIT

ED

TOL

OSS

OF

DA

TAO

RD

ATA

BE

ING

RE

ND

ER

ED

INA

CC

UR

AT

EO

RL

OSS

ES

SUST

AIN

ED

BY

YO

UO

RT

HIR

DPA

RT

IES

OR

AFA

ILU

RE

OF

TH

EPR

O-

GR

AM

TOO

PER

AT

EW

ITH

AN

YO

TH

ER

PRO

GR

AM

S),

EV

EN

IFSU

CH

HO

LD

ER

OR

OT

HE

RPA

RT

YH

AS

BE

EN

AD

VIS

ED

OF

TH

EPO

SSIB

I-L

ITY

OF

SUC

HD

AM

AG

ES.

17.I

nter

pret

atio

nof

Sect

ions

15an

d16

.

Ifth

edi

scla

imer

ofw

arra

nty

and

limita

tion

oflia

bilit

ypr

ovi-

ded

abov

eca

nnot

begi

ven

loca

lle

gal

effe

ctac

cord

ing

toth

eir

term

s,re

view

ing

cour

tssh

alla

p-pl

ylo

cal

law

that

mos

tcl

ose-

lyap

prox

imat

esan

abso

lute

wai

-ve

rof

all

civi

llia

bilit

yin

con-

nect

ion

with

the

Prog

ram

,un

-le

ssa

war

rant

yor

assu

mpt

ion

oflia

bilit

yac

com

pani

esa

copy

ofth

ePr

ogra

min

retu

rnfo

rafe

e.

Page 503: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

EN

DO

FT

ER

MS

AN

DC

ON

-D

ITIO

NS

How

toA

pply

The

seTe

rms

toY

ourN

ewPr

ogra

ms

Ifyo

ude

velo

pa

new

prog

ram

,an

dyo

uw

ant

itto

beof

the

grea

test

poss

ible

use

toth

epu

-bl

ic,

the

best

way

toac

hiev

eth

isis

tom

ake

itfr

eeso

ftw

are

whi

chev

eryo

neca

nre

dist

ribu

tean

dch

ange

unde

rthe

sete

rms.

Todo

so,

atta

chth

efo

llow

ing

notic

esto

the

prog

ram

.It

issa

fest

toat

tach

them

toth

est

art

ofea

chso

urce

file

tom

oste

ffec

-tiv

ely

stat

eth

eex

clus

ion

ofw

ar-

rant

y;an

dea

chfil

esh

ould

have

atle

astt

he“c

opyr

ight

”lin

ean

da

poin

tert

ow

here

the

full

notic

eis

foun

d.

<one

line

togi

veth

epr

ogra

m’s

nam

ean

da

brie

fid

eaof

wha

tit

does

.>C

opyr

ight

(C)

<yea

r><n

ame

ofau

thor

>

Thi

spr

ogra

mis

free

soft

war

e:yo

uca

nre

dist

ribu

teit

and/

orm

odif

yit

unde

rthe

term

sof

the

GN

UG

ener

alPu

blic

Lic

ense

aspu

blis

hed

byth

eFr

eeSo

ftw

are

Foun

datio

n,ei

ther

vers

ion

3of

the

Lic

ense

,or

(at

your

optio

n)an

yla

terv

ersi

on.

Thi

spr

ogra

mis

dist

ribu

ted

inth

eho

peth

atit

will

beus

e-fu

l,bu

tWIT

HO

UT

AN

YW

AR

-R

AN

TY

;w

ithou

tev

enth

eim

-pl

ied

war

rant

yof

ME

RC

HA

N-

TAB

ILIT

Yor

FIT

NE

SSFO

RA

PAR

TIC

UL

AR

PUR

POSE

.See

the

GN

UG

ener

alPu

blic

Lic

en-

sefo

rmor

ede

tails

.

You

shou

ldha

vere

ceiv

eda

copy

ofth

eG

NU

Gen

eral

Publ

icL

icen

seal

ong

with

this

prog

ram

.If

not,

see

<http

://w

ww

.gnu

.org

/lice

nses

/>.

Als

oad

din

form

atio

non

how

toco

ntac

tyo

uby

elec

tron

ican

dpa

perm

ail.

Ifth

epr

ogra

mdo

este

rmin

alin

-te

ract

ion,

mak

eit

outp

uta

shor

tno

tice

like

this

whe

nit

star

tsin

anin

tera

ctiv

em

ode:

<pro

gram

>C

opyr

ight

(C)

<yea

r><n

ame

ofau

thor

>T

his

prog

ram

com

esw

ithA

BSO

-L

UT

ELY

NO

WA

RR

AN

TY

;fo

rde

tails

type

‘sho

ww

’.T

his

isfr

eeso

ftw

are,

and

you

are

wel

com

eto

redi

stri

bute

itun

der

cert

ain

cond

ition

s;ty

pe‘s

how

c’fo

rdet

ails

.

The

hypo

thet

ical

com

man

ds‘s

how

w’

and

‘sho

wc’

shou

ldsh

owth

eap

prop

riat

epa

rts

ofth

eG

ener

alPu

blic

Lic

ense

.O

fco

urse

,yo

urpr

ogra

m’s

com

-m

ands

mig

htbe

diff

eren

t;fo

ra

GU

Iin

terf

ace,

you

wou

ldus

ean

“abo

utbo

x”.

You

shou

ldal

soge

tyo

urem

-pl

oyer

(if

you

wor

kas

apr

o-gr

amm

er)

orsc

hool

,if

any,

tosi

gna

“cop

yrig

htdi

scla

i-m

er”

for

the

prog

ram

,if

ne-

cess

ary.

For

mor

ein

form

ati-

onon

this

,an

dho

wto

appl

yan

dfo

llow

the

GN

UG

PL,

see

<http

://w

ww

.gnu

.org

/lice

nses

/>.

The

GN

UG

ener

alPu

blic

Lic

en-

sedo

esno

tper

mit

inco

rpor

atin

gyo

urpr

ogra

min

topr

opri

etar

ypr

ogra

ms.

Ifyo

urpr

ogra

mis

asu

brou

tine

libra

ry,

you

may

cons

ider

itm

ore

usef

ulto

perm

itlin

king

prop

riet

ary

appl

icat

ions

with

the

libra

ry.

Ifth

isis

wha

tyo

uw

ant

todo

,us

eth

eG

NU

Les

ser

Gen

eral

Publ

icL

icen

sein

stea

dof

this

Lic

ense

.B

utfir

st,

plea

sere

ad<h

ttp://

ww

w.g

nu.o

rg/p

hilo

soph

y/w

hy-

not-

lgpl

.htm

l>.

22.2

GN

UFr

eeD

ocum

enta

tion

Lic

ense

Page 504: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

Ver

sion

1.3,

3N

ovem

ber2

008

Cop

yrig

ht©

2000

,200

1,20

02,

2007

,200

8Fr

eeSo

ftw

are

Foun

-da

tion,

Inc.

<http

://fs

f.org

/>

Eve

ryon

eis

perm

itted

toco

pyan

ddi

stri

bute

verb

atim

copi

esof

this

licen

sedo

cum

ent,

but

chan

ging

itis

not

allo

wed

.0.

PRE

AM

BL

E

The

purp

ose

ofth

isL

icen

seis

tom

ake

am

anua

l,te

xtbo

ok,o

rot

her

func

tiona

lan

dus

eful

do-

cum

ent"

free

ïnth

ese

nse

offr

ee-

dom

:to

assu

reev

eryo

neth

eef

-fe

ctiv

efr

eedo

mto

copy

and

re-

dist

ribu

teit,

with

orw

ithou

tmo-

dify

ing

it,ei

ther

com

mer

cial

lyor

nonc

omm

erci

ally

.Sec

onda

ri-

ly,t

his

Lic

ense

pres

erve

sfo

rthe

auth

oran

dpu

blis

her

aw

ayto

get

cred

itfo

rth

eir

wor

k,w

hi-

leno

tbe

ing

cons

ider

edre

spon

-si

ble

for

mod

ifica

tions

mad

eby

othe

rs.

Thi

sL

icen

seis

aki

ndof

"cop

y-le

ft",

whi

chm

eans

that

deriv

ati-

vew

orks

ofth

edo

cum

entm

ust

them

selv

esbe

free

inth

esa

me

sens

e.It

com

plem

ents

the

GN

UG

ener

alPu

blic

Lic

ense

,w

hich

isa

copy

left

licen

sede

sign

edfo

rfre

eso

ftw

are.

We

have

desi

gned

this

Lic

ense

inor

der

tous

eit

for

man

uals

for

free

soft

war

e,be

caus

efr

eeso

ftw

are

need

sfr

eedo

cum

en-

tatio

n:a

free

prog

ram

shou

ldco

me

with

man

uals

prov

idin

gth

esa

me

free

dom

sth

atth

eso

ft-

war

edo

es.

But

this

Lic

ense

isno

tlim

ited

toso

ftw

are

man

u-al

s;it

can

beus

edfo

ran

yte

xtu-

alw

ork,

rega

rdle

ssof

subj

ect

mat

ter

orw

heth

erit

ispu

blis

-he

das

apr

inte

dbo

ok.

We

re-

com

men

dth

isL

icen

sepr

inci

pal-

lyfo

rw

orks

who

sepu

rpos

eis

inst

ruct

ion

orre

fere

nce.

1.A

PP-

LIC

AB

ILIT

YA

ND

DE

FIN

ITI-

ON

S

Thi

sL

icen

seap

plie

sto

any

ma-

nual

orot

her

wor

k,in

any

me-

dium

,tha

tcon

tain

sa

notic

epl

a-ce

dby

the

copy

righ

thol

ders

ay-

ing

itca

nbe

dist

ribu

ted

un-

der

the

term

sof

this

Lic

ense

.Su

cha

notic

egr

ants

aw

orld

-w

ide,

roya

lty-f

ree

licen

se,

unli-

mite

din

dura

tion,

tous

eth

atw

ork

unde

rth

eco

nditi

ons

sta-

ted

here

in.T

he"D

ocum

ent"

,be-

low

,re

fers

toan

ysu

chm

anua

l

orw

ork.

Any

mem

bero

fthe

pu-

blic

isa

licen

see,

and

isad

dres

-se

das

"you

".Y

ouac

cept

the

li-ce

nse

ifyo

uco

py,m

odif

yor

dis-

trib

ute

the

wor

kin

aw

ayre

qui-

ring

perm

issi

onun

derc

opyr

ight

law

.

A"M

odifi

edV

ersi

onöf

the

Do-

cum

entm

eans

any

wor

kco

ntai

-ni

ngth

eD

ocum

ento

ra

port

ion

ofit,

eith

erco

pied

verb

atim

,or

with

mod

ifica

tions

and/

ortr

ans-

late

din

toan

othe

rlan

guag

e.

ASS

econ

dary

Sect

ionï

sa

na-

med

appe

ndix

ora

fron

t-m

atte

rse

ctio

nof

the

Doc

umen

tth

atde

als

excl

usiv

ely

with

the

rela

ti-on

ship

ofth

epu

blis

hers

orau

t-ho

rsof

the

Doc

umen

tto

the

Doc

umen

t’sov

eral

lsu

bjec

t(o

rto

rela

ted

mat

ters

)an

dco

nta-

ins

noth

ing

that

coul

dfa

lldi

-re

ctly

with

inth

atov

eral

lsub

ject

.(T

hus,

ifth

eD

ocum

ent

isin

part

ate

xtbo

okof

mat

hem

atic

s,a

Seco

ndar

ySe

ctio

nm

ayno

tex

plai

nan

ym

athe

mat

ics.

)T

here

latio

nshi

pco

uld

bea

mat

ter

ofhi

stor

ical

conn

ectio

nw

ithth

esu

bjec

tor

with

rela

ted

mat

ters

,or

ofle

gal,

com

mer

cial

,phi

loso

-

phic

al,e

thic

alor

polit

ical

posi

ti-on

rega

rdin

gth

em.

The

Ïnva

rian

tSe

ctio

nsär

ece

r-ta

inSe

cond

ary

Sect

ions

who

setit

les

are

desi

gnat

ed,

asbe

ing

thos

eof

Inva

rian

tSe

ctio

ns,

inth

eno

tice

that

says

that

the

Do-

cum

enti

sre

leas

edun

dert

his

Li-

cens

e.If

ase

ctio

ndo

esno

tfit

the

abov

ede

finiti

onof

Seco

nda-

ryth

enit

isno

tal

low

edto

bede

sign

ated

asIn

vari

ant.

The

Do-

cum

ent

may

cont

ain

zero

Inva

-ri

antS

ectio

ns.I

fth

eD

ocum

ent

does

not

iden

tify

any

Inva

rian

tSe

ctio

nsth

enth

ere

are

none

.

The

"Cov

erTe

xtsä

rece

rtai

nsh

ort

pass

ages

ofte

xtth

atar

elis

ted,

asFr

ont-

Cov

erTe

xts

orB

ack-

Cov

erTe

xts,

inth

eno

ti-ce

that

says

that

the

Doc

umen

tis

rele

ased

unde

rth

isL

icen

se.

AFr

ont-

Cov

erTe

xtm

aybe

atm

ost5

wor

ds,a

nda

Bac

k-C

over

Text

may

beat

mos

t25

wor

ds.

A"T

rans

pare

nt"c

opy

ofth

eD

ocum

ent

mea

nsa

mac

hine

-re

adab

leco

py,

repr

esen

ted

ina

form

atw

hose

spec

ifica

tion

isav

aila

ble

toth

ege

nera

lpu

-bl

ic,t

hati

ssu

itabl

efo

rre

visi

ng

Page 505: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

the

docu

men

tst

raig

htfo

rwar

d-ly

with

gene

ric

text

edito

rsor

(for

imag

esco

mpo

sed

ofpi

xels

)ge

neri

cpa

int

prog

ram

sor

(for

draw

ings

)so

me

wid

ely

avai

l-ab

ledr

awin

ged

itor,

and

that

issu

itabl

efo

rin

putt

ote

xtfo

rmat

-te

rsor

for

auto

mat

ictr

ansl

ati-

onto

ava

riet

yof

form

ats

sui-

tabl

efo

rin

put

tote

xtfo

rmat

-te

rs.A

copy

mad

ein

anot

herw

i-se

Tran

spar

ent

file

form

atw

ho-

sem

arku

p,or

abse

nce

ofm

ark-

up,h

asbe

enar

rang

edto

thw

art

ordi

scou

rage

subs

eque

ntm

odi-

ficat

ion

byre

ader

sis

notT

rans

-pa

rent

.A

nim

age

form

atis

not

Tran

spar

enti

fus

edfo

ran

ysu

b-st

antia

lam

ount

ofte

xt.A

copy

that

isno

t"Tr

ansp

aren

tïsca

lled

Öpa

que"

.

Exa

mpl

esof

suita

ble

form

ats

for

Tran

spar

ent

copi

esin

clud

epl

ain

ASC

IIw

ithou

tm

arku

p,Te

xinf

oin

put

form

at,

LaT

eXin

put

form

at,

SGM

Lor

XM

Lus

ing

apu

blic

lyav

aila

ble

DT

D,

and

stan

dard

-con

form

ing

sim

-pl

eH

TM

L,

Post

Scri

ptor

PDF

desi

gned

for

hum

anm

odifi

ca-

tion.

Exa

mpl

esof

tran

spar

ent

imag

efo

rmat

sin

clud

ePN

G,

XC

Fan

dJP

G.O

paqu

efo

rmat

s

incl

ude

prop

riet

ary

form

ats

that

can

bere

adan

ded

ited

only

bypr

opri

etar

yw

ord

proc

esso

rs,

SGM

Lor

XM

Lfo

rw

hich

the

DT

Dan

d/or

proc

essi

ngto

ols

are

not

gene

rally

avai

labl

e,an

dth

em

achi

ne-g

ener

ated

HT

ML

,Po

stSc

ript

orPD

Fpr

oduc

edby

som

ew

ord

proc

esso

rsfo

rou

t-pu

tpur

pose

son

ly.

The

"Titl

ePa

ge"m

eans

,fo

ra

prin

ted

book

,th

etit

lepa

geits

-el

f,pl

ussu

chfo

llow

ing

page

sas

are

need

edto

hold

,le

gibl

y,th

em

ater

ial

this

Lic

ense

requ

i-re

sto

appe

arin

the

title

page

.Fo

rw

orks

info

rmat

sw

hich

dono

tha

vean

ytit

lepa

geas

such

,"T

itle

Page

"mea

nsth

ete

xtne

-ar

the

mos

tpro

min

enta

ppea

ran-

ceof

the

wor

k’s

title

,pre

cedi

ngth

ebe

ginn

ing

ofth

ebo

dyof

the

text

.

The

"pub

lishe

r"m

eans

any

per-

son

oren

tity

that

dist

ribu

tes

co-

pies

ofth

eD

ocum

entt

oth

epu

-bl

ic.

Ase

ctio

ntitl

edX

YZ

"mea

nsa

nam

edsu

buni

tof

the

Doc

u-m

ent

who

setit

leei

ther

ispr

e-ci

sely

XY

Zor

cont

ains

XY

Zin

pare

nthe

ses

follo

win

gte

xtth

attr

ansl

ates

XY

Zin

anot

her

lan-

guag

e.(H

ere

XY

Zst

ands

for

asp

ecifi

cse

ctio

nna

me

men

-tio

ned

belo

w,

such

asÄ

ckno

w-

ledg

emen

ts",

"Ded

icat

ions

",Ë

n-do

rsem

ents

",or

"His

tory

".)

To"P

rese

rve

the

Title

öfsu

cha

sec-

tion

whe

nyo

um

odif

yth

eD

o-cu

men

tm

eans

that

itre

mai

nsa

sect

ion

Ënt

itled

XY

Zäc

cord

ing

toth

isde

finiti

on.

The

Doc

umen

tm

ayin

clud

eW

arra

nty

Dis

clai

mer

sne

xtto

the

notic

ew

hich

stat

esth

atth

isL

icen

seap

plie

sto

the

Doc

u-m

ent.

The

seW

arra

nty

Dis

clai

-m

ers

are

cons

ider

edto

bein

clu-

ded

byre

fere

nce

inth

isL

icen

se,

but

only

asre

gard

sdi

scla

imin

gw

arra

ntie

s:an

yot

her

impl

icat

i-on

that

thes

eW

arra

nty

Dis

clai

-m

ers

may

have

isvo

idan

dha

sno

effe

cton

the

mea

ning

ofth

isL

icen

se.2

.VE

RB

AT

IMC

OPY

-IN

G

You

may

copy

and

dist

ribu

teth

eD

ocum

ent

inan

ym

ediu

m,

eith

erco

mm

erci

ally

orno

ncom

-m

erci

ally

,pro

vide

dth

atth

isL

i-ce

nse,

the

copy

righ

tnot

ices

,and

the

licen

seno

tice

sayi

ngth

isL

i-

cens

eap

plie

sto

the

Doc

umen

tar

ere

prod

uced

inal

lcop

ies,

and

that

you

add

noot

herc

ondi

tions

wha

tsoe

ver

toth

ose

ofth

isL

i-ce

nse.

You

may

not

use

tech

ni-

calm

easu

res

toob

stru

ctor

con-

trol

the

read

ing

orfu

rthe

rco

-py

ing

ofth

eco

pies

you

mak

eor

dist

ribu

te.H

owev

er,y

oum

ayac

cept

com

pens

atio

nin

exch

an-

gefo

rcop

ies.

Ifyo

udi

stri

bute

ala

rge

enou

ghnu

mbe

rof

copi

esyo

um

usta

lso

follo

wth

eco

ndi-

tions

inse

ctio

n3.

You

may

also

lend

copi

es,

un-

der

the

sam

eco

nditi

ons

stat

edab

ove,

and

you

may

publ

icly

disp

lay

copi

es.3

.CO

PYIN

GIN

QU

AN

TIT

Y

Ifyo

upu

blis

hpr

inte

dco

pies

(or

copi

esin

med

iath

atco

mm

only

have

prin

ted

cove

rs)

ofth

eD

o-cu

men

t,nu

mbe

ring

mor

eth

an10

0,an

dth

eD

ocum

ent’s

licen

seno

tice

requ

ires

Cov

erTe

xts,

you

mus

ten

clos

eth

eco

pies

inco

-ve

rsth

atca

rry,

clea

rly

and

legi

-bl

y,al

lthe

seC

over

Text

s:Fr

ont-

Cov

erTe

xts

onth

efr

ont

cove

r,an

dB

ack-

Cov

erTe

xts

onth

eba

ckco

ver.

Bot

hco

vers

mus

tal

socl

earl

yan

dle

gibl

yid

entif

y

Page 506: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

you

asth

epu

blis

hero

fthe

seco

-pi

es.

The

fron

tco

ver

mus

tpr

e-se

ntth

efu

lltit

lew

ithal

lwor

dsof

the

title

equa

llypr

omin

ent

and

visi

ble.

You

may

add

othe

rm

ater

ial

onth

eco

vers

inad

di-

tion.

Cop

ying

with

chan

ges

li-m

ited

toth

eco

vers

,as

long

asth

eypr

eser

veth

etit

leof

the

Do-

cum

ent

and

satis

fyth

ese

cond

i-tio

ns,c

anbe

trea

ted

asve

rbat

imco

pyin

gin

othe

rres

pect

s.

Ifth

ere

quir

edte

xts

for

eith

erco

ver

are

too

volu

min

ous

tofit

legi

bly,

you

shou

ldpu

tth

efir

ston

eslis

ted

(as

man

yas

fitre

-as

onab

ly)

onth

eac

tual

cove

r,an

dco

ntin

ueth

ere

ston

toad

ja-

cent

page

s.

Ifyo

upu

blis

hor

dist

ribu

teO

paqu

eco

pies

ofth

eD

ocu-

men

tnu

mbe

ring

mor

eth

an10

0,yo

um

ust

eith

erin

clu-

dea

mac

hine

-rea

dabl

eTr

ans-

pare

ntco

pyal

ong

with

each

Opa

que

copy

,ors

tate

inor

with

each

Opa

que

copy

aco

mpu

ter-

netw

ork

loca

tion

from

whi

chth

ege

nera

lne

twor

k-us

ing

pu-

blic

has

acce

ssto

dow

nloa

dus

ing

publ

ic-s

tand

ard

netw

ork

prot

ocol

sa

com

plet

eTr

ansp

a-

rent

copy

ofth

eD

ocum

ent,

free

ofad

ded

mat

eria

l.If

you

use

the

latte

rop

tion,

you

mus

tta

kere

ason

ably

prud

ent

step

s,w

hen

you

begi

ndi

stri

butio

nof

Opa

que

copi

esin

quan

tity,

toen

-su

reth

atth

isTr

ansp

aren

tco

pyw

illre

mai

nth

usac

cess

ible

atth

est

ated

loca

tion

until

atle

ast

one

year

afte

rth

ela

sttim

eyo

udi

stri

bute

anO

paqu

eco

py(d

i-re

ctly

orth

roug

hyo

urag

ents

orre

taile

rs)

ofth

ated

ition

toth

epu

blic

.

Itis

requ

este

d,bu

tnot

requ

ired

,th

atyo

uco

ntac

tth

eau

thor

sof

the

Doc

umen

twel

lbef

ore

redi

s-tr

ibut

ing

any

larg

enu

mbe

rofc

o-pi

es,

togi

veth

ema

chan

ceto

prov

ide

you

with

anup

date

dve

r-si

onof

the

Doc

umen

t.4.

MO

DI-

FIC

AT

ION

S

You

may

copy

and

dist

ribu

tea

Mod

ified

Ver

sion

ofth

eD

ocu-

men

tun

der

the

cond

ition

sof

sect

ions

2an

d3

abov

e,pr

ovi-

ded

that

you

rele

ase

the

Mod

i-fie

dV

ersi

onun

derp

reci

sely

this

Lic

ense

,with

the

Mod

ified

Ver

-si

onfil

ling

the

role

ofth

eD

o-cu

men

t,th

uslic

ensi

ngdi

stri

bu-

tion

and

mod

ifica

tion

ofth

eM

o-

difie

dV

ersi

onto

who

ever

pos-

sess

esa

copy

ofit.

Inad

ditio

n,yo

um

ustd

oth

ese

thin

gsin

the

Mod

ified

Ver

sion

:

*A

.Use

inth

eTi

tlePa

ge(a

ndon

the

cove

rs,i

fan

y)a

title

dis-

tinct

from

that

ofth

eD

ocum

ent,

and

from

thos

eof

prev

ious

vers

i-on

s(w

hich

shou

ld,i

fthe

rew

ere

any,

belis

ted

inth

eH

isto

ryse

c-tio

nof

the

Doc

umen

t).Y

oum

ayus

eth

esa

me

title

asa

prev

ious

vers

ion

ifth

eor

igin

alpu

blis

her

ofth

atve

rsio

ngi

ves

perm

issi

-on

.*B

.Lis

ton

the

Title

Page

,as

auth

ors,

one

orm

ore

pers

ons

oren

titie

sre

spon

sibl

efo

rau

t-ho

rshi

pof

the

mod

ifica

tions

inth

eM

odifi

edV

ersi

on,

toge

ther

with

atle

ast

five

ofth

epr

inci

-pa

laut

hors

ofth

eD

ocum

ent(

all

ofits

prin

cipa

laut

hors

,if

itha

sfe

wer

than

five)

,unl

ess

they

re-

leas

eyo

ufr

omth

isre

quir

emen

t.*

C.S

tate

onth

eTi

tlepa

geth

ena

me

ofth

epu

blis

her

ofth

eM

odifi

edV

ersi

on,a

sth

epu

blis

-he

r.*

D.P

rese

rve

all

the

copy

-ri

ghtn

otic

esof

the

Doc

umen

t.*

E.A

ddan

appr

opri

ate

copy

righ

tno

tice

fory

ourm

odifi

catio

nsad

-ja

cent

toth

eot

her

copy

righ

tno-

tices

.*

F.In

clud

e,im

med

iate

-

lyaf

ter

the

copy

righ

tno

tices

,alic

ense

notic

egi

ving

the

publ

icpe

rmis

sion

tous

eth

eM

odifi

edV

ersi

onun

der

the

term

sof

this

Lic

ense

,in

the

form

show

nin

the

Add

endu

mbe

low

.*G

.Pre

-se

rve

inth

atlic

ense

notic

eth

efu

lllis

tsof

Inva

rian

tSe

ctio

nsan

dre

quir

edC

over

Text

sgi

ven

inth

eD

ocum

ent’s

licen

seno

ti-ce

.*

H.

Incl

ude

anun

alte

red

copy

ofth

isL

icen

se.

*I.

Pre-

serv

eth

ese

ctio

nE

ntitl

ed"H

is-

tory

",Pr

eser

veits

Title

,and

add

toit

anite

mst

atin

gat

leas

tth

etit

le,y

ear,

new

auth

ors,

and

pu-

blis

her

ofth

eM

odifi

edV

ersi

-on

asgi

ven

onth

eTi

tlePa

ge.

Ifth

ere

isno

sect

ion

Ent

itled

"His

tory

ïnth

eD

ocum

ent,

crea

-te

one

stat

ing

the

title

,yea

r,au

t-ho

rs,

and

publ

ishe

rof

the

Do-

cum

enta

sgi

ven

onits

Title

Pa-

ge,t

hen

add

anite

mde

scri

bing

the

Mod

ified

Ver

sion

asst

ated

inth

epr

evio

usse

nten

ce.

*J.

Pres

erve

the

netw

ork

loca

tion,

ifan

y,gi

ven

inth

eD

ocum

ent

for

publ

icac

cess

toa

Tran

spa-

rent

copy

ofth

eD

ocum

ent,

and

likew

ise

the

netw

ork

loca

tions

give

nin

the

Doc

umen

tfo

rpr

e-vi

ous

vers

ions

itw

asba

sed

on.

The

sem

aybe

plac

edin

the

"His

-

Page 507: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

tory

ßect

ion.

You

may

omit

ane

t-w

ork

loca

tion

for

aw

ork

that

was

publ

ishe

dat

leas

tfo

urye

-ar

sbe

fore

the

Doc

umen

tits

elf,

orif

the

orig

inal

publ

ishe

roft

heve

rsio

nit

refe

rsto

give

spe

rmis

-si

on.

*K

.Fo

ran

yse

ctio

nE

nt-

itled

Äck

now

ledg

emen

tsör

"De-

dica

tions

",Pr

eser

veth

eTi

tleof

the

sect

ion,

and

pres

erve

inth

ese

ctio

nal

lthe

subs

tanc

ean

dto

-ne

ofea

chof

the

cont

ribu

tor

ackn

owle

dgem

ents

and/

orde

di-

catio

nsgi

ven

ther

ein.

*L

.Pr

e-se

rve

all

the

Inva

rian

tSe

ctio

nsof

the

Doc

umen

t,un

alte

red

inth

eir

text

and

inth

eir

title

s.Se

c-tio

nnu

mbe

rsor

the

equi

vale

ntar

eno

tco

nsid

ered

part

ofth

ese

ctio

ntit

les.

*M

.D

elet

ean

yse

ctio

nE

ntitl

edË

ndor

sem

ents

".Su

cha

sect

ion

may

not

bein

-cl

uded

inth

eM

odifi

edV

ersi

-on

.*N

.Do

notr

etitl

ean

yex

is-

ting

sect

ion

tobe

Ent

itled

Ën-

dors

emen

tsör

toco

nflic

tin

title

with

any

Inva

rian

tSec

tion.

*O

.Pr

eser

vean

yW

arra

nty

Dis

clai

-m

ers.

Ifth

eM

odifi

edV

ersi

onin

clu-

des

new

fron

t-m

atte

rsec

tions

orap

pend

ices

that

qual

ify

asSe

-co

ndar

ySe

ctio

nsan

dco

ntai

nno

mat

eria

lco

pied

from

the

Doc

u-m

ent,

you

may

atyo

urop

tion

desi

gnat

eso

me

oral

lof

thes

ese

ctio

nsas

inva

rian

t.To

doth

is,

add

thei

rtit

les

toth

elis

tof

In-

vari

antS

ectio

nsin

the

Mod

ified

Ver

sion

’slic

ense

notic

e.T

hese

title

sm

ust

bedi

stin

ctfr

oman

yot

hers

ectio

ntit

les.

You

may

add

ase

ctio

nE

ntit-

led

Ënd

orse

men

ts",

prov

ided

itco

ntai

nsno

thin

gbu

ten

dors

e-m

ents

ofyo

urM

odifi

edV

ersi

onby

vari

ous

part

ies—

for

exam

p-le

,sta

tem

ents

ofpe

erre

view

orth

atth

ete

xtha

sbe

enap

prov

edby

anor

gani

zatio

nas

the

auth

o-ri

tativ

ede

finiti

onof

ast

anda

rd.

You

may

add

apa

ssag

eof

upto

five

wor

dsas

aFr

ont-

Cov

erTe

xt,

and

apa

ssag

eof

upto

25w

ords

asa

Bac

k-C

over

Text

,to

the

end

ofth

elis

tof

Co-

ver

Text

sin

the

Mod

ified

Ver

si-

on.

Onl

yon

epa

ssag

eof

Fron

t-C

over

Text

and

one

ofB

ack-

Cov

erTe

xtm

aybe

adde

dby

(or

thro

ugh

arra

ngem

ents

mad

eby

)an

yon

een

tity.

Ifth

eD

ocum

ent

alre

ady

incl

udes

aco

vert

extf

orth

esa

me

cove

r,pr

evio

usly

ad-

ded

byyo

uor

byar

rang

emen

t

mad

eby

the

sam

een

tity

you

are

actin

gon

beha

lfof

,you

may

not

add

anot

her;

but

you

may

repl

ace

the

old

one,

onex

pli-

citp

erm

issi

onfr

omth

epr

evio

uspu

blis

hert

hata

dded

the

old

one.

The

auth

or(s

)an

dpu

blis

her(

s)of

the

Doc

umen

tdo

notb

yth

isL

icen

segi

vepe

rmis

sion

tous

eth

eir

nam

esfo

rpu

blic

ityfo

ror

toas

sert

orim

ply

endo

rse-

men

tofa

nyM

odifi

edV

ersi

on.5

.C

OM

BIN

ING

DO

CU

ME

NT

S

You

may

com

bine

the

Doc

u-m

ent

with

othe

rdo

cum

ents

re-

leas

edun

der

this

Lic

ense

,un

-de

rth

ete

rms

defin

edin

sect

ion

4ab

ove

for

mod

ified

vers

ions

,pr

ovid

edth

atyo

uin

clud

ein

the

com

bina

tion

allo

fth

eIn

vari

ant

Sect

ions

ofal

lof

the

orig

inal

docu

men

ts,u

nmod

ified

,and

list

them

alla

sIn

vari

antS

ectio

nsof

your

com

bine

dw

ork

inits

licen

-se

notic

e,an

dth

atyo

upr

eser

veal

lthe

irW

arra

nty

Dis

clai

mer

s.

The

com

bine

dw

ork

need

only

cont

ain

one

copy

ofth

isL

icen

-se

,an

dm

ultip

leid

entic

alIn

va-

rian

tSe

ctio

nsm

aybe

repl

aced

with

asi

ngle

copy

.If

ther

ear

e

mul

tiple

Inva

rian

tSec

tions

with

the

sam

ena

me

butd

iffer

entc

on-

tent

s,m

ake

the

title

ofea

chsu

chse

ctio

nun

ique

byad

ding

atth

een

dof

it,in

pare

nthe

ses,

the

na-

me

ofth

eor

igin

alau

thor

orpu

-bl

ishe

rof

that

sect

ion

ifkn

own,

orel

sea

uniq

uenu

mbe

r.M

ake

the

sam

ead

just

men

tto

the

sec-

tion

title

sin

the

listo

fIn

vari

ant

Sect

ions

inth

elic

ense

notic

eof

the

com

bine

dw

ork.

Inth

eco

mbi

natio

n,yo

um

ust

com

bine

any

sect

ions

Ent

itled

"His

tory

ïnth

eva

riou

sor

igin

aldo

cum

ents

,fo

rmin

gon

ese

c-tio

nE

ntitl

ed"H

isto

ry";

likew

i-se

com

bine

any

sect

ions

Ent

-itl

edÄ

ckno

wle

dgem

ents

",an

dan

yse

ctio

nsE

ntitl

ed"D

edic

ati-

ons"

.Y

oum

ust

dele

teal

lse

c-tio

nsE

ntitl

edË

ndor

sem

ents

".6.

CO

LL

EC

TIO

NS

OF

DO

CU

-M

EN

TS

You

may

mak

ea

colle

ctio

nco

n-si

stin

gof

the

Doc

umen

tan

dot

her

docu

men

tsre

leas

edun

der

this

Lic

ense

,and

repl

ace

the

in-

divi

dual

copi

esof

this

Lic

ense

inth

eva

riou

sdo

cum

ents

with

asi

ngle

copy

that

isin

clud

edin

the

colle

ctio

n,pr

ovid

edth

atyo

u

Page 508: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

follo

wth

eru

les

ofth

isL

icen

-se

for

verb

atim

copy

ing

ofea

chof

the

docu

men

tsin

allo

ther

re-

spec

ts.

You

may

extr

act

asi

ngle

do-

cum

ent

from

such

aco

llect

ion,

and

dist

ribu

teit

indi

vidu

ally

un-

der

this

Lic

ense

,pr

ovid

edyo

uin

sert

aco

pyof

this

Lic

en-

sein

toth

eex

trac

ted

docu

men

t,an

dfo

llow

this

Lic

ense

inal

lot

her

resp

ects

rega

rdin

gve

rba-

timco

pyin

gof

that

docu

men

t.7.

AG

GR

EG

AT

ION

WIT

HIN

DE

-PE

ND

EN

TW

OR

KS

Aco

mpi

latio

nof

the

Doc

umen

tor

itsde

rivat

ives

with

othe

rsep

a-ra

tean

din

depe

nden

tdoc

umen

tsor

wor

ks,i

nor

ona

volu

me

ofa

stor

age

ordi

stri

butio

nm

ediu

m,

isca

lled

anäg

greg

ateï

fth

eco

-py

righ

tre

sulti

ngfr

omth

eco

m-

pila

tion

isno

tus

edto

limit

the

lega

lrig

hts

ofth

eco

mpi

latio

n’s

user

sbe

yond

wha

tthe

indi

vidu

-al

wor

kspe

rmit.

Whe

nth

eD

o-cu

men

tis

incl

uded

inan

aggr

e-ga

te,t

his

Lic

ense

does

nota

pp-

lyto

the

othe

rw

orks

inth

eag

-gr

egat

ew

hich

are

not

them

sel-

ves

deriv

ativ

ew

orks

ofth

eD

o-cu

men

t.

Ifth

eC

over

Text

requ

irem

ento

fse

ctio

n3

isap

plic

able

toth

ese

copi

esof

the

Doc

umen

t,th

enif

the

Doc

umen

tis

less

than

one

half

ofth

een

tire

aggr

egat

e,th

eD

ocum

ent’s

Cov

erTe

xts

may

bepl

aced

onco

vers

that

brac

ket

the

Doc

umen

twith

inth

eag

gre-

gate

,ort

heel

ectr

onic

equi

vale

ntof

cove

rsif

the

Doc

umen

tis

inel

ectr

onic

form

.Oth

erw

ise

they

mus

tap

pear

onpr

inte

dco

vers

that

brac

ket

the

who

leag

greg

a-te

.8.T

RA

NSL

AT

ION

Tran

slat

ion

isco

nsid

ered

aki

ndof

mod

ifica

tion,

soyo

um

aydi

s-tr

ibut

etr

ansl

atio

nsof

the

Doc

u-m

entu

nder

the

term

sof

sect

ion

4.R

epla

cing

Inva

rian

tSe

ctio

nsw

ithtr

ansl

atio

nsre

quir

essp

e-ci

alpe

rmis

sion

from

thei

rco

py-

righ

tho

lder

s,bu

tyo

um

ayin

-cl

ude

tran

slat

ions

ofso

me

oral

lInv

aria

ntSe

ctio

nsin

addi

tion

toth

eor

igin

alve

rsio

nsof

the-

seIn

vari

ant

Sect

ions

.Y

oum

ayin

clud

ea

tran

slat

ion

ofth

isL

i-ce

nse,

and

all

the

licen

seno

ti-ce

sin

the

Doc

umen

t,an

dan

yW

arra

nty

Dis

clai

mer

s,pr

ovid

edth

atyo

ual

soin

clud

eth

eor

igi-

nal

Eng

lish

vers

ion

ofth

isL

i-ce

nse

and

the

orig

inal

vers

ions

ofth

ose

notic

esan

ddi

scla

imer

s.In

case

ofa

disa

gree

men

tbe

t-w

een

the

tran

slat

ion

and

the

ori-

gina

lver

sion

ofth

isL

icen

seor

ano

tice

ordi

scla

imer

,the

orig

inal

vers

ion

will

prev

ail.

Ifa

sect

ion

inth

eD

ocum

ent

isE

ntitl

edÄ

ckno

wle

dgem

ents

","D

edic

atio

ns",

or"H

isto

ry",

the

requ

irem

ent

(sec

tion

4)to

Pre-

serv

eits

Title

(sec

tion

1)w

illty

-pi

cally

requ

ire

chan

ging

the

ac-

tual

title

.9.T

ER

MIN

AT

ION

You

may

notc

opy,

mod

ify,

sub-

licen

se,

ordi

stri

bute

the

Doc

u-m

ent

exce

ptas

expr

essl

ypr

ovi-

ded

unde

rth

isL

icen

se.A

nyat

-te

mpt

othe

rwis

eto

copy

,m

odi-

fy,s

ublic

ense

,or

dist

ribu

teit

isvo

id,a

ndw

illau

tom

atic

ally

ter-

min

ate

your

righ

tsun

dert

his

Li-

cens

e.

How

ever

,if

you

ceas

eal

lvio

la-

tion

ofth

isL

icen

se,

then

your

licen

sefr

oma

part

icul

arco

py-

righ

thol

deri

sre

inst

ated

(a)p

ro-

visi

onal

ly,

unle

ssan

dun

tilth

eco

pyri

ght

hold

erex

plic

itly

and

final

lyte

rmin

ates

your

licen

se,

and

(b)p

erm

anen

tly,i

fthe

copy

-ri

ght

hold

erfa

ilsto

notif

yyo

u

ofth

evi

olat

ion

byso

me

rea-

sona

ble

mea

nspr

ior

to60

days

afte

rthe

cess

atio

n.

Mor

eove

r,yo

urlic

ense

from

apa

rtic

ular

copy

righ

thol

deri

sre

-in

stat

edpe

rman

ently

ifth

eco

py-

righ

tho

lder

notifi

esyo

uof

the

viol

atio

nby

som

ere

ason

able

mea

ns,t

his

isth

efir

sttim

eyo

uha

vere

ceiv

edno

tice

ofvi

olat

i-on

ofth

isL

icen

se(f

oran

yw

ork)

from

that

copy

righ

tho

lder

,and

you

cure

the

viol

atio

npr

ior

to30

days

afte

ryou

rrec

eipt

ofth

eno

tice.

Term

inat

ion

ofyo

urri

ghts

un-

der

this

sect

ion

does

not

term

i-na

teth

elic

ense

sof

part

ies

who

have

rece

ived

copi

esor

righ

tsfr

omyo

uun

der

this

Lic

ense

.If

your

righ

tsha

vebe

ente

rmin

a-te

dan

dno

tper

man

ently

rein

sta-

ted,

rece

ipt

ofa

copy

ofso

me

oral

lof

the

sam

em

ater

iald

oes

notg

ive

you

any

righ

tsto

use

it.10

.FU

TU

RE

RE

VIS

ION

SO

FT

HIS

LIC

EN

SE

The

Free

Soft

war

eFo

unda

ti-on

may

publ

ish

new

,re

vise

dve

rsio

nsof

the

GN

UFr

eeD

ocum

enta

tion

Lic

ense

from

Page 509: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

time

totim

e.Su

chne

wve

r-si

ons

will

besi

mila

rin

spi-

rit

toth

epr

esen

tve

rsio

n,bu

tm

aydi

ffer

inde

tail

toad

dres

sne

wpr

oble

ms

orco

ncer

ns.S

eeht

tp://

ww

w.g

nu.o

rg/c

opyl

eft/.

Eac

hve

rsio

nof

the

Lic

ense

isgi

ven

adi

stin

guis

hing

vers

ion

num

ber.

Ifth

eD

ocum

ents

peci

-fie

sth

ata

part

icul

arnu

mbe

red

vers

ion

ofth

isL

icen

seör

any

la-

ter

vers

ionä

pplie

sto

it,yo

uha

-ve

the

optio

nof

follo

win

gth

ete

rms

and

cond

ition

sei

ther

ofth

atsp

ecifi

edve

rsio

nor

ofan

yla

ter

vers

ion

that

has

been

pu-

blis

hed

(not

asa

draf

t)by

the

Free

Soft

war

eFo

unda

tion.

Ifth

eD

ocum

ent

does

not

spec

ify

ave

rsio

nnu

mbe

rof

this

Lic

en-

se,y

oum

aych

oose

any

vers

ion

ever

publ

ishe

d(n

otas

adr

aft)

byth

eFr

eeSo

ftw

are

Foun

datio

n.If

the

Doc

umen

tspe

cifie

sth

ata

prox

yca

nde

cide

whi

chfu

ture

vers

ions

ofth

isL

icen

seca

nbe

used

,th

atpr

oxy’

spu

blic

stat

e-m

ento

fac

cept

ance

ofa

vers

ion

perm

anen

tlyau

thor

izes

you

toch

oose

that

vers

ion

for

the

Do-

cum

ent.

11.R

EL

ICE

NSI

NG

"Mas

sive

Mul

tiaut

hor

Col

labo

-ra

tion

Site

"(or

"MM

CSi

te")

me-

ans

any

Wor

ldW

ide

Web

ser-

vert

hatp

ublis

hes

copy

righ

tabl

ew

orks

and

also

prov

ides

prom

i-ne

ntfa

cilit

ies

for

anyb

ody

toed

itth

ose

wor

ks.

Apu

blic

wi-

kith

atan

ybod

yca

ned

itis

anex

ampl

eof

such

ase

rver

.A

"Mas

sive

Mul

tiaut

hor

Col

labo

-ra

tion"

(or"

MM

C")

cont

aine

din

the

site

mea

nsan

yse

tof

copy

-ri

ghta

ble

wor

ksth

uspu

blis

hed

onth

eM

MC

site

.

"CC

-BY

-SA

"mea

nsth

eC

reat

i-ve

Com

mon

sA

ttrib

utio

n-Sh

are

Alik

e3.

0lic

ense

publ

ishe

dby

Cre

ativ

eC

omm

onsC

orpo

ratio

n,a

not-

for-

profi

tcor

pora

tion

with

apr

inci

pal

plac

eof

busi

ness

inSa

nFr

anci

sco,

Cal

ifor

nia,

asw

ell

asfu

ture

copy

left

vers

ions

ofth

atlic

ense

publ

ishe

dby

that

sam

eor

gani

zatio

n.

Ïnco

rpor

ate"

mea

nsto

publ

ish

orre

publ

ish

aD

ocum

ent,

inw

hole

orin

part

,as

part

ofan

othe

rDo-

cum

ent.

An

MM

Cis

ëlig

ible

for

relic

en-

sing

ïfit

islic

ense

dun

dert

hisL

i-ce

nse,

and

ifal

lw

orks

that

we-

refir

stpu

blis

hed

unde

rth

isL

i-ce

nse

som

ewhe

reot

hert

han

this

MM

C,

and

subs

eque

ntly

inco

r-po

rate

din

who

leor

inpa

rtin

toth

eM

MC

,(1)

had

noco

vert

exts

orin

vari

ants

ectio

ns,a

nd(2

)we-

reth

usin

corp

orat

edpr

iort

oN

o-ve

mbe

r1,2

008.

The

oper

ator

ofan

MM

CSi

tem

ayre

publ

ish

anM

MC

cont

ai-

ned

inth

esi

teun

der

CC

-BY

-SA

onth

esa

me

site

atan

ytim

ebe

fore

Aug

ust

1,20

09,

prov

i-de

dth

eM

MC

isel

igib

lefo

rrel

i-ce

nsin

g.A

DD

EN

DU

M:H

owto

use

this

Lic

ense

for

your

docu

-m

ents

Tous

eth

isL

icen

sein

ado

cu-

men

tyou

have

wri

tten,

incl

ude

aco

pyof

the

Lic

ense

inth

edo

cu-

men

tan

dpu

tth

efo

llow

ing

co-

pyri

ght

and

licen

seno

tices

just

afte

rthe

title

page

:

Cop

yrig

ht(C

)Y

EA

RY

OU

RN

AM

E.P

erm

issi

onis

gran

ted

toco

py,

dist

ribu

tean

d/or

mod

ify

this

docu

men

tun

der

the

term

sof

the

GN

UFr

eeD

ocum

enta

ti-on

Lic

ense

,V

ersi

on1.

3or

any

late

rve

rsio

npu

blis

hed

byth

eFr

eeSo

ftw

are

Foun

datio

n;w

ith

noIn

vari

antS

ectio

ns,n

oFr

ont-

Cov

erTe

xts,

and

noB

ack-

Cov

erTe

xts.

Aco

pyof

the

licen

seis

incl

uded

inth

ese

ctio

nen

title

d"G

NU

Free

Doc

umen

tatio

nL

i-ce

nse"

.

Ifyo

uha

veIn

vari

ant

Sect

ions

,Fr

ont-

Cov

erTe

xts

and

Bac

k-C

over

Text

s,re

plac

eth

e"w

ith..

.Te

xts.

"lin

ew

ithth

is:

with

the

Inva

rian

tSe

ctio

nsbe

ing

LIS

TT

HE

IRT

ITL

ES,

with

the

Fron

t-C

over

Text

sbe

ing

LIS

T,an

dw

ithth

eB

ack-

Cov

erTe

xts

bein

gL

IST.

Ifyo

uha

veIn

vari

ant

Sect

ions

with

out

Cov

erTe

xts,

orso

me

othe

rco

mbi

natio

nof

the

thre

e,m

erge

thos

etw

oal

tern

ativ

esto

suit

the

situ

atio

n.

Ifyo

urdo

cum

ent

cont

ains

nont

rivia

lexa

mpl

esof

prog

ram

code

,w

ere

com

men

dre

leas

ing

thes

eex

ampl

esin

para

llelu

nder

your

choi

ceof

free

soft

war

eli-

cens

e,su

chas

the

GN

UG

ener

alPu

blic

Lic

ense

,to

perm

itth

eir

use

infr

eeso

ftw

are.

Page 510: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

22.3

GN

UL

esse

rG

ener

alPu

blic

Lic

ense

GN

UL

ESS

ER

GE

NE

RA

LPU

-B

LIC

LIC

EN

SE

Ver

sion

3,29

June

2007

Cop

yrig

ht©

2007

Free

Soft

war

eFo

unda

tion,

Inc.

<http

://fs

f.org

/>

Eve

ryon

eis

perm

itted

toco

pyan

ddi

stri

bute

verb

atim

copi

esof

this

licen

sedo

cum

ent,

but

chan

ging

itis

nota

llow

ed.

Thi

sve

rsio

nof

the

GN

UL

esse

rG

ener

alPu

blic

Lic

ense

inco

rpo-

rate

sth

ete

rms

and

cond

ition

sof

vers

ion

3of

the

GN

UG

ene-

ral

Publ

icL

icen

se,

supp

lem

en-

ted

byth

ead

ditio

nal

perm

issi

-on

slis

ted

belo

w.

0.A

dditi

onal

Defi

nitio

ns.

As

used

here

in,

“thi

sL

icen

se”

refe

rsto

vers

ion

3of

the

GN

UL

esse

rG

ener

alPu

blic

Lic

ense

,an

dth

e“G

NU

GPL

”re

fers

tove

rsio

n3

ofth

eG

NU

Gen

eral

Publ

icL

icen

se.

“The

Lib

rary

”re

fers

toa

cove

r-ed

wor

kgo

vern

edby

this

Lic

en-

se,o

ther

than

anA

pplic

atio

nor

aC

ombi

ned

Wor

kas

defin

edbe

-lo

w.

An

“App

licat

ion”

isan

yw

ork

that

mak

esus

eof

anin

terf

ace

prov

ided

byth

eL

ibra

ry,

but

whi

chis

noto

ther

wis

eba

sed

onth

eL

ibra

ry.D

efini

nga

subc

lass

ofa

clas

sde

fined

byth

eL

ibra

ryis

deem

eda

mod

eof

usin

gan

in-

terf

ace

prov

ided

byth

eL

ibra

ry.

A“C

ombi

ned

Wor

k”is

aw

ork

prod

uced

byco

mbi

ning

orlin

-ki

ngan

App

licat

ion

with

the

Li-

brar

y.T

hepa

rtic

ular

vers

ion

ofth

eL

ibra

ryw

ithw

hich

the

Com

-bi

ned

Wor

kw

asm

ade

isal

soca

lled

the

“Lin

ked

Ver

sion

”.

The

“Min

imal

Cor

resp

ondi

ngSo

urce

”fo

ra

Com

bine

dW

ork

mea

nsth

eC

orre

spon

ding

Sour

-ce

for

the

Com

bine

dW

ork,

ex-

clud

ing

any

sour

ceco

defo

rpor

-tio

nsof

the

Com

bine

dW

ork

that

,con

side

red

inis

olat

ion,

are

base

don

the

App

licat

ion,

and

noto

nth

eL

inke

dV

ersi

on.

The

“Cor

resp

ondi

ngA

pplic

ati-

onC

ode”

fora

Com

bine

dW

ork

mea

nsth

eob

ject

code

and/

orso

urce

code

for

the

App

licat

i-on

,in

clud

ing

any

data

and

uti-

lity

prog

ram

sne

eded

for

re-

prod

ucin

gth

eC

ombi

ned

Wor

kfr

omth

eA

pplic

atio

n,bu

texc

lu-

ding

the

Syst

emL

ibra

ries

ofth

eC

ombi

ned

Wor

k.1.

Exc

eptio

nto

Sect

ion

3of

the

GN

UG

PL.

You

may

conv

eya

cove

red

wor

kun

der

sect

ions

3an

d4

ofth

isL

icen

sew

ithou

tbei

ngbo

und

byse

ctio

n3

ofth

eG

NU

GPL

.2.

Con

veyi

ngM

odifi

edV

ersi

ons.

Ifyo

um

odif

ya

copy

ofth

eL

i-br

ary,

and,

inyo

urm

odifi

cati-

ons,

afa

cilit

yre

fers

toa

func

-tio

nor

data

tobe

supp

lied

byan

App

licat

ion

that

uses

the

faci

lity

(oth

erth

anas

anar

gum

ent

pas-

sed

whe

nth

efa

cilit

yis

invo

ked)

,th

enyo

um

ayco

nvey

aco

pyof

the

mod

ified

vers

ion:

*a)

unde

rthi

sLic

ense

,pro

vide

dth

atyo

um

ake

ago

odfa

ithef

-fo

rtto

ensu

reth

at,i

nth

eev

ent

anA

pplic

atio

ndo

esno

tsu

pply

the

func

tion

orda

ta,t

hefa

cilit

yst

illop

erat

es,a

ndpe

rfor

msw

ha-

teve

rpar

tofi

tspu

rpos

ere

mai

nsm

eani

ngfu

l,or

*b)

unde

rth

eG

NU

GPL

,with

none

ofth

ead

-di

tiona

lpe

rmis

sion

sof

this

Li-

cens

eap

plic

able

toth

atco

py.

3.O

bjec

tC

ode

Inco

rpor

atin

gM

ater

ial

from

Lib

rary

Hea

der

File

s.

The

obje

ctco

defo

rmof

anA

pp-

licat

ion

may

inco

rpor

ate

mat

eri-

alfr

oma

head

erfil

eth

atis

part

ofth

eL

ibra

ry.Y

oum

ayco

nvey

such

obje

ctco

deun

dert

erm

sof

your

choi

ce,p

rovi

ded

that

,ift

hein

corp

orat

edm

ater

ial

isno

tli-

mite

dto

num

eric

alpa

ram

eter

s,da

tast

ruct

ure

layo

uts

and

ac-

cess

ors,

orsm

allm

acro

s,in

line

func

tions

and

tem

plat

es(t

enor

few

erlin

esin

leng

th),

you

dobo

thof

the

follo

win

g:

Page 511: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

*a)

Giv

epr

omin

entn

otic

ew

ithea

chco

pyof

the

obje

ctco

deth

atth

eL

ibra

ryis

used

init

and

that

the

Lib

rary

and

itsus

ear

eco

ver-

edby

this

Lic

ense

.*b)

Acc

om-

pany

the

obje

ctco

dew

itha

copy

ofth

eG

NU

GPL

and

this

licen

-se

docu

men

t.

4.C

ombi

ned

Wor

ks.

You

may

conv

eya

Com

bi-

ned

Wor

kun

der

term

sof

your

choi

ceth

at,

take

nto

geth

er,

ef-

fect

ivel

ydo

not

rest

rict

mod

ifi-

catio

nof

the

port

ions

ofth

eL

i-br

ary

cont

aine

din

the

Com

bi-

ned

Wor

kan

dre

vers

een

gine

e-ri

ngfo

rde

bugg

ing

such

mod

ifi-

catio

ns,

ifyo

ual

sodo

each

ofth

efo

llow

ing:

*a)

Giv

epr

omin

entn

otic

ew

ithea

chco

pyof

the

Com

bine

dW

ork

that

the

Lib

rary

isus

edin

itan

dth

atth

eL

ibra

ryan

dits

use

are

cove

red

byth

isL

icen

se.

*b)

Acc

ompa

nyth

eC

ombi

ned

Wor

kw

itha

copy

ofth

eG

NU

GPL

and

this

licen

sedo

cum

ent.

*c)

For

aC

ombi

ned

Wor

kth

atdi

spla

ysco

pyri

ght

notic

esdu

-ri

ngex

ecut

ion,

incl

ude

the

co-

pyri

ght

notic

efo

rth

eL

ibra

ry

amon

gth

ese

notic

es,a

sw

ella

sa

refe

renc

edi

rect

ing

the

user

toth

eco

pies

ofth

eG

NU

GPL

and

this

licen

sedo

cum

ent.

*d)

Do

one

ofth

efo

llow

ing:

o0)

Con

-ve

yth

eM

inim

alC

orre

spon

ding

Sour

ceun

der

the

term

sof

this

Lic

ense

,and

the

Cor

resp

ondi

ngA

pplic

atio

nC

ode

ina

form

sui-

tabl

efo

r,an

dun

der

term

sth

atpe

rmit,

the

user

tore

com

bine

orre

link

the

App

licat

ion

with

am

odifi

edve

rsio

nof

the

Lin

-ke

dV

ersi

onto

prod

uce

am

o-di

fied

Com

bine

dW

ork,

inth

em

anne

rsp

ecifi

edby

sect

ion

6of

the

GN

UG

PLfo

rco

nvey

-in

gC

orre

spon

ding

Sour

ce.o

1)U

sea

suita

ble

shar

edlib

rary

me-

chan

ism

for

linki

ngw

ithth

eL

i-br

ary.

Asu

itabl

em

echa

nism

ison

eth

at(a

)us

esat

run

time

aco

pyof

the

Lib

rary

alre

ady

pre-

sent

onth

eus

er’s

com

pute

rsy

s-te

m,

and

(b)

will

oper

ate

pro-

perl

yw

itha

mod

ified

vers

ion

ofth

eL

ibra

ryth

atis

inte

rfac

e-co

mpa

tible

with

the

Lin

ked

Ver

-si

on.*

e)Pr

ovid

eIn

stal

latio

nIn

-fo

rmat

ion,

buto

nly

ifyo

uw

ould

othe

rwis

ebe

requ

ired

topr

ovid

esu

chin

form

atio

nun

der

sect

ion

6of

the

GN

UG

PL,a

ndon

lyto

the

exte

ntth

atsu

chin

form

atio

n

isne

cess

ary

toin

stal

lan

dex

e-cu

tea

mod

ified

vers

ion

ofth

eC

ombi

ned

Wor

kpr

oduc

edby

re-

com

bini

ngor

relin

king

the

Ap-

plic

atio

nw

itha

mod

ified

vers

i-on

ofth

eL

inke

dV

ersi

on.

(If

you

use

optio

n4d

0,th

eIn

stal

la-

tion

Info

rmat

ion

mus

tacc

ompa

-ny

the

Min

imal

Cor

resp

ondi

ngSo

urce

and

Cor

resp

ondi

ngA

pp-

licat

ion

Cod

e.If

you

use

optio

n4d

1,yo

um

ustp

rovi

deth

eIn

stal

-la

tion

Info

rmat

ion

inth

em

an-

ners

peci

fied

byse

ctio

n6

ofth

eG

NU

GPL

forc

onve

ying

Cor

re-

spon

ding

Sour

ce.)

5.C

ombi

ned

Lib

rari

es.

You

may

plac

elib

rary

faci

litie

sth

atar

ea

wor

kba

sed

onth

eL

i-br

ary

side

bysi

dein

asi

ngle

li-br

ary

toge

ther

with

othe

rlib

ra-

ryfa

cilit

ies

that

are

not

App

li-ca

tions

and

are

not

cove

red

byth

isL

icen

se,a

ndco

nvey

such

aco

mbi

ned

libra

ryun

dert

erm

sof

your

choi

ce,

ifyo

udo

both

ofth

efo

llow

ing:

*a)

Acc

ompa

nyth

eco

mbi

ned

libra

ryw

itha

copy

ofth

esa

me

wor

kba

sed

onth

eL

ibra

ry,

un-

com

bine

dw

ithan

yot

her

libra

-

ryfa

cilit

ies,

conv

eyed

unde

rthe

term

sof

this

Lic

ense

.*b)

Giv

epr

omin

ent

notic

ew

ithth

eco

m-

bine

dlib

rary

that

part

ofit

isa

wor

kba

sed

onth

eL

ibra

ry,a

ndex

plai

ning

whe

reto

find

the

ac-

com

pany

ing

unco

mbi

ned

form

ofth

esa

me

wor

k.

6.R

evis

edV

ersi

ons

ofth

eG

NU

Les

serG

ener

alPu

blic

Lic

ense

.

The

Free

Soft

war

eFo

unda

tion

may

publ

ish

revi

sed

and/

orne

wve

rsio

nsof

the

GN

UL

esse

rG

e-ne

ral

Publ

icL

icen

sefr

omtim

eto

time.

Such

new

vers

ions

will

besi

mila

rin

spir

itto

the

pres

ent

vers

ion,

butm

aydi

ffer

inde

tail

toad

dres

sne

wpr

oble

ms

orco

n-ce

rns.

Eac

hve

rsio

nis

give

na

dist

ingu

-is

hing

vers

ion

num

ber.

Ifth

eL

i-br

ary

asyo

ure

ceiv

edit

spec

ifies

that

ace

rtai

nnu

mbe

red

vers

ion

ofth

eG

NU

Les

ser

Gen

eral

Pu-

blic

Lic

ense

“or

any

late

rve

rsi-

on”

appl

ies

toit,

you

have

the

optio

nof

follo

win

gth

ete

rms

and

cond

ition

sei

ther

ofth

atpu

-bl

ishe

dve

rsio

nor

ofan

yla

ter

vers

ion

publ

ishe

dby

the

Free

Soft

war

eFo

unda

tion.

Ifth

eL

i-

Page 512: 2012 · 2012 well licensed - figures con- licensed this a The page chap- may licenses, of 477

brar

yas

you

rece

ived

itdo

esno

tsp

ecif

ya

vers

ion

num

ber

ofth

eG

NU

Les

ser

Gen

eral

Publ

icL

i-ce

nse,

you

may

choo

sean

yve

r-si

onof

the

GN

UL

esse

rG

ene-

ral

Publ

icL

icen

seev

erpu

blis

-he

dby

the

Free

Soft

war

eFo

un-

datio

n.

Ifth

eL

ibra

ryas

you

rece

ived

itsp

ecifi

esth

ata

prox

yca

nde

-ci

dew

heth

erfu

ture

vers

ions

ofth

eG

NU

Les

ser

Gen

eral

Publ

icL

icen

sesh

alla

pply

,tha

tpro

xy’s

publ

icst

atem

ent

ofac

cept

ance

ofan

yve

rsio

nis

perm

anen

taut

-ho

riza

tion

fory

outo

choo

seth

atve

rsio

nfo

rthe

Lib

rary

.