Python for Unix and Linux System Administration (ru)


Чтобы посмотреть этот PDF файл с форматированием и разметкой, скачайте его и откройте на своем компьютере.
  \b\t\n \f\r\t\b « \b» \t\t\b\r\r
\f \b «Books.Ru …    » \t \t \t\r 
\t  \r \r\r  !  ISBN 9785932861493, \r\f\r
 \t «Python   \t\b\b \r\b   \r UNIX Linux» … 
!!\r  \t\t\b\r\r\f \t «Books.Ru …    ». " # 
  \r \r !\r! \b   \b \r\f\b, # \r$ 
\b\t\n\r\t \f\r!\r\t \f\r!\r\t  !
%\t\t\r&  '\r\t \r! \r\r. #\r\b \t' \b \r 
\r \r, \r\r!\n\t (  \f\r\t « \b»
)[email protected]*, \t \b\t #   \r \r.
Noah Gift, Jeremy M. Jones
Python
System Administration
     . 
Python
     
 
2009
     . 
Python      
UNIX  Linux
  .  
   
.
.    
.   
    
.
  
.
  
C. 
  
. 
 .,  .
Python         UNIX  Linux  .  . .:
 , 2009. 512., .
ISBN 9785932861493
 Python         UNIX  Linux   
,  !!   " # $ $ $ %  &    UNIX
 Linux    # &$    & Python. ' &   & 
     $ % ,     $ %  ,  $    
(   $     (          ,   
  %      " &  &$ Python.     
( : $&   &        % !   ' 
   #$    (  ($ ,  $    (  
 !%    !  , $& $  &  $ (
 $   '  & Google App Engine.    ,     $
   & $$        &   # 
"  $ Ubuntu,  % (       $    
   & #  ,  #$ SNMP, IPython, SQLAlchemy
     .
)$  %   "   
   (, # %
 # &$ Python,  #   $ %      &$ (
     %     #
 $      
  .
ISBN 9785932861493
ISBN 9780596515829 ()
)$  #   , 2009
Authorized translation of the English editio
n 2008 OReilly Media, Inc. This trans
lation is published and sold by permission of OReilly Media, Inc., the owner of all
rights to publish and sell the same.
    $  $     #   *,  %&      %
%   $     !  .   $   $     $
,      &  $ , && &      #    ( !.
)$  #   .199034,  ,16&,7,
.+812- 3245353, www.symbol.ru. / $& / N 000054 25.12.98.
;  & #      !     
 00593,  2= 953000    ".
    % # 12.01.2009. *  70
100
.  % # ! &.
?  32  %.. @' 1000  $.  $ C
 %    (  $    D @ !& ; 
199034,   , 9 &, 12.
  !  "   #
 $.  (Joseph E. Bogen),
%& %'   %&   *  % "%,
 + - %     % -/' 0.
  !  %&  -   %% "%,
1&  . 2+ "0 %, "  %
 +-     &'  ,
   - " !& &.     %
/ /   '&,  /   %&.
 %
  
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.   
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 %  PythonF
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
H &
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
       &$ Python
. . . . . . . . . . . . . . . . . . . . . . . . .
) #$  !   &$ Python
. . . . . . . . . . . . . . . . . . . . . . . . .
    #$     
  #    import
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2. IPython
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
D    IPython
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
J$   & &
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    # ! &
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  &   %  UNIX
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  ! 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
K  $&    &
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 $ % 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.  
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
       Python   
. . . . . . . . . . . . . . . . . . . . . . .
K$ ' 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ElementTree
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 $ % 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.     
. . . . . . . . . . . . . . . . . . . . . . . . . . .
K  $    ! 
. . . . . . . . . . . . . . . . . . . . . . . . .
  !  %
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
*    ! 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    ! 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 $ % 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
5. 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   $ 
  (   
. . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scapy
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 $       #$   Scapy
. . . . . . . . . . . . . . . . . . . . .
6. 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
) #$   & OS &$  & 
. . . . . . . . .
   ,      ,     
   (
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    &,     !
. . . . . . . . . . . . . . . . . . . . . . . .
  (
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
?   (
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  !        " 
. . . . . . . . . . . . . . . . . . . . . . . . . .
   & rsync
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
H   :  (
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
K(  , '  , '      
. . . . . . . . . .
) #$   & tarfile &  $ & (  TAR
. . . . . . . . .
) #$   & tarfile &    
 '  !  TAR
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7. SNMP
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    SNMP
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
IPython  NetSNMP
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
)       (
. . . . . . . . . . . . . . . . . . . . . . . . .
 %   '   $%     # SNMP
. . . . . . . . . . . . . . .
 $   (     SNMP
. . . . . . . . . . . . . . . . . . . . . . .
"   $ '   NetSNMP
. . . . . . . . . . . . . . . . . . . . . . . . . .
D      %  $ SNMP
. . . . . . . . . . . . . . . . . . . . . . . . . .
) & SNMP   #  & &   #Zenoss
. . . . . . . . .
8.       
. . . . . . . . . . . . . . . . . . . . . . . . . . .
 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  !     
&$ Python  UNIX
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
PyInotify
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
OS X
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
K      Red Vat Linux
. . . . . . . . . . . . . . . . . . . . . .
K    Ubuntu
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
K      Solaris
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
 $&
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
%&   (
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
) #$  Zenoss &  &
   Windows $ Linux
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9.    
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
12.    
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  &  $&
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 & &  $&
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 $ % 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
13. # $  
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   #$ & 
       
. . . . . . . . . . . . . . . .
   optparse
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   "   #$ & optparse
. . . . . . . . . . . . . . . . . . . . . .
      %      
       &$ Python
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
) & ! ( ! 
. . . . . . . . . . . . . . . . . . . . . . . .
 $ % 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
14.       
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
D  [NS    #    &$ Python
. . . . . . . . . .
) #$    L[AP &    OpenL[AP, Active
[irectory      $     &$ Python
. . . .
    %     !  ' Apache
. . . . . . . . . . .
   ]TP
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
% . & '  
. . . . . . . . . . . . . . . . . . . .
*! " 
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
   
^  &  $     '     #   #
 $  ,  &    #$  &$  Python & '
      &. ^      &,  
   $ #  &$  Python    (   
 &  ( &$ (=  
  ( '   '  #    
             $.   
    &$ $ #  #  %      
 #  , %    # $ % #    
#" , %   ' .
J %       , &  #$  &$ Python
    &  " & $ %           
&. ^ $ $,  #        (  "& ,
 & &    &$  Python        
,     $ #, %          &    .
K , ;  +Noah-  Y'   +`eremy-,   #  #   
    &$ Python,   %   &
!        &. ^ ( '      $
     # .
Y      &       &$   
& Python &  (      + (-,  
 $   . ^  "  &     &$ Python
    &,         $ $   . ^  
, % '  "       $ #   #  
(   .    &    
 %  # ,  & 
        
    ', SN
MP         &,   %     ( 
& ( & &  #  
# $ %,   
        & '   .
  
  !    $
     #$ &    !   " &:
3 
   & &   ,    URL,     
    % ,   !   ( " &.
 
) #$ & & !  &     , &  $% 
&    (  (    ,       (
 ! , $ (,  
(,    ( ' &,
  , % (  ,      .
  
) #$ & &   &      , 
'    #&  #$   .
  
) #$ & &   &  ,   #$  # ' 
$  #   $% &  $% &,  & 
  .
@       & &   ,   ' &   %
&   ( .
@       & &   ' &     ' 
&.
+         
Y&  $ $ # 
   #   "  "( $ %.
    '     #$  #      
 $      (  (     .   '
 #&  $  #  $ $ "  ,      #
  $  #     %
    . ; ,
  $      #$      # 
      $ ,   '  #& $ $
 
 "  .   % 
'     &  
     $   
   (   % # $ " 
 $  #  OReilly. Y&   &     
   $   $?&   (      %  $ 
" &    &.   %     ( ?    
      $         "  
  
-0"%
 % # $ "  $  # .
H    ,      & #       %
   .        %   $  
 $   , $  # 
 ISBN. ; : Python for Unix
and Linux System Administration by Noah Gift and `eremy M. `ones. qo
pyright 2008 Noah Gift and `eremy M. `ones, 9780596515829.
  %   $ " &   #$  $% #( ?  
       $     #    :
[email protected]
Safari
Books Online
{   ' (%     #  
Safari
Books Online,  $% , %   
  %  $ OReilly Network Safari Bookshelf.
Safari     %"  "  , %     .
|  #&  ,  $ &&  $   (  # &%
%"( (%  ( ,  $ #
  & #   , $
' #   (  #    ,     &  
 &   '& ! &.          
http:44
safari.oreilly.com
   % $
       ' &, &   , 
#  $  #  :
OReilly Media
1005 Gravenstein Vighway North
Sebastopol, qA 95472
8009989938 +   ( }  ( K      -
7078290515 + '  -
7078290104 +! -
  % , !   
     # 
!      :
http:44www.oreilly.com4978569;668=9
   ' &     (%   (  & 
  :
[email protected]
 
Y   # !  (, ' &, ~     
$  #  OReilly     :
http:44www.oreilly.com
,   
 -
/        & ( % % #   Y' $ ! {. J 
  +`oseph E. Bogen-,   %  %   ,  $ 
 #" &   &     ,      #"  
 (  . ^     J  ,      ! qal
tech,     $    , &     '$ 
  &, (  ,   
,    ,   
&     $&    ( (  &(. |   
" %   ,   &     %,  &      .
   # & "      . ^  %  , %  
 '  %  # =    #   &  &  #"    .
^ ( %  $ #    '  /  +Leah-,   %"  $  (
' ,   %"(&  . J $      '   
  #   #   . @  ,   . ^  #
 #"       '$, &  &. ^  ' ( %   
 #    / +Liam-,       , $ , % 
 ,   &       . H " # #  $ # 
" $& & $     ,  
 & '    #   
$  #" ,    #  $  .
H   " : &  &  ( %  $ #  , %   
  &   &.
  % ' , & ( %  $ #  Y'   H. Y'  +`eremy M. `o
nes-,      $ , %  &  #     
  . ^ , $   %# %&  . D  $
 ,      &  ,    (  
" .       ( $ &$ Python  
&  & (  "       .  
@  J +Titus Brown-,    # & '   $ # 
  J ,  , $'         &$ 
Python,   &      ! qaltech. |     
 ,  ' $%   '  #  %   ,  &  %  #
      ,    "#  $   #.
    " #  &:  %     #$ "# Py
thonF. ) '  &  "     #. {   @ , &  $
   &    &$  `ava  Perl.   '  %  #
      :
http:44ivory.idyll.org4blog
D }   J   +Shannon Behrens- $  &   ,  , 
 ,    & $
&$  Python. ^  $ &
 
}     & @ ,  
   '#  . } 
   & %   ,   ( (    ,   
   ?  $ &$ Python,  ' '  $ #, 
  . {   #   , %  # &$  Python,     
          ,  & % $% &$
 $  . )   &  '  ,       #   
 $    . ^         # , &  '
  #  ,  &  #   %#        . ;  , 
    # (%  
  $  .   '  %  #
      :
http:44jjinux.blogspot.com4
{  $ $  (%  
  $    Y 
+[oug Vellmann-.   %       % #  
     $. Y'      %   $  , %
   # $ % #      "   %    
 $  .   %&   '        &
  '   .   &   &    % 
 (  &,            Racemi. 
 '  %  #       :
http:44blog.doughellmann.com4
   & (   $ #   $ #  #F
  / +Scott Leerseen- $ $    $   $   
        . ^  %     #  '
(   , $ "(&   !      . ;
  &    .
K#! Y $ +Alfredo [eza- $         # 
"  Ubuntu, &   (  &     .
@    &  % #  .
/$ Y  +Liza [aly- $ $   %       
( %    .   % $%   $.
Y' !! " +`eff Rush- $   #        Buildout,
Eggs  irualenv.
K    +Aaron Villegass-,  # $ % #  
%   Big Nerd Ranch, $         # 
 &  . H    $ , %  %  #    #&
.
H  /  +Mark Lutz-,         &  "  
% & &$  Python  
   # $ % #(
  &$  Python.
      Python  K 
  %     PyAtl:
http:44pyatl.org
    %  &.     +Rick qope
land-,  @  +Rick Thomas-, J 
   +Brandon Rhodes-, Y 
%   +[erek Richardson-, Y'   /  +`onathan La qour-,
$    '      Mr. Metaclass, Y $  +[rew
Smathers-,   +qary Vull-, J  H # +Bernard Mat
 
thews-, H  /!  +Michael Langford-     ,  & $
  & #. J        +Brandon and Rick qopeland-
         $=  && &    
   &$ Python.   '  %  #   J   
  :
http:44rhodesmill.org4brandon4
   +Grig Gheorghiu- $ , % &    
      , $         $ , %  
  ,      (  .
H    ,   (%        
 Racemi, #$ D  +qharles Watt-. ^    %&
     , %  $ ,        ' #.  
, % &       # &   ,   ' # 26#
     ( # 200 #     #  
  ,    .
Y  ;   +Nanda Ganesan-,       
 !               / 
K '   +qSULA-.     %  &    ! 
( (     '$ ,    ,  '   &  #
  & # .
Y     +qindy Veiss-    !       
  #    .     &  $ , %  
 #     ,   %  % , $ &    '$#,
 
}   J   +Sheldon Blockburger-,  $ "    
   #     &  #  !       
    (%         /  +qal
Poly SLO-. Y'  , % &    %    ,  $ 
 '  (   %  , %      %  
 ,         # $     
. )   '  # 
    $ &    
& # ! ,   %     .
J Y'. J  +Bruce `. Bell-,   &    qaltech.  % 
   # (          %  &   
, &   $&       UNIX,  & % #
$    $  .     #&   '  $  #& 
  :
http:44www.ugcs.caltech.edu4~bruce4
K#   $ +Alberto alez-,      Sony Imageworks, $
, %  ,  ', %"    $  (,   &  
 ,  $ , %      $ '  #    #   
$  #    .
H  '  !#  |  *  +Ed ]uller-,     
     & %      &.
 
J    (  , $"(       #
 ,  %& Y' !  Y  +`ennifer [avis-,    
  qaltech, &      #  ( $ =  
 # ( $         Turner Y D 
+[oug Wake-, D J   +Wayne Blanchard-,    +Sam
Allgood-, Y     +[on oravong-=  ( $      
  [isney ]eature animation,  %& }    !! +Sean Som
eroff-,   ; +Greg Neagle-  J  / +Bobby Lea-.   ;
+Greg Neagle-,  %   , % #     & %  Mac OS X.
 
  +Mike Mcqrery- $ IBM [eveloperworks $ , %    
 $ '  #   #  ! 
       $ .
^ ( %    #  '    ,   $    
  '$   , %  %    .  %   ' 
'$     &   %  ,   #    #  
&: %&   , % &       #   ',   ( 
     #,  $ %& , % &       $% #
   .   $ , %     #
%      (  % . /        #  
'$#,     &   &   &= &        # 
'    #&   # , %
   # ( %   #.
;  ,  $  #  OReilly  @ #& K  +Tatiana
Apandi- $ , %          #  #    
 &$  Python        .   ,   
   &   Y'  ,  &    $  .  # ' 
 @ #&   $  #  , %     #    % , 
   ,   ' %   #    . ^  ' (  
  #       Y'   +`ilie Steele-, & 
 '  #  $%.          &,
% % &   % #  .     &  #  " #
&      Y'    %      #   .
 % 
Y     
;  $   &  %   #
 &    %   ,   %      % &
  ,    ' ,        % 
 (,   ' (  #   $ #  .
   %  # & (    $ 
          J 
, c   #   &     #   $   & %    
   #.
K  $       %  # & (      #  
 Y  +[ebra-. @ $   ,   & 
    . @   $   !$: ;    , 
      . @     &,     
  (  ,          ,     
  #.   . ^  &. J $ & &      #
  .
^  ' (     #  ( ( ,   +Zane-  
 +`ustus- $ (     "       .
^     #" %  $      &  .
^  '       #,  &   &   $
   ,  % .      #  # &   
"  \ids Rock,  (   %     . ^   
   ,      '   .   $ "
 
  . )   $ , %  #,   ", % &
 %  $ % . ^    (.
^ ( %    #  (    , #$  /  Y'  +qhar
les and Linda `ones-, $ (  '          . ;
 #"   & ( %  $ #   $ , %  &  & 
     , $ , % %  &   #         
 # #. ; #, %   &      #   &,  
  .
 ;  !  +Noah Gift-,     , $ , %  &  &
   .  $ # &' , &'  , %  & ,   
   $ ( &' (,     (  #
 #.        %     %  ,    ,
     '  %      , & ,  
 % ( $  .  , ; . |      &# 
 $ &.
^ ( %    # " 
   $  . ;  '   
  ( ,  & ( %  $    # Y  +[oug
Vellman-, Y' !  Y  +`enni
fer [avis-, }   Y'. J  
+Shannon `. Behrens-,  H Y +qhris Mc[owell-, @ 
J +Titus Brown-    / +Scott Leerseen-.   
#  . J    ,   & $(    ,   
&     '  .
        
    #   $( % $ &. +      
 & , Y' ! . { 
,  & & 
  ,
   #$      , #  &
.-    .
^ (    $ #  "   , @ #& K  +Tati
ana Apandi-  Y'   +`ulie Steele-.  $&   &  
 ,     &   
 .    % "
 ".
^  ' ( % $ #   $ #  # *    $
+]ernando Perez-    +ill ainio- $  & $
. ; #, %    #  $  # ' IPython. )  
$ IPython. J $    & '$# $#    .
 , Y  H    +[uncan McGreggor-, $   #  
   #$ &  !  Twisted. "    
% $%   $. )  , %   '   # 
  $ % #   !  . ^  #, %  #    #$ 
 #   " .
^   J  H +Bram Moolenaar-   ( (,  
        im.  %       XML, 
  " #  #,      # im.   
       & $   #  (       (
 
      ( .    im  $    & #  
 $  #  #.  .
^  ' ( %  $ #  / @ #  +Linus Torvalds-,
$ %  [ebian, $ %  Ubuntu    ,  
           Linux.  %  '   ,
 &  % ,   % 
  Linux.    %    
&          ( '       $%(
 .  .
;  ,     % 
 #" (, & ( %    #
    +Guido van Rossum-   ( (,    
  &$    & Py
thon. ^ $    $ 
"      &'    #
(   (  . Y  (  
 (      &  %  & $ &$  Python.
^$ Python            $    &  (
 ,  & %  #$  #  &$    20012002  (.
 . Python " &   " .
 Python?
{       ,   &  " #   
 #&  Perl, Bash, ksh     &$    .
   '  #$  #     # &$      
. ^$     %  $ 
&  & #  ,  
#       #   '  #,   '   $ (.
/  &$    "#    ,  $ &   #
 . ~   # &$   & & "# ,  # %
      #  '   #    . H %  ,
% Python   &            , %
   $ '  # !!   & # "  .
H '   $ #, % Python %" , %  Perl, Bash, Ruby   
  &$ F ;    % #  '  #   %   
  ,   % &     % #  &$  $ 
" &   ,  #$   .   
 ?   % # %    & #  . ^$   
 &   ( , #  
   #       
  &   .        $ #, % &$ Py
thon %" ,   ?& %,    %   Python
%"   . H  ' ?&,  %    (  "  ( 
 &  " & $ %       &.
 & %,     %   Python   (  &$ ,
    , %  % #    $% . { &$      
     #& &   !!     ,   
#  #  $   . ; '   (      #   
 &  $%  &$ ,  ' %   ' #    & 
 #    %   & F |      &  (  
   . {
       ,     
 1.   
  #&   , %    ' $ " # (.    #
&$  Python   % #  #   $    #
 &   # % ,    
  #. { &$   $ &
  %     #    ,    $ 
 #&     $    $% &.
 &$ ,  #      $% ,    $ &  " #
 ' $ %,  '     % (    .   
  & %,    
%   Python   (  &$
   &, $ % &  , %   $ &  " #
   ' $ %,   #  '  $ #.    
&    $       # ! ' , %    #
$ (   ' ! F ^$ Python    &  
 %#  " #   $ %. )    &    # ! '
, $ %# $      $   #  &  '
 IP      !   &  '  $ !  '
  +  (& &   &   $ (- $   
  &,  $   ( #  $#     &   $ 
(F  & (      '  $  #  &$ Python.
^$ Python  #$ & &  " &  #  '( $ %,  (
 $  (    #  , &   % &   
       %(        ' "(    %  (
% .  $ ' ,       &  " #   $
%,       " $ #, %  %  (   
&$   '   " # (.
   ,      &  & #  ' "  , 
      ' &      & '  # %" 
 ,   (  $ . ^$ Python      , &$
   '      ,     #  $ &
' #  '      &$    &.  
          ! ,   %
# "     '  .    &$ Python 
 #   , %  $ &  $ #&    &  &.
)   %   , %   '    # $  &   
 ,  #"   
 %&. @  $ ,   
        &$   # & ,       ,
%  $ &   #    %   #(      .
 & %,     %   Python   ( 
&$ , $ % &      %        .
J       &
&   %   .  
    $&    # $ (    &  .  
  , &$ Python     #$   .     
$  &, % ( &  &$ Python  #$ &    #
 ,           #"     $ 
  % (     . D    ,     #
     %        .
  Python?
@  #,    &       &$  Python,
        # (
!       
&$ ( Python, Perl  Bash.      $ &     #
     &$  Python
. ;'   &    
   &$ Bash,      $ '  
    $  
    $  
#!/bin/bash
for a in 1 2; do
for b in a b; do
echo "$a $b"
done
done
     !   &$ Perl:
#!/usr/bin/perl
foreach $a ('1', '2') {
foreach $b ('a', 'b') {
print "$a $b\n";
}
|      '   
. K  #     $
    
for
 &$ Python:
#!/usr/bin/env python
for a in [1, 2]:
for b in ['a', 'b']:
print a, b
Y       #$   (     Bash,
Perl  Python.  #  #$ &   &  &   &
else
,    #   && &
&& &  $   #
!    :
#!/bin/bash
if [ d "/tmp" ] ; then
echo "/tmp is a directory"
else
echo "/tmp is not a directory"
;'   &        &$ Perl:
#!/usr/bin/perl
if ( d "/tmp") {
print "/tmp is a directory\n";
else {
 1.   
print "/tmp is not a directory\n";
K '        &$ Python:
#!/usr/bin/env python
import os
if os.path.isdir("/tmp"):
print "/tmp is a directory"
else:
print "/tmp is not a directory"
{  ! ,   &   #$   (   &$  Python,
     '  ?         &  
 & +-. K  '  & #  , %  %  $ 
&  #$  # ,       (   . ;    
&& &     #   ,   # $ & % $%  
     .   $ &      $  #   
     !  #
% , ?     % 
$  ? . ^$ Bash 
 ' ,  Perl  Py
thon  ' . ;'   &  #  &$ Perl   
   :
package Server;
use strict;
sub new {
my $class = shift;
my $self = {};
$self �{IP} = shift;
$self �{HOSTNAME} = shift;
bless($self);
  Python?
 1.   
 $ ' #&  #$ &  ( $ (. ; ,  
 &
from module import *
 %  & %  &   
 .      '    #$    
    #$  #    
import
module
,    

from
module
import
resource
. )       ' 
 &           &  ' $ #   
   ' &,       # & #   
&  &  $ #,  ( & & $  ! . | 
   "    '   #    &   
 , %  $  ,     '  #  ,  & #
      #"    .
   &   
" &    # 
 #$  %"(   
  &. H %  , %   #   #$.
   &   &$  Python    $ % #&
    # Python. {   # &$  Python  "
!$     ( &      ,  "# $% ,
%    &    $ &  " #    $ %  $  
(      #    &   . ; ,   &  (
      &$ , Python   %  '   &
( ' ,  ,   # (     &  ! 
&     �   ,   %   $   
XML, $  ! ( !
 , !  &    !
    , ( & (,  #    &,
  '       &      http, ftp,
imap, smtp  nntp     . $       Python  
  '   (  ( !  #(        
    #& "  &     (   .  " 
 &'    &    %  $ # !  #
 $ '  .  #  % & , %     & &    
Python      &    # %   .     $ ' 
    % $%   $    $   (    (
   &$ Python.
        %       (  $ 
     '     Python.    '  
 , ( &(        &$  Python,  
   #" %     ,  (  )  , 
   &    .  )  ,    
http:44
pypi.python.org
,         Python +Python Package
Index, PyPI-,    '   '    #    
   #$  .     ,   #     , & $
$       3800 
.         
 IPython,     #&      ,
Storm + # ?   &   ' &,  
  #&   12-  Twisted,  &  ! , & 
  #&   5,  # 3 $& $   % 
  Python?
3800  . ;%  #$  #&
PyPI,  ' , %    
"   (   &           $(  .
H  $     &$  Python    $  $   !
  !. {    " &   Python     
import
this
,     & &  $  Y$  &$  Py
thon @   +Tim Peters-:
In [1]: import this
 1.   
|    ,     %  & &$ #
   (  &( $  &$ ,   (  , ' &,  
   %   , %  (   &$   &$ . )  % 
, %  $ % # .  $ ' ,
      # $  
  &  #$  # Python. |  !  !&     , % 
 '  &$ . )       " ' &, $
% &$ Python  (  "     & .
/  $
{  # % $&          '  $
 %      #  )  , ,  $ ' , $ 
      #  '  $% # &$ Python    
  #. ;  &     &  # Python,   
     (    #$     #
Bash  Perl. {    # (   ,   &   
! , % &$ Python % #    $% . &    
%   &,     '   , %     
&$ & $% &    &,  % 
{  ' $   &$  Python  %   &    
     &$ ,   &   ' &  %
      $  ( ,  % &    ,  
$  #&  "(  (. H  #  $  #  , 
   #      & #    .  
  &         %   ' &    
       # SNMP,
 $ &    
  %  Python  $  IPython, $    
  (,      &       
#    ?   &   ' &,  (  ' 
,                 .
{    &    &  &$     
 % ,  '  %    #&.   '      
  Python.  ' "# '  % #&,   & &
      "  # ' ! ,     
$& #         %  #   .
H   , %     #     .  $ ' , % # $  ,
%  "   ,  .    
 ,     $'  , %     
% #&   ,  # $
&   &  . ;  
   '   ' % #&    #.   , 
   ' $'      , % #  %   
!  #  $ &    !     %  
   # $   .    ( (  
(        $      .
    (   
 &$ Python   &  

 !  #         !  !, ' 
,       &$ . ;%  #  $ 
&  && & &$ #     &  & Python, ( &
      .
{  $   '        $ % &
 , %     ' % #& #      
 $ . &   $ & (  "  & %   #  &, 
  %  #    #       ,  (  (
$& #&    ,  
  ,    !. % #
  $ % # $%   
 &     $ , 
 $  && &  &   
  &$  Python.  
Python   "  &   ',       & .  
$ %      %   '    , 
    ,  %   $  " 20, 30, 40 
 '  #" .
{  #     ,  $  #, %  , ' 
 %  #,  #    
 ,       (.
{   " $& #    ,  $   #$ 
 &$  Python         UNIX  Linux,
$% ,  '   &   ,   & #     
    % . |       &  ,  "   #
    &$ Python. ;% $   (   
&      , %  (  &    &
Python. {    , % % #     &$
Python,   $ '   (     $ . {
   #   &,    %   $   $   
 &  , %   (  #      &$
Python. |   #   ,       "  ,
 $  " '$#.
|    &$ Python # % &     , . .
    #$  #      %   $  IPy
thon  %     %  Bash.  '  
 #    ,        %  Bash  
        %  IPython.  '     
  #,   & &   '  &    #
Python     # Bash. Y& % $$     
      %  IPython &    !     
.  % #  '   
http:44ipython.scipy.org4moin4
Download
. {    %    '  % #   
  # IPython,  '  #$  # %     
 %      Python.   '  ' $$ #  
#  ",  %   &      $ 
,   '   #         
 1.   
    %  IPython.    %       
ipython
,         " &  .
 #   %  IPython       $ ,  '
  #     :
[ngiftYMacintosh ^][H:106^9][`:0]# ipython
Python 2.5.1 (r251:5q86z, `an 1^ 2008, 19:z5:1^)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2 An enhanced Interactive Python.
| � Introduction and overview of IPython's features.
%~uickre�f uick reference.
help � Python's own help system.
object| � Details about 'object'. |object also works, || prints more.
In [1]:
)  &   %  IPython
  %  
  %  Bash   '  & #    , 

pwd
            & IPython.
|    &  $%  Python.
          %  Python    
  :
In [1]: print "I can program in Python"
I can program in Python
         %  Bash     
 :
[ngiftYMacintosh ^][H:10688][`:0]# echo "I can program in Bash"
I can program in Bash
  ( (  (   &    ( $%  ' 
Python  Bash. H  &, %    ' " # Python % 
 $ %  .
     "  $ Python
{  (  &   # $% # % #      
   , $% ,  ' (  #  & #  
  ,  $ ' ,   & #   !   (  
  UNIX.    &   &    Bash,
$      & , 
&   Python.   
      %  Bash      :
[ngiftYMacintosh ^][H:10^01][`:0]# ls l /tmp/
total 0
rw r r 1 ngift wheel 0 Apr ^ 00:26 file.txt
          %  Python    
  :
     !" Python
In [2]: import subprocess
In [z]: subprocess.call(["ls"," l ","/tmp/"])
total 0
rw r r 1 ngift wheel 0 Apr ^ 00:26 file.txt
Out[z]: 0
        %  Bash  '  &   & &(, 
  %&  
,  ,        ( 
 #    #&      &$ Python,  
      %  Python  &   ' &    
 .       #: |  % $  
import
sub
process
F.  $ ( '(      Python $ % &
   $ '       # 
   !,  
'     #$    (  (. {
 $    &
source
 Bash,      
(     .        % '  & #, %  
     # subprocess 
 #$        
 %     ,  $  " .    , 
 
subprocess

import
,   '   $' ,       $
 #& ,  %      &   ,   &  
    :
subprocess.call(["-", "-  ", "_-  __ 3"])
)$ Python  '   #      % ,   
  &#      %  Bash. D% &   ! 
,  '     #    
 &$ Python. 
    %  # 
         
  ,  $  !    
pyls.py
    
 &     #  
chmod
pyls.py
.  ' !
  &    1.1.
% .. 2  %"+ ls  #+  Python
#!/usr/bin/env python
#G  - ls   Python
import subprocess
subprocess.call(["ls"," l"])
{  # $  #   
,   % '   
$#  , %   $  
$      :
[ngiftYMacintosh ^][H:10^q6][`:0]# ./pyls.py
total 8
rwxr xr x 1 ngift staff 115 Apr ^ 12:5^ pyls.py
|    '  $ #&  +      && &-,  
&     % 
   Python      
  . ^$ Python %  #$ & &   
& (      UNIX. @  #  '   
 1.   
% #  #     '
 ,   &  ! 
   $  .  
    ,   
$         .   '       #
 '   1.2,    #  
psysinfo.py

ba�sh
sysinfo.py
,   '     (    .
% .=. ?A &   %A  % Python
#!/usr/bin/env python
#Q  +  -Q   -
import subprocess
#- 1
uname = "uname"
uname_arg = " a"
print "athering system information with %s command:\n" % uname
subprocess.call([uname, uname_arg])
#- 2
diskspace = "df"
diskspace_arg = " h"
print "athering diskspace information %s command:\n" % diskspace
subprocess.call([diskspace, diskspace_arg])
% .F. ?A &   %A  % Bash
#!/usr/bin/env bash
#Q  +  -Q   -
#- 1
UNAME="uname a"
printf "athering system information with the $UNAME command: \n\n"
$UNAME
#- 2
DISSPACE="df h"
printf "athering diskspace information with the $DISSPACE command: \n\n"
$DISSPACE
{  #   #   &,  ' $  #, % 
% #  ( '. K  $  # (,    %    %  
$#  . H #  % :    #  ! 
subpro
cess.call
  # 
    "   &$ # .
H '  #$  #, 
,   !  $:
subprocess.call("df h", shell=True)
 $ % # ,     ?&,      &
import
 % $  &   &  #
subprocess
.     &
 &$ Python         &
subprocess
. .   '   ,  $ &  & # $ 
  .
     !" Python
 '   #  ,   &  #
subprocess
,   
    !,  '  (     .
  '  $  #        #,  !,     
  #$  #  
  ,   & 
%  ' ,         $  &
sub
process
.       % 
 %  ,     $# 
      %    &'  !   
     .  $
$ % #(       
     %  IPython          $&  #
 #     !    % #    (   . {
    #  UNIX,       
   
4usr4bin
. ; ,   $#       , 
  Ubuntu  Solaris,      #  Red Vat,   
'   #  
   
4usr4bin
, %  $ #  
 1.   
 ' # "
Tab
, %   $  # !     
&, &    (   .   #   
"     ' $  #
subprocess.call
. @  #, %   
% #   # !    #$ 
subprocess.call
   :
In [1z]: subprocess.call|
Type: function
Base Class: type 'function'�
String Form: function call at 0x561z^�0
Namespace: Interactive
File: /System/ibrary/Frameworks/Python.framework/ersions/2.5/lib/
python2.5/
subprocess.py
Definition: subprocess.call(*popenargs, **kwargs)
Docstring:
#$"   !" Python
     .     $   $ ,  $  #
        #     ! .
+   ! "  $ Python
     $   $,   & &   , %
     #   $ , . .  $% , %     & 
 $  #     (  ,  #"
 &# %.   "  "    
   $   $ 
! . {    $ 
 ! &  &$ Bash       &$  
 &,     & (     .
*   $ &  $  #     ,   
 . |     ( ' 
  Bash  &  ,
   .  $
%     , %   ' 
 % #     '  
! .   %  %  '
 #    &   ' #  ! &(  $  $
  #      '  &     .
@  #    &     # 
 (.  &$ Python   ,
  '     '      , '
 #    .  ( &$ (,  (  Bash,  
 & & ! &,  $ % &  !   .  &$
Python        ( '  #    .
|  '  #    (, # % $% # &$ , 
%  $    &     %    $  , % 
       &  "   %    #   
. {        $     &
& & " ,   # & %, %  ( (  ( 
#     . %  "    
 %     .
 ,    !   &$ Python  Bash. {  
  '      &
  %  IPython,   ' 
 $  # !  &  &$ Python, ( &     $& &.
          " &   %  IPy
thon:
In [1]: def pyfunc():
...: print "Hello function"
...:
...:
In [2]: pyfunc
Out[2]: function pyfunc at 0x2d50^0�
In [z]: pyfunc()
Hello function
In [q]: for i in range(5):
 1.   
...: pyfunc()
...:
...:
Hello function
Hello function
Hello function
Hello function
Hello function
       &
print
     ! . @  #  '
 # $ #   !   $  ,   $ #  # $,
 #    &.   
[q]
  #$     + -
&   & !  & # $. { #"      
  %&,    #  & #, %  $ !  & # $.
@ '   '   #  
          %
Bash. ;'    &  $    :
bash z.2$ function shfunc()
� printf "Hello function\n"
bash z.2$ for (( i=0 ; i 5 ; i))
� do
� shfunc
� done
Hello function
Hello function
Hello function
Hello function
Hello function
    &$ Bash   $    & ! 
shfunc
, 
& $   $ & # $, %  ' ,     
  !       &$ Python.  % # , %
   &$ Bash     #  #" ', %   
$  # '  , %   &$ Python.     
%&  
for
 &$ Bash  
for
 &$ Python. { 
"  &   %  ! &  Bash  Python,     
'& #&   $   ( # ( !    IPy
thon,  ' %   #& #" .
 ! &(  %    
 ,      #   #
!         %
  '     #  
      % ,   "       ! &
. ;'   &       ( ! :
In [1]: def print_many():
...: print "Hello function"
...: print "Hi again function"
...: print "Sick of me yet"
...:
#$"   !" Python
...:
In [2]: print_many()
Hello function
Hi again function
Sick of me yet
In [z]: def addition():
...: sum = 11
...: print "1 1 = %s" % sum
...:
...:
In [q]: addition()
1 1 = 2
)  ,   $  %  & 
 #   "(     
 (, %        # ,    F @  # 
 '    #&  ,    !   
  $  #       ! ,   $   
 1.4.
% .G. - #+& A & -   %A  %
 #+  Python: pysysinfo_func.py
#!/usr/bin/env python
#Q  +  -Q   -
import subprocess
#- 1
def uname_func():
uname = "uname"
uname_arg = " a"
print "athering system information with %s command:\n" % uname
subprocess.call([uname, uname_arg])
#- 2
def disk_func():
diskspace = "df"
diskspace_arg = " h"
print "athering diskspace information %s command:\n" % diskspace
subprocess.call([diskspace, diskspace_arg])
# Q,     3 Q
def main():
uname_func()
disk_func()
main()
D% & "       ! &,  '  $ #, %  
$         &  #  , %   
         # !   $  $  (
$     #   ! . {   $    
 1.   
     &,  ,  $ ' ,   $ , %  
 %      ,      &  $  &
  # ! ,  $   $ & $     ! 
.  $  '   % &   $     ,
% ,     "  #$  #        
 ,   '  #, $ #  !   #   
   #   ! .  #
 , %  "   &
   ,   #     .
        &     &   
! ,  #   
 & &     ,   &
   &  &. |  '  #    ( &  $ (
  ,        $  #       
    #$ &,   %"   #$  # ! , 
 $ %        &,     #
 $    ! , &   & #   
  .
Y&  &  '  #$ 
!  &      
&  &$ Bash,  &    !    , 
 $    1.5.
% .6. - #+& A & -   %A  %
 #+  Bash: bashsysinfo_func.sh
#!/usr/bin/env bash
#Q  +  -Q   -
#- 1
function uname_func ()
UNAME="uname a"
printf "athering system information with the $UNAME command: \n\n"
$UNAME
#- 2
function disk_func ()
DISSPACE="df h"
printf "athering diskspace information with the $DISSPACE command:
\n\n"
$DISSPACE
function main ()
uname_func
disk_func
main
  $"      %$&   import
$&  "  
 &$ Bash,  ' $  #   ( 
'    %      &$ Python.  #  '  $
  ! ,  $  $ & $   ! .
{  "       ! &,       
   #  $     # $    !    (
 &(,     %       "  +
-,     
 # $  # (  $. ;  $   $#  $    
  '  % #   %  %  ,   %  
( &   & &,   
$    ! .
@  #   ' %  #  &   ,     #
   !    ( &$ (, Bash  Python.   
% &  &,     %   & #       $
  #   (  (,  &$ Bash  Python, $   
(    
  . #     # % ,
        #  ( !     
  ( $  $   ! .
      
  :;    import
 $        %          , % 
     %   &  #,  % #  '   
   .        
$  (  #  & # $
    ,  %      "  ,      $
 F    (  (   $ ,   $  # ! ,
   & #         #  
      % . H  '  , %  # 
%      %        
  ! .     (  %   '  ,   
'   # $        , %    '
     #$  #   (  (.    $ 
  '  ,  %    ' . Y     
  (  &   !       (.
    IPython  Bash,   $  (, %    
       #,  %  !     '
 #  %  $ &      #$ &    .
 $ "(  (   
 &$ Python   &   
      #  #   !    
pysysinfo.py
&$ Python ! && &        ,      
'      #  !  &    %  IPython.  
 ,      '  $ # " 
.py
!
     . * %         % &  
 % ,  "    $ . )  ,     
 &     ;  Macbook Pro:
 1.   
In [1]: import pysysinfo
athering system information with uname command:
Darwin Macintosh 8.local 9.2.2 Darwin ernel ersion 9.2.2: /
Tue Mar q 21:1^:zq PST 2008; root:xnu 1228.q.z11/REEASE_Iz86 iz86
athering diskspace information df command:
Filesystem Sie Used Avail Capacity Mounted on
/dev/disk0s2 9zi 88i q.2i 96% /
devfs 110i 110i 0Bi 100% /dev
fdesc 1.0i 1.0i 0Bi 100% /dev
  $"      %$&   import
 % $& #  (    .    
pysysinfo_func.py
            
   :
# Q,     3 Q
def main():
uname_func()
disk_func()
main()
    , % ! &
main
,  $ &      
  $ ,  # &      &   #.   
  , (  #   #  $ '  # $  #   $ 
     , %   % #   !    , 
     ,      ' , %   #   % 
     .  % #,
    #  #$  #  
     ,  & ( $      ,    
    #$ (    
 % %   % &  &$
Python.  "           , %    #, 
    $ #  ! , $     % #
 &,   $ ' :
# Q,     3 Q
def main():
uname_func()
disk_func()
if __name__ == "__main__":
main()
|       &  ,  %  #$ & &
 " &     . /    , ( &   
           ,   & #&, # 
   # $  & $      .    #&   ,
$  %    &      
   
pysysinfo_func_=.py
{  #   #&   % IPython      #  
 ,  '  #   :
In [1]: import pysysinfo_func_2
;  $  & "  & ! &
main
$ 
. )  ,   &  # 
     #$ &  
  :    &  ! ,   '  #$ 
 #  (  (  $ #        %
IPython.   :     , %     (  #
 $ '  # $ # # ! , &   ! 
         . %  (   #
  #&   $  $ '     %  IPython,   '
     .   ,    #$  "
Tab
 1.   
&  % &          &,  ( & 
 #$ &. ;'  $ ,  &    & " 
 &:
In [2]: pysysinfo_func_2.
pysysinfo_func_2.__builtins__ pysysinfo_func_2.disk_func
pysysinfo_func_2.__class__ pysysinfo_func_2.main
pysysinfo_func_2.__delattr__ pysysinfo_func_2.py
pysysinfo_func_2.__dict__ pysysinfo_func_2.pyc
pysysinfo_func_2.__doc__ pysysinfo_func_2.subprocess
pysysinfo_func_2.__file__ pysysinfo_func_2.uname_func
  $"      %$&   import
Darwin Macintosh 8.local 9.2.2 Darwin ernel ersion 9.2.2:
Tue Mar q 21:1^:zq PST 2008; root:xnu 1228.q.z11/REEASE_Iz86 iz86
athering diskspace information df command:
Filesystem Sie Used Avail Capacity Mounted on
/dev/disk0s2 9zi 88i q.2i 96% /
devfs 110i 110i 0Bi 100% /dev
fdesc 1.0i 1.0i 0Bi 100% /dev
 1.   
   $   $,  #     '  #  $ '
  #      #$ &    ,   #  
  #$  #.  (  (:       ! 
!  $ ,     &  #  $ '  # $  #  
 $      ,  #$  #   % 
    
if__name__
"__main__":
.      ' 
    #   !     % IPython,     #
$  # (     .  &   !  ,    
#   &  . @  #   '  $  #  &$
Python  #  '     #$  # (      
 $   (    .
  $ #(    &$  Python && &    
   ,    % .   %    %  $ '  #
     #  ,     # !  #  $ ' 
    !    ,      ,    # 
      &, & (    % 
" #   #   $  (   . %    
  &$ Python            
   %  Python +   #     %  IPython,   
      &-, $  &    ,   %
&# $    '    %      , % & !
       $  
   .     (
  '      & #          
   & #      '  !     
     .
     IPython   &         % 
Python. |    #&   %        " 
 $ '  &                %
 Python.   $ &  $ 
#   ' &,  
    # " (  (=   $ '  #   # 
    %  Python    '  ,  
&$ Python ,    
% &,  ' ' 
 #$  #&  %           % .    
   &   #$  IPython   #  " & !! 
    " & $ %, &$
(       &$
Python  nix   % (.
   %  IPython    #  %      .   '
  #&   %      
http:44lists.ipython.sci�
py.org4mailman4listinfo4ipython�user
.    $ % #&  
   +wiki-
http:44ipython.scipy.org4moin
. )  % #    
 2. IPython
      
http:44ipython.scipy.org4moin4Cookbook
  $  (      ' %  # !     
 #  . {   #,    '     #  ' #
  $&   &,  $  IPython. ;  $ 
IPython       
#$       
 &  & ( (  ,  &     ' 
 % #  $ ( (  
   # ( $% . {
   %  , %  ' 
 #& ,   '   
 #    $  &.
  IPython
     #   
   IPython.  , 
  , $ % &   %      ( 
 .  ,    ' $$ # IPython, (  & 
  
http:44ipython.scipy.org4dist4
.      &  (  
      & IPython 0.8.2  $# $ "   
    0.8.3.     # IPython $ ( (  , 
   
http:44ipython.scipy.org4dist4ipython�5.8.=.tar.gz
 $
$ !
.tar.gz
.   #  !  '    # 

0.8.2.tar.g
.  $(      
     :   IPYTHON
  (Fernando Perez)
*    $  
 !$   % 
 (  , $& $  % ( 
     !         
    "     .   &  
& $ & % $ &   
       |  D +Velen Wills-
!        J  
,   %"#  $  (   $ &
'   &  $   & #       
(    #(    & %( % .   
   %& % &  
   $&   % 
$     #(    & %( % 
 &$ Python.  % 
IPython  2001  ,   
& $  # !! 
      &
 " &    ( %(
$ %. J & "&
 &  $ %     '    $
      &     ,     $  
'   ,   %(  .
' IPython
 ' #& !
setup.py
. $      Python,   
 & !
setup.py
   
install
+ ,
python
     :   IPYTHON
  (Ville Vainio)
   %   #   ! 
    2003          
  (  ,  (  %   ! #
    , *& &.      % 
        &  %    
     !    [igia Plc,
 $   
   %  
&$ q &  !  Symbian OS, $   
& Nokia  UIQ.   & %      
qimcorp Oy, $      %   &$
Python & $  &   "    .
   '   IPython,
  2006     (
   #    IPython + & 0.x-. {     
IPython %#       %"  IPython
%          %  & Windows,   
&           %  (     &
    &.             
 , *& &,  "      % 
          ! (  %    
  mail protected]  ,  &  ILeo,  && &  
     '  IPython  Leo    Leo    
        '  IPython.
 2. IPython
    
4usr4bin4python
  &  %  & 
 !
ipython
@       IPython $ % &   #$  
 Python.    '  
  #, %  Python   
 &  #,   , ,   
 ,   .    &$ Py
thon  !  "  
.egg
,   &    (
!   ZIP.    '   #    #   
easy_install
.  $ $ % #(        
easy_in
stall
$ % &  , %    &   #   $ 
      ( 
 .    ( 
  #  #" , %  #    ,  &  #$  &
     & & % #  
.   $  $ &  
     Python +Python Package Index-,  PyPI &   
+( &    ' $  Python qheeseShop +& 
 Python--.    #$  #&   
easy_install
,  ( 
 $    #&     %   $#, & 
   $    
site�packages
,  $  #  
easy_install
ipython
    $ % &   #$  IPython    $
   . F,  '  
 #. Y   , %  $
$ #     (       $  #  
ipython.py
$           ! ,   % 
   $ & $'     IPython. |     
,  '  $  '  #     
site�packages
, ( &
  & %  #   % &    . {
 $  IPython $   ,      !  
 ,      $
     ' &
PTHONPATH
  '  #$  #      .
, $ $
      %  IPython     ,      $
$   
ipython
,        :
jmjonesYdink:$ ipython
**********************************************************************
elcome to IPython. I will try to create a personal configuration directory
where you can customie many aspects of IPython's functionality in:
(J+  3  IPython.  +@  3  3  
  -,   -   3     IPython:)
/home/jmjones/.ipython
Successful installation!
(&    +!)
Please read the sections 'Initial Configuration' and 'uick Tips' in the
IPython manual (there are both HTM and PDF versions supplied with the
(" !!
distribution) to make sure that your system environment is properly
configured to take advantage of IPython's features.
(  ,     'Initial Configuration'  'uick Tips'
    IPython (    +  X  HTM,   PDF
 ),  + - 3 +  3,    -      -
+-  3 IPython)
Important note: the configuration system has changed! The old system is
 2. IPython
"(  .    $ #     # , %   ( 
   #.       %
IPython     !  
#  $ '   &$  Python.    # %  (
!  IPython.      #  ' $  #   
UNIX    % IPython   ( #        Python.  
      , %  ' '  # IPython  
      %.
;'   &     &  (   (  
&:
In [1]: a = 1
In [2]: b = 2
In [z]: c = z
        ( %          
 %      Python,        '   .
 #      $% & 1, 2  3     a, b  c,  
    .   #" %  '  IPython        
 %  Python,   '   # $ #,     , %
  %  IPython    &        " &
 .
@  #,      &   
#    ( +a, b  c-, 
   $% & +1, 2  3,      -,  '   
 #,     $% &   ' :
In [q]: print a
In [5]: print b
In [6]: print c
  % ,     ,   %  # %    
$% &,   '     # $  , %  (  #.
 $% & '      
        
 "  #     #" , %     #  (  . ;'
  &        ' & $%     (:
In [^]: a
Out[^]: 1
In [8]: b
Out[8]: 2
In [9]: c
Out[9]: z
;  &  , %  $#   
( (     & &  
%    ,     , $ #   &   $
(" !!
%&. )  &
print
 #$  !#     
   ,      #$    #     
     & !#        . %
$  '    &    &   $   
    ,     
 . ;'   &
  $%  '    &       &:
In [10]: class DoubleRep(object):
....: def __str__(self):
....: return "Hi, I'm a __str__"
....: def __repr__(self):
....: return "Hi, I'm a __repr__"
....:
....:
In [11]: dr = DoubleRep()
In [12]: print dr
Hi, I'm a __str__
In [1z]: dr
Out[1z]: Hi, I'm a __repr__
 #   #    $%  '  !#   
!#      
 & ?   $  & 
DoubleRep
,   &  
__str__

__repr__
.  #
 
__str__
?  $ &,     &  % # 
 !#        .  # 
__repr__
?  $ &,     &  % #  !
#        .    $ &  $ & 
DoubleRep
 &   %   $% &     

  $% 
   #   
print
. $ & 
__str__
.      " &        &  
   ,   $#  %  $ & 
__repr__
. @  
$ ,        & 
   ,   %  IPython  
 !#        .      #$ 
  
print
,  %   !#      
  .    &$ Python 
__str__
$ &,    
(    ! 
str(obj)
,      & '  
? ,      #$ &    !   &,  
  :
"%s"
obj
.     (    ! 
repr(obj)
  #$ &    !   &,  & 
"%r"
obj
, $
 & 
__repr__
    ,   (    &  && &    
 #  % #   %  IPython. |     #   & 
   Python. ;'   & '     #$ 
& 
DoubleRep
            % Python:
��� class DoubleRep(object):
... def __str__(self):
 2. IPython
(" !!
Out[2]: 1
In [z]: print a
In [q]:
K  #         % Python:
��� a = 1
��� a
��� print a
   #      ( $%  '  ,     %
( IPython  Python  & &  .    %    
   & "   
. ; !#   
            % IPython          %
Python ' &  $ .    % IPython   &
    $ 
Out
,       % Python     &
$%      .  % '  #$ &   
print
  ( $%    &   (   % (   &
# $%  .
;%   $
[  
]:

Out
[  
]:
 '
$ #   :   &     #     $%&
 '  IPython         %  Python,    &  
% #  %   ( .    , $%&  
' . @  #   %&        %  Python 
   !  #  $ '  &   %  IPython.
   % IPython   &         ,    
   (  $ #. |       

Out
& $ (   & ?  ,     (& &  
  ,   & ?  &.  %     
& ! &
type
'  $ (:
In [1]: type(In)
Out[1]: class 'IPython.iplib.Inputis�t'
In [2]: type(Out)
Out[2]: type 'dict'�
    %  #$  #&    

Out
,   $%&
 '        $%  .
)  , % ' ( &   (    (F
In [z]: print In
['\n', u'type(In)\n', u'type(Out)\n', u'print In\n']
In [q]: print Out
{1: class 'IPython.iplib.Inputist'�, 2: type 'dic�t'}
 2. IPython
    '  #,    

Out
 ' ,     
 , %
None
   '    $#     
&     '  .   #  ' &       
 '    , 
     (& #  
         ,   . ;  ( 
       '     &     , 
  ' # $% 
None
.   , . .  ' &  
&    $ $%  , %
None
,  #   (
& #        (,   #.
 
Y&    &    $&     # IPython ! &   
&, &$& " &.    &   %  Py
thon  '   !     &   , %  
        '    readline,  &
   (    #    &:
��� import rlcompleter, readline
(" !!
|     "#   
  $ '  #      
 &       % IPython,  IPython, %  ' $ #&
    #,  '  & #          
    &.       %  IPython, %   '
   #,  IPython      #    
 #:
In [1]: import o
opcode operator optparse os os2emxpath ossaudiodev
In [1]: import xm
xml xmllib xmlrpclib
   , %   
     & &&
 &     ,  #  '  %    . |
!  #&     #.
   % IPython  #      &:      
    &.   #$       
   & &     $ '    $    &   
% # #  ,     
    & &    #
  $ #  ,  '    '  "
Tab
  & !       #  . 
 %    % IPython  #$ &     .
       IPython     % #   .
 $ ! $    $
  && , &&   ,   $   ,
  #& ! &
edit
. +     #( ! &(
         $  .- $    #$  &
   % ,       ,    ,  
%  $%  . @    
'  &    $%,
    $  #  .  $ '  #        
$ $ % #  .     ,    %   & ,
%     (  & '  # 
  &,     
  ,            .
    %      %   (  .    #  
     $  &   % !!  . ;     $
   (   #    $      . J    
(  #  $ '  #  #$  # &     %    
   , ( &  % 
$ '  #   &  '
 IPython. H ' $ ,   #$  #    
  &  $ &     &$ Python,       , %
    . H  $        ' 
  %                     
     ,    %  $ '  #    # 
     %         . {  '  
$ #, %    '   $ '         
 2. IPython
    " ,  $% , %   %       ! 
   % &. @. .  '  $ #, %   %   
   !   % #   ,   '  & 
  % &.
 #& ! &
edit
 $    &     & 
"    '    %           
   % Python          %        
.           &  , %   
%         $ '    (        
&.  "   &'    &      "  
       .     '     #  
     $ & #  
   (   ,   
! .      " #          
     $  &    % .     (
(  (    #"  (   ' #   . 
 %  $ '  # & #    % '     
    $   % ,   '    #  ,   
  #   & #  
$      . 
 $         %       $  &,
          .
-  " IPython
  && $  ,      $ #,   & 
    IPython. {    $      '    
  $   %  IPython,   $    
.ipython
 "  
"     .     
.ipython
 & !    
ipy_user_conf.py
. | % !  !  #$  
&,    (& &    , !       % 
 (     &$ Python.  !  ! (
 #" $ $    ,  $ &(   #  "
  !  #  $ ' 
 IPython   &. ; ,
 &  $ '  #  #    &   % ,  
 #        " &   #     ,
   %     #$  #& !  
%edit
&
   . H    & #&   & &.   $ ,
%   !  !         , % 
 $  #&    ',  $ ' ,     
   ,     & $  #.
     ! $
  '   ,   %  IPython    # " 
 $ '  &. @ & "     %     
  %   (  #(
! . @ % '   
#& ! &F     IPython    &:
)    $ !
  %  IPython      , %&
 
,  $   #  ! . |  !   
$ & & #     
    %  IPython  &
 &      &      .     #(
!  % &   
,         &
 $  #$ & (    % .
 :     
'%cd mydir'
+ $ % - $  
 %     mydir,        .
   #  $  #&      $   #(  $
 '         
# ! .  &  
#&  %& ! &,    ,  ! &
lsmagic
. * &
lsmagic
    (  #( ! 
. ;'   &  $#    ! 
lsmagic
In [1]: lsmagic
Available magic functions:
%Exit %Pprint %uit %alias %autocall %autoindent %automagic %bg
%bookmark %cd %clear %color_info %colors %cpaste %debug %dhist %dirs
%doctest_mode %ed %edit %env %exit %hist %history %logoff %logon
%logstart %logstate %logstop %lsmagic %macro %magic %p %page %pdb
%pdef %pdoc %pfile %pinfo %popd %profile %prun %psearch %psource
 2. IPython
    #  
TAB
  $#   !   
 69  #( ! .    , ! &
lsmagic
 &
TAB
 $ &     % #   (  
(&  #( ! ,     %    
 %  $  #&  , %    . ;   $ 
&     &   %#   & #, & %   $%  '
& ! &.
 #     #  &  #&  %& ! 
&. |  ! & $ &
. * &
magic
 $ &  % #
 %   (  #( ! ,   (   
 %  IPython.   % !   % & & ! ,
 &  #$ & +  #   &-   
 & ! . ;'   &  ! 
page
%page:
)    $ !
Docstring:
 2. IPython
(   -    - X   Q3X QX
   -X -X)
files = !ls /usr : Capture sytem command output
(?X    - -)
files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
 $ % &     :
%time:
Time execution of a Python statement or expression.
(G -    Q     )
%timeit:
Time execution of a Python statement or expression
(G -    Q     )
%unalias:
Remove an alias
(&  -)
%upgrade:
Upgrade your IPython installation
(+  @ IPython)
%who:
Print all interactive variables, with some minimal formatting.
(G       -   --3- -  -)
%who_ls:
 ! * UNIX
Print all interactive variables, with some minimal formatting.
(G       -   --3- -  -)
If any arguments are given, only variables whose type matches one of
these are printed. For example:
(V   + - , +      -  3
   @7  . - :)
%who function str
will only list functions and strings, excluding all other types of
variables. To find the proper type names, simply use type(var) at
a command line to see how python prints type names. For example:
(  3 -  Q   X   - X, @   - 
@+X X . 4 +   3  + - - ,   3
- type(var),     -    Python. - :)
In [1]: type('hello')
Out[1]: type 'str�'
indicates that the type name for strings is 'str'.
( ,          -  - 'str')
%who always excludes executed names loaded through your configuration
file and things which are internal to IPython.
(%who   @  - - ,  
  Q ,  - ,
@7    - 7 - IPython.)
This is deliberate, as typically you may load many modules and the
purpose of %who is to show you only what you've manually defined.
(  K   -  ,   - + 3   -  
- ,    Q %who    -,  +  3
3 - ,     @.)
 %& ! & ! 
%who
,   &  
! 
%~uickref
,    #   %       $ 
Doc
string
  ! , &  $ &  
%who
# $ ' UNIX
D         % UNIX  #       +$ 
(  ' $ # !   (  "    ,  
       ,   %         ,
        ,         -, 
&      $ % #  #       
  $ '   Python.   %  IPython   &     
 ,   "    # 
 &  ( (   % .
 &     # ?  &   %  Pyth�onUNIX,  
 ,   #& ! &
alias
.    #   ! 
 2. IPython
  '  $  #        (  .
   #   , 
 %      & ! 
alias
   $ #     +    
 -. ; :
 ! * UNIX
  ,  #$ &  &     #  %      
 #      , &    $  &   .
)        ( ,     , %  &
  #    #   :
 2. IPython
In [5]: store achoo
Alias stored: achoo (2, 'echo first: "%s", second: "%s"')
In [6]:
Do you really want to exit ([y]/n)|
(psa)jmjonesYdinkgutsy:code$ ipython nobanner
In [1]: achoo one two
first: one, second: two
   
Y  ,  ',           &  ( 
 $ % &   #$     #  $  +
-  
 ! * UNIX
1: jmjones 6008 0.0 0.q 21zq0 qz0q pts/1 Ss Apr11 0:02 bash
2: jmjones 8298 0.0 0.q 21296 q280 pts/2 Ss Apr11 0:0q bash
z: jmjones 1018q 0.0 0.5 226qq 5608 pts/z Ss Apr11 0:01 bash
q: jmjones 120z5 0.0 0.q 21260 q168 pts/15 Ss Apr15 0:00 bash
5: jmjones 129qz 0.0 0.q 21288 q268 pts/5 Ss Apr11 0:01 bash
6: jmjones 15^20 0.0 0.q 21z60 q268 pts/1^ Ss 02:z^ 0:00 bash
^: jmjones 18589 0.1 0.q 21z56 q260 pts/q Ss 0^:0q 0:00 bash
8: jmjones 2^^05 0.0 0.q 21z8q qz12 pts/^ Ss Apr12 0:01 bash
9: jmjones z2010 0.0 0.q 21252 q1^2 pts/6 Ss Apr12 0:00 bash
   , %  $# 
   ,  (    
, % &  $#  ,  %       
  . |  , %    &
 ' ?  ,  
           & %  
.    ?         #  $ 
    .
K#     #$   
&& &  #$  

. |  &   %  $ '  #  & #
'   &, % 
, $  %    , %   $ &  
(& #  $#       . ;
  #$   
&  $ '  #  #$  #   

_[0
,   
'  #& ' ,  $  ) &  $#  .
) #$ 

          
 &  #"  , %   $ 
   ,   ( 
%&(     %  #   $ #&   ,   
(  #$ 

. ; ,     &, %  
&     #$  #&   & , %"  $  # &
   . Y&      % #    #$ &
%"  & #

         $ &     �   &
 (  $   %  IPython,      
 #  ! 
rehash
+ &   ( "  -.  (
%   %  $ &,   $      (  ,
      ,      .  #& ! &
hash
 &       , %  ' 
     ! , 
&       ' &
PATH
. 
 '   #:  $     F.     $  
&   ,   %  IPython '       
   ,  
 '  #   .
@      $     ' &.
Y&  ( " &        %  #
 #$  #  # ! 
rehashx
,  
rehash
    !    ' ,     ,  $ 
"    &  '   %&.
 2. IPython
  &     %  IPython   &  "  &' 
 &    (,  ( 

Out
,    '   %
#  .  $  (    ( $ &
__IP
.    
&    ?       % . K    ? ,
  
alias_table
,  &    . |     ,
 (& & ' &           .
H  '     #   
 %  ' ,   
    :
In [1]: __IP.alias_table
Out[1]:
{'cat': (0, 'cat'),
'clear': (0, 'clear'),
'cp': (0, 'cp i'),
'lc': (0, 'ls F o color'),
'ldir': (0, 'ls F o color %l grep /$'),
'less': (0, 'less'),
'lf': (0, 'ls F o color %l grep '),
'lk': (0, 'ls F o color %l grep l'),
'll': (0, 'ls lF'),
'lrt': (0, 'ls lart'),
'ls': (0, 'ls F'),
'lx': (0, 'ls F o color %l grep ..x'),
'mkdir': (0, 'mkdir'),
'mv': (0, 'mv i'),
'rm': (0, 'rm i'),
'rmdir': (0, 'rmdir')}
|   &    #:
In [2]: type(__IP.alias_table)
Out[2]: type 'dict'�
  ' $ #& %,    %.
  &          & 16    :
In [z]: len(__IP.alias_table)
Out[z]: 16
  $  ! 
rehash
?   & $%
 #  %&:
In [q]: rehash
In [5]: len(__IP.alias_table)
Out[5]: 2z1q
      #    , %     ' ,  % ' 
  & #&,  #    '  & #&   
transcode
In [6]: __IP.alias_table['transcode']
Out[6]: (0, 'transcode')
 ! * UNIX
      % & &         , %
 &  (     %  & +
-,   ,
 $% , %      , %  
$ & #  '       . H  #  
   
__IP
,  # &  , %       #
        .  %  (      
   #$  #& !#     !  
+API- IPython    #& ? 
_ip
,    $ 
        %  IPython.
rehashx
 #& ! &
rehashx
        
# ! 
rehash
, $  %    , %     
  ,   % (
      ' &
PATH
,  &
      #    & ( ! .   
 $     ' #, % $   $    %  IPython   
$#    ! 
rehashx
       #
'   #" ? ,    $  ! 
rehash
In [1]: rehashx
In [2]: len(__IP.alias_table)
Out[2]: 2z0^
)   :   $  ! 
rehashx
$     
  $&   #      #" , %    $  ! 
rehash
. ;'  & &    # %:
In [z]: from sets import Set
 2. IPython
 #   , %
rmmod.utils
   
insmod.modutils
, 
ins
mod.modutils
     .
{  (  #   #         % Python, ,
 $ ' ,  $ , %      %  '   # &
  ,     (  #. H '  #$  # ! 
os.chdir()
, %       '   ,    % #   .
)&       ' $ #    # ! 
 ! * UNIX
{       # ! 
 IPython && &  $ '  #
  (       $  . +   ?&,
   $  &.-        $ ,    #
  (       $    $  :
In [1]: cd b t
(bookmark:t)� /tmp
/tmp
        &, %  &   
4tmp
  $
 $      
. * #      (      
$      :
bookmark_name
,   $  
bookmark_name
                
bookmark_name
, %
 '   #    %   % 
IPython    , %   
 #   #   (  $
 .
  &&   #&     #,    ! 
&
   % IPython, $ % &   $ '         
    ,         "(& 
  . ;'   & 
  #$ &    :
0: /home/jmjones
1: /home/jmjones/local/ideos
2: /home/jmjones/local/Music
z: /home/jmjones/local/downloads
q: /home/jmjones/local/Pictures
5: /home/jmjones/local/Projects
6: /home/jmjones/local/tmp
^: /tmp
8: /home/jmjones
In [2]: cd 6
/home/jmjones/local/tmp
    %      &     "(&  
  .    % #,        ' .    
$  ! 
,      & %    
.   
   % IPython, %    &        , 
(  &        6,  #    
4home4jmjones4
local4tmp
. )          %    , %  #  
(  #    
4home4jmjones4local4tmp
bookmark
H # %     ,   #$  # $  
! 
&   (        . K  #   
' ,   $  #   $      & #.    &
 #, % $    (& & 
'         % 
IPython. { $ " #      % ,  $   # $  #
 2. IPython
, $         .  $  # $    ' &
  . ;'    &   $ (:
In [1]: cd /tmp
/tmp
In [2]: bookmark t
   
bookmark
    (     
4tmp
,   $ 
 $      
,  $    
4tmp
.      
 $ & $          %     :
In [z]: bookmark muak /home/jmjones/local/Music
 #   $  $      
muak
, &  $   
#     $ .      & $  ,
   &   ,    & $  .
 % #  $  , (    &       
  ,  '    #  
.   ,  &  
  ( "( $  :
In [q]: bookmark l
Current bookmarks:
muak� /home/jmjones/local/Music
t � /tmp
D & # $    ' &   :   # $  $  
  # .        $  &  & $
 , $    & &,       & &   #
$  :
In [5]: bookmark ulb /usr/local/bin
In [6]: bookmark l
Current bookmarks:
muak� /home/jmjones/local/Music
t � /tmp
ulb � /usr/local/bin
In [^]: bookmark d ulb
In [8]: bookmark l
Current bookmarks:
muak� /home/jmjones/local/Music
t � /tmp
   
bookmark
 '  #$  #  
In [9]: cd bTAB�
muak t
;'   # $ " Backspace,  '     , 
  #:
In [9]: bookmark r
 ! * UNIX
In [10]: bookmark l
Current bookmarks:
     %   $  $      
ulb
,  $
&    
4usr4local4bin
.           #
  
bookmark_name
 
bookmark
.      
 $      #   
dhist
    #$ & ! 
      
  "(&     . |   (& &  #
 %   ,    '         %  IPython.
;'    &   $  ! 
dhist
 $   :
In [1]: dhist
Directory history (kept in _dh)
0: /home/jmjones
1: /home/jmjones/local/ideos
2: /home/jmjones/local/Music
z: /home/jmjones/local/downloads
q: /home/jmjones/local/Pictures
5: /home/jmjones/local/Projects
6: /home/jmjones/local/tmp
^: /tmp
8: /home/jmjones
9: /home/jmjones/local/tmp
10: /tmp
J   % #        '    #  
TAB�
,   $ ' :
In [1]: cd
TA�B
00 [/home/jmjones] 06 [/home/jmjones/local/tmp]
01 [/home/jmjones/local/ideos] 0^ [/tmp]
02 [/home/jmjones/local/Music] 08 [/home/jmjones]
0z [/home/jmjones/local/downloads] 09 [/home/jmjones/local/tmp]
0q [/home/jmjones/local/Pictures] 10 [/tmp]
05 [/home/jmjones/local/Projects]
Y   #(  $ '   ! 
dhist
   
, %   
T�AB
.     %  &  $ '  #  
$ #,  #     '  # '  . ; , % 
 $ #, %   & $ # # & #   (   
"(&    ,  '   #$  #&    :
In [2]: dhist 5
Directory history (kept in _dh)
6: /home/jmjones/local/tmp
^: /tmp
8: /home/jmjones
9: /home/jmjones/local/tmp
10: /tmp
 2. IPython
      # $          "(&
    . ; , %     #     
  #   "  ,  '
  #    :
In [z]: dhist z ^
Directory history (kept in _dh)
z: /home/jmjones/local/downloads
q: /home/jmjones/local/Pictures
5: /home/jmjones/local/Projects
6: /home/jmjones/local/tmp
   :     
    ,      
    ,   % &   ,      % '
     #  &           ,   
      $       ,    &   .
|   & ! &,   %
  (   
      . * &
pwd
  &     . ;
 :
In [1]: cd /tmp
/tmp
In [2]: pwd
Out[2]: '/tmp'
   
          %  IPython        
( ,      
    &    #
 &  "   #$  &.  & $ (       
   (. Y  &        #$     
  % # , %   "       % ,
Python # , %   ' &$  Python. ;  # 
      #    . @  #      $& # $% 
 ,    %       Python,     # 
     % :
In [1]: for i in range(10):
...: !date� ${i}.txt
...:
...:
In [2]: ls
0.txt 1.txt 2.txt z.txt q.txt 5.txt 6.txt ^.txt 8.txt 9.txt
In [z]: !cat 0.txt
Sat Mar 8 0^:q0:05 EST 2008
 ! * UNIX
|   %    . {       &  $  #
10  ( ! , '  $
(  '  . ;  
  &     , 
 " #   
&$ Python      &$      % .
     & &     ,  $   ! 
 
range()
, '        %    (& &   
   
.  '      #$    
$
&  &   
date
.    , %    
$ 
date
  %    ,   #$ & ,   
      ' &
.     (  $  
& $    
date
,     & &  !    
{ & !%  }.txt
.          & 
  $ ( !   '  
'   $ (, %   
 #&, %   '  % ,    .
     %   '    #  $% &,  % 
  Python. ; $  ,  %    $% & $ $ 
(,  $   ( % ,  %    $#   &
' XMLRPq  $ %  $    !,   '  
% # (    &$  Python     #     ,
 &&     #$  
' '  
Y     &         #,     
 %  IPython, && &  $ '  #   #   ,  % 
  (  .    ', %   (   
% #   !    (   
  +PI[-,   '(  #$ 
 
jmjones
. Y&    '    #$  #   
 :
ps aux awk '{if ($1 == "jmjones") print $2}'
|    &    %
     &  . ;   
   " #  '  $ %    IPython. Y& %  
%   
aux
In [1]: ps = !ps aux
In [2]:
 $#     
aux
 (& &      
 
 ,       && &   ,  %   
   .           %  $
  &, %    & 
  '     
list
,  
    '   ,   '   . J
 &  ,     & ! &, & '   % #
 ,   '    # 
 %  ?   $#  .
   ,      (       '
 2. IPython
   #   (       ,   
   #&. @ #    , %       #  
    ,   
 ' $ %  % &  (  
  ,   '(  #$  
jmjones
.     
  
grep()
. * %      &    %
!# ,   & ,        #,     
 #.  $ #,   & 
   #   ,  '
 
lighthttp
,       #$  #&     :
In [2]: ps.grep('lighttpd')
Out[2]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: www data q905 0.0 0.1........0:00 /usr/sbin/lighttpd f /etc/lighttpd/l
 #  $ 
grep()
      & ' 
'lighthttp'
.   :  & ' &,     &
 
,  %  #   
  .   $#   
 $   
grep()
  %    ,      
    &  ' 
'lighthttp'
.   % #  $
, $  %   (, %      $   & 
' ,      #$  #      :
In [z]: ps.grep('Mar0^', prune=True)
Out[z]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: USER PID %CPU %MEM SZ RSS TT STAT START TIME COMMAND
1: jmjones 19z01 0.0 0.q 21z6q q2^2 pts/2 Ss 0z:58 0:00 bash
2: jmjones 21zq0 0.0 0.9 202q8q 1018q pts/z Sl 0^:00 0:06 vim ipytho
z: jmjones 2z02q 0.0 1.1 81q80 11600 pts/q S 08:58 0:00 /home/jmjo
q: jmjones 2z025 0.0 0.0 0 0 pts/q Z 08:59 0:00 [sh] defu
5: jmjones 2zz^z 5.q 1.0 81160 11196 pts/0 R 09:20 0:00 /home/jmjo
6: jmjones 2zz^q 0.0 0.0 z908 5z2 pts/0 R 09:20 0:00 /bin/sh c
^: jmjones 2zz^5 0.0 0.1 1502q 1056 pts/0 R 09:20 0:00 ps aux
H     
grep()
 & ' 
'Mar0^'
 
', %  #"       $  7  ,    
 "  % #    ,   $ 
7  .
  % #  $,      &  ' 

'Mar0^'
,       :
prune=True
. |   
       % IPython, %  $,  
    $   &  ' , '  #
 " . ),    ,   
%        $
,       &  ' 
'Mar0^'
  
grep()
 '  '  #$  # !     $ 
. | $% , % 
grep()
 '  #     
!   $ # .     !      
 . { ! &  $
True
&      ,   % &
     . ; ,      % #  '  
     #    # !  #   :
 ! * UNIX
In [1]: import os
In [2]: file_list = !ls
In [z]: file_list
Out[z]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: ch01.xml
1: code
2: ipython.pdf
z: ipython.xml
|     ' !. H   '   $ #,   $ (
  # && & !,      ,    
 #$  #& !#  
os.path.isfile()
,   '   # #
,  && & !:
In [q]: file_list.grep(os.path.isfile)
Out[q]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: ch01.xml
1: ipython.pdf
2: ipython.xml
       !
,   # ,    
&& & ! .      #   :
In [5]: file_list.grep(os.path.isdir)
Out[5]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: code
@  #   , %
code
  # && &    . Y  
    
fields()
.   + ' -  ,  
   !# &   
$#          
    &,   ' $ #  &,  ' 
 #     .   & "       ,
  # $   (, $ (  7  ,   
# !    &(
USER
PID

START
In [q]: ps.grep('Mar0^', prune=True).fields(0, 1, 8)
Out[q]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: USER PID START
1: jmjones 19z01 0z:58
2: jmjones 21zq0 0^:00
z: jmjones 2z02q 08:58
q: jmjones 2z025 08:59
5: jmjones 2zz^z 09:20
6: jmjones 2zz^q 09:20
^: jmjones 2zz^5 09:20
  (,    , % 
fields()
 & &  
$#  ,  $   
grep()
. |  $ '  , %

grep()
 $ ?  ' , %  ?
 2. IPython
fields()
 '  $ ?  ' , %  
grep()
J &      ?  #    %   
grep()
fields()
. @  #    , % $ #  (  . H
fields()
     %   ,  ,    
 &,  $%        ,      
&, %    & &   . | % #  ( '  , 
$     .    %  
fields()
 
 &         &     0, 1  8. |   
        
USER
PID

START
@  #   & $ % ' &   !     (   
  +PI[-,   '(  #$  
jmjones
In [5]: ps.fields(0, 1).grep('jmjones').fields(1)
Out[5]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: 5z85
1: 5z88
2: 5q2z
z: 5q25
q: 5q29
5: 5qz1
6: 5qz^
^: 5qq0
8: 5qqq
  ...�
     %  & #     , 0  1,
       
USER

,      .   $
 %    ,    #  
grep()
,  & #
$,       &  ' 
'jmjones'
) $ %  , $  %       & #    
   # $   
fields(1)
. +; $ , %  &  
  % &  &.-
      ,    "     , $ (,
  (  #       #,   
? 
,   $ &  % #          .
 $ ' , %  $#  ,    ? ,     ,
%  (  #   % #. 
  &   % "( (
        %  #$  
 :
In [6]: ps.fields(0, 1).grep('jmjones').fields(1).s
Out[6]: '5z85 5z88 5q2z 5q25 5q29 5qz1 5qz^ 5qq0 5qqq 5q52 5q5q 5q5^
5q58 5q68 5q^0 5q^8 5q80 5q8z 5q89 5562 5568 559z 5595 559^ 5598 5618
5621 562z 5628 56z2 56q0 5^q0 5^q2 5808 58z8 12^0^ 1291z 1qz91 1q^85
19z01 21zq0 2z02q 2z025 2zz^z 2zz^q 2zz^5'
      s  $ & %&   ,  '
&   !      , $     ,   
 '   #         % .  '  
 ! * UNIX
       '   ( #          
pids
 $     % IPython   #,  ,    :
kill
$pids
. ;  &      
SITERM
    
,   '  #$  
jmjones
, %    $ 
"             IPython.
 '     #, %  ' & $ %  '  #  
"     #    %   &  &$
awk
ps aux awk '{if ($1 == "jmjones") print $2}'
H      #& ( '  $#      ,   
    . H
grep()
    &$
#      
field
. {  
field
  , 
 & & &  " &  %  %          $#
        & #&  $   :
In [1]: ps = !ps aux
In [2]: ps.grep('jmjones', field=0)
Out[2]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: jmjones 5z61 0.0 0.1 q6q12 1828 | S Apr11
0:00 /usr/bin/gnome keyring daemon d
1: jmjones 5z6q 0.0 1.q 21q9q8 1q552 | Ssl Apr11
0:0z x session manager
....
5z: jmjones z2q25 0.0 0.0 z908 58q | S Apr15
0:00 /bin/sh /usr/lib/firefox/run moilla.
5q: jmjones z2q29 0.1 8.6 60z^80 88656 | Sl Apr15
2:z8 /usr/lib/firefox/firefox bin
   %        ,     % 
   .   # #   !      ,  '
    #     :
In [z]: ps.grep('jmjones', field=0).fields(1)
Out[z]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: 5z61
1: 5z6q
....
5z: z2q25
5q: z2q29
@  #        %#  '  , %  !#   &$
 $  &  IPython,      ,   
!#.  !#    ! ( (,  $
' &  $   %  IPython. ) &  $ '  #  $
 2. IPython
 #  $ # %  ! 
&     IPython  $
       . Y& $      !  
  #$  # %      
  $ # & '   
 !&.
 !#
+ shell-   $   (  !  IPython.
 !#
 & $% &  ( ! ( 
  ,   $#  %    %  IPython    &   '  
     "          % .   
     !,  ( $% &, %
$%         ! IPython:  , $  
'          " &  ,  
 , $   ( "   
  ,   % (     
  ' &
PATH
, %   %    #    
 &  !,    &,  ,    %
Bash.
       ( ! ( $%   !#
      $ " &. ; ,   
 " 
envpersist
. " 
envpersist
 $ & $ 
& # $%     ' &  $  # ( $% &
 !
,  & %    
 &  (   #  
& #  ' !
.bash_profile

.bashrc
;'  $ ,  &  $%      
PATH
jmjonesYdinkgutsy:tmp$ ipython p sh
IPython 0.8.z.br.r96 [on Py 2.5.1]
[/tmp]�2 import os
[/tmp]�z os.environ['PATH']
z� '/home/jmjones/local/python/psa/bin:
/home/jmjones/apps/lb/bin:/home/jmjones/bin:
/usr/local/sbin:/usr/local/bin:/usr/sbin:
/usr/bin:/sbin:/bin:/usr/games'
@  # 
:/appended
   $% &     
PATH
[/tmp]�q env PATH=:/appended
PATH after append = /home/jmjones/local/python/psa/bin:
/home/jmjones/apps/lb/bin:/home/jmjones/bin:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:
/sbin:/bin:/usr/games:/appended
/prepended:
 % :
[/tmp]�5 env PATH =/prepended:
PATH after prepend = /prepended:/home/jmjones/local/python/psa/bin:
/home/jmjones/apps/lb/bin:/home/jmjones/bin:/usr/local/sbin:
/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/appended
@  #     '     
PATH
   #
os.environ
[/tmp]�6 os.environ['PATH']
 ! * UNIX
6� '/prepended:/home/jmjones/local/python/psa/bin:
/home/jmjones/apps/lb/bin:/home/jmjones/bin:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:
/bin:/usr/games:/appended'
     %  IPython:
[/tmp]�^
Do you really want to exit ([y]/n)|
jmjonesYdinkgutsy:tmp$
@  #       %  IPython, %  $& #   '
     
PATH
jmjonesYdinkgutsy:tmp$ ipython p sh
IPython 0.8.z.br.r96 [on Py 2.5.1]
[/tmp]�2 import os
[/tmp]�z os.environ['PATH']
z� '/prepended:/home/jmjones/local/python/psa/bin:
/home/jmjones/apps/lb/bin:/home/jmjones/bin:/usr/local/sbin:
/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/appended'
   ,   $% &  #   (   (,  
        # $ &
#    ! 
 . %      
PATH
  (   $ "   
" # . @  #   ,
  " $
 &    (
' &  (& &:
[/tmp]�q env p
q� {'add': [('PATH', ':/appended')], 'pre': [('PATH', '/
prepended:')],
 2. IPython
[/tmp]�^
Do you really want to exit ([y]/n)|
jmjonesYdinkgutsy:tmp$ ipython p sh
IPython 0.8.z.br.r96 [on Py 2.5.1]
[/tmp]�2 import os
[/tmp]�z os.environ['PATH']
z� '/home/jmjones/local/python/psa/bin:/home/jmjones/apps/lb/bin:
/home/jmjones/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:
/sbin:/bin:/usr/games'
    '  #,    &
PATH
 # $% , 
  "        ,
   
  $  &.
{    $&     #   !
  #& ! 
&
mglob
. * &
mglob
       &   
   (    #$
&. ; , %    #
 !  "  
.py
  [jango,  '    
 #$  #&     :
[django/trunk]�z mglob rec:*py
z� Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
)*  
* &
mglob
 $ ?  ,     , %  &$ Py
thon  '   #   ,  '   #    %  
     .
|    & "# 
(        &  
!&
.                !&,
    .
' ! 
IPython    '  #" , %      % ,     '
     #. |        $    ! 
     ? (,   (  &  
 #.    %    $ '     ! ,
%     #  '   #&       
&.    $   & &     ,    
    ! .
{     ? , 
 (  &   #,   
 &    ,  '    
 #   #$  #&  # 
!  
page
.   '  #$  # ! 
page
&  
?     #     %    .   (
 (  %         %  #$ &
  
less
,    '  #$  #   #   
. ;'    &         #$ &:
In [1]: p = !ps aux
['USER PID %CPU %MEM SZ RSS TT STAT START TIME COMMAND',
'root 1 0.0 0.1 5116 196q | Ss Mar0^ 0:00 /sbin/init',
... 3   3   +  ... �
In [2]: page p
['USER PID %CPU %MEM SZ RSS TT STAT START TIME COMMAND',
'root 1 0.0 0.1 5116 196q | Ss Mar0^ 0:00 /sbin/init',
... 3   3   +  ... �
 #      
 (& &  $#    &   
 
aux
.   $ & ! &
page
,      &
?   $#  .     ! &
page
$   
less
* &
page
    #  :
. | 
    ! 
page
   #  
   % 
    !           ?  + 
$#  $  ! 
str()
-. Y& "  ?      
       & #  :
 2. IPython
In [z]: page r p
ilus cd burner/mapping d', 'jmjones 5568 0.0 1.0 2z200q 10608 | S
)*  
r"""OS routines for Mac, NT, or Posix depending on what system we're on.
This exports:
all functions from posix, nt, os2, mac, or ce, e.g. unlink, stat, etc.
... 3   3   +  ..�.
      & !  &
    &  
less
. |  ' $ #&  ,     #  & #,  % 
   !   
    &   
   . |  ! &    ,    !  && &
  !    
.pyc
@ ' ! , %  &  # ! 
%pdef
%pdoc

%pfile
,  '  % #    #   
. % 
 #$    
  %  # .
* &
pinfo
          #  , %
 '    #,   ' (  #&  $ (. * &
pinfo
  &   ! ,  , $  ,   
           &. {    #, %  
 &  #,  '   :
#!/usr/bin/env python
class Foo:
"""-  Foo"""
def __init__(self):
pass
class Bar:
"""-  Bar"""
def __init__(self):
pass
class Bam:
"""-  Bam"""
def __init__(self):
pass
 '   $  # !
         :
In [1]: import some_module
In [2]: pinfo some_module
Type: module
Base Class: type 'module�'
String Form: module 'some_module' from 'some_module.p�y'
Namespace: Interactive
File: /home/jmjones/code/some_module.py
Docstring:
no docstring�
 2. IPython
           :
In [z]: pinfo some_module.Foo
Type: classobj
String Form: some_module.Foo
Namespace: Interactive
File: /home/jmjones/code/some_module.py
Docstring:
-  Foo
Constructor information:
Definition: some_module.Foo(self)
  $ &   $  :
In [q]: f = some_module.Foo()
In [5]: pinfo f
Type: instance
Base Class: some_module.Foo
String Form: some_module.Foo instance at 0x86e9e0�
Namespace: Interactive
Docstring:
-  Foo
  
,  &        ? ,  $   
% #  ' ! ,    ! &
pinfo
In [6]: | f
Type: instance
Base Class: some_module.Foo
String Form: some_module.Foo instance at 0x86e9e�0
Namespace: Interactive
Docstring:
-  Foo
In [^]: f |
Type: instance
Base Class: some_module.Foo
String Form: some_module.Foo instance at 0x86e9e�0
Namespace: Interactive
Docstring:
-  Foo
K  $     +
-,            ? ,
 $ &  % #   #" ! :
In [8]: some_module.Foo ||
Type: classobj
String Form: some_module.Foo
Namespace: Interactive
File: /home/jmjones/code/some_module.py
Source:
class Foo:
"""-  Foo"""
)*  
def __init__(self):
pass
Constructor information:
Definition: some_module.Foo(self)
  
   ' ! ,   ! &
pinfo
 (     $ $ "   ? .
  #        $  !     
   ,   
  (    # &
  ? ,    # !   . |      #   %  IPy
thon  #$ & $% # % , %  & &     #.
psource
* &
psource
  (     $ 
? ,  #  #   
  &,     
! &. Y& ' & (        #$ 
&     %    
. ;'   &   
 #$ &
psource
&     '   &:
In [1]: import some_other_module
In [2]: psource some_other_module
#!/usr/bin/env python
class Foo:
"""-  Foo"""
def __init__(self):
pass
class Bar:
"""-  Bar"""
def __init__(self):
pass
class Bam:
"""-  Bam"""
def __init__(self):
pass
def ba():
"""- Q ba"""
 2. IPython
       ! &
psource
 #$ & &   
(    ! :
In [q]: psource some_other_module.ba
def ba():
"""- Q ba"""
)*  
 2. IPython
   , ! &
psearch
 $ &   # ?   $(
 . ;'        % ( ?    
    
user
In [1z]: psearch e builtin * int
       $      :
In [1q]: psearch e builtin * string
__name__
? 

___
,     $ #, && &   &
 IPython. ?
__name__
  #&    &, &
( &  &. {    &
__name__
 '   
'__main__'
,  $% , %  #  & &    & #
  ,      &    .
who
  %  IPython   &  '        % & 
    ( ? 
.   $ ( ! &
who
  &  '   
        

  #$   ! 
who
In [15]: who
a aa b bb c cc
|  ! &   '   ( 
 ( ,        
% #  ( ? ,  
         '
 . * 
who
 '  #$  # &       (  
 (  ,  :
In [16]: who int
a b c
In [1^]: who str
aa bb cc
who_ls
* &
who_ls
 ( '  ! 
who
, $  %    , % 
     % #      (    (,   $
 . ;'   &    #$ & ! 
who_ls
 $   :
)*  
In [18]: who_ls
Out[18]: ['a', 'aa', 'b', 'bb', 'c', 'cc']
K        $  &    ?     
 :
In [19]: who_ls int
Out[19]: ['a', 'b', 'c']
In [20]: who_ls str
Out[20]: ['aa', 'bb', 'cc']
* &
who_ls
 $   ,      '  
% #    
   #     
, &  '  
     $#  . ;
'    &    ( 
      %              
In [21]: for n in _:
....: print n
....:
....:
whos
* &
whos
 ( '  ! 
who
,   %    
! &
whos
  !   %   . ;'  
 &    #$ & ! 
whos
 $   :
In [22]: whos
ariable Type Data/Info

a int 1
aa str one
b int 2
bb str two
c int z
cc str three
n str cc
@ ' ,   ! &
who
,      #       
     $  :
In [2z]: whos int
ariable Type Data/Info

a int 1
b int 2
c int z
 2. IPython
In [2q]: whos str
ariable Type Data/Info

aa str one
bb str two
cc str three
n str cc
+  $
   % IPython         % &    
  "(&  .       #$   
'    readline,       #$   #
  ! 
hist
  % readline
   % IPython   % &     !  #
 $ '  &,   '    #  '  ,  
  '    readline. {     #$  #
& & & &   &      
    % Bash, $%          #$ 
  '   !  #    IPython.    '  
& &   #    (,  $   $  &     
  :
In [1]: foo = 1
In [2]: bar = 2
In [z]: bam = z
In [q]: d = dict(foo=foo, bar=bar, bam=bam)
In [5]: dict2 = dict(d=d, foo=foo)
In [6]: CTR r�
(reverse i search)fo': dict2 = dict(d=d, foo=foo)
CTR� r
(reverse i search)fo': d = dict(foo=foo, bar=bar, bam=bam)
 #  '  "
Ctrlr
, $      
, 
&    %    &   .   $#    
%    ,      "  IPython
[5]
.  #$
&#  '       readline,   # ' 

Ctrlr
  %   ,      " 
IPython
.{ #     ",   '  #$ 
 #  %  '  readline
,    & ( % #  
.  &
Ctrla
       %   , &
)*  
Ctrle
     .  &
Ctrlf
$      
        +forward-,  &
Ctrlb
 
  $ +backward-.  &
Ctrld
 2. IPython
_ip.magic("hist ")
_ip.magic("hist n")
| % #   ,      IPython  $   (   #
   #      $   %  IPython    #
      .
 
 $  $  +translated-    
 ,   $ ,     #   & &  ,
     % IPython. |         %
. ;'   &  &  , & $ # 
 &     ,  % &    
In [^]: hist t
1: foo = 1
2: bar = 2
z: bam = z
q: _ip.magic("cd /tmp")
5: _ip.magic("hist ")
6: _ip.magic("hist n")
^: _ip.magic("hist t")
  #$   
  &  &     
     + -  +raw-  ' &     
,      #. ;'   &  $#    &
 
In [8]: hist r
1: foo = 1
2: bar = 2
z: bam = z
q: cd /tmp
5: hist
6: hist n
^: hist t
8: hist r
 
!    %  $ '  #       
$   " . ;'  
&    #$ & 
 
, %    #     ( ' &  
hist
In [9]: hist g hist
018^: hist
0188: hist n
0189: hist g import
0190: hist h
0191: hist t
0192: hist r
019z: hist d
021z: hist g foo
0219: hist g hist
shadow history ends, fetch by %rep number� (must start with 0)
)*  
=== start of normal history ===
5 : _ip.magic("hist ")
6 : _ip.magic("hist n")
^ : _ip.magic("hist t")
8 : _ip.magic("hist r")
9 : _ip.magic("hist g hist")
      shadow history +  &  &-,  &
" &        . @  &  &   &
 (  ,   #   .          
  ' &    %    % &  &.
              ' &  
    % &  &.
+  $ 
)         % Python,     % IPython  &  $
 '  #    #    "(&  ,  
  $#  .        $ % &   #$ 
  #          
, &  '   
    $#  . ;'   &    #$ &
    
 IPython:
In [1]: foo = "foo_string"
In [2]: _
Out[2]: ''
In [z]: foo
Out[z]: 'foo_string'
In [q]: _
Out[q]: 'foo_string'
In [5]: a = _
In [6]: a
Out[6]: 'foo_string'
    " 
[1]
      
foo
,    
&

[2]
      .       $%    
foo

[z]
,    &

[q]
   %  "  
$#  . K  & 
 $, %  &  $ '  #  (
& #  $#       .
;'   & '   ,         
  % Python:
��� foo = "foo_string"
��� _
Traceback (most recent call last):
File "std�in", line 1, in module�
 2. IPython
NameError: name '_' is not defined
��� foo
'foo_string'
��� _
'foo_string'
��� a = _
��� a
'foo_string'
 #,         % Python,     %    '
  , %     % IPython, $  %    , %
     #&  
 ,  %  #   
 ,  $'  &  % 
NameError
  %  IPython             
$#        #.  $      ( 
       

    #, %  $#
     
 #$&  ( #      ,   $  
 '  #$  #.     &,    &     
$#      #    %  & +
-,  $ 
  %          
_[0
9]*
.  '  
    #  $#     
Out
9]*
      #,   
   ,  % 
    ! ,    
%      #   % 
  $#  :
In [1]: !!ls apa*py
Out[1]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: apache_conf_docroot_replace.py
1: apache_log_parser_regex.py
2: apache_log_parser_split.py
In [2]: !!ls e*py
Out[2]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: elementtree_system_profile.py
1: elementtree_tomcat_users.py
In [z]: !!ls t*py
Out[z]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: test_apache_log_parser_regex.py
1: test_apache_log_parser_split.py
@  #   '  #&  $ '  #  
Out
z]    

.      &  ,      $% &
       &  :
In [q]: apache_list = _1
In [5]: element_tree_list = _2
In [6]: tests = _z
 "!   % !
@  #
apache_list
tree_list

tests
 ' '    , 
      (
Out
[1]
Out
[2]

Out
[z]
,      :
In [^]: apache_list
Out[^]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: apache_conf_docroot_replace.py
1: apache_log_parser_regex.py
2: apache_log_parser_split.py
In [8]: element_tree_list
Out[8]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: elementtree_system_profile.py
1: elementtree_tomcat_users.py
In [9]: tests
Out[9]: Sist (.p, .n, .l, .s, .grep(), .fields() available). alue:
0: test_apache_log_parser_regex.py
1: test_apache_log_parser_split.py
   $ :    % IPython  &  $ '  # 
 #&     $#    %  $  #  
,  %  $
 &  $      %   
  $#  .
*  $  : $
  %  IPython    %   , %    #  $ 
 #  #  ,         & & ! 
     ,   (   $  #  "  $ %  IPy
thon.
Y& %  &   # ! 
alias
. H '  
 "     ,           #
  #$ &. ;  (  #    #, %
! &
alias
    #   %#  #$  #   
    nix    % IPython,   '  ' $ #  
 #    $  " & $ %.
macro
* & macro  $ &  & #      , 
    & #&  $  ,          ,
    &   #. H    &,  $  
  #  #  ! 
macro
,  & &    
 "     . {    &  &  
  #  #   ,   %  #$ & 
   ( ! ,   '  $  #      , 
 2. IPython
  & #    .   % #     , 
   #     &  '  & #    
! ,      :
In [1]: dirlist = []
In [2]: for f in dirlist:
...: print "working on", f
...: print "done with", f
...: print "moving %s to %s.done" % (f, f)
...: print "*" * q0
...:
...:
In [z]: macro procdir 2
Macro procdir created. To execute, type its name (without ~uotes).
Macro contents:
for f in dirlist:
print "working on", f
print "done with", f
print "moving %s to %s.done" % (f, f)
print "*" * q0
      $ &   
[2]

dirlist
       
, %  (  '        ,        ,
%  $  
dirlist
 && &    ,   $     
  
, &  & (      . H  
   $  &          :
macro
macro_name
of_lines
,  
range_of_lines
 $  &     
 ,  '  #         .   
    '  & #&     $    
  + ,
-    & #&     .
        $     !    (
      
dirlist
,  $       
procdir
H      (   !  
dirlist
In [q]: dirlist = ['a.txt', 'b.txt', 'c.txt']
In [5]: procdir
� procdir()
working on a.txt
done with a.txt
moving a.txt to a.txt.done
****************************************
working on b.txt
done with b.txt
moving b.txt to b.txt.done
****************************************
working on c.txt
done with c.txt
moving c.txt to c.txt.done
****************************************
 "!   % !
           ,  '   
   #    # ! 
edit
.   $#     
     . % #    #  $ '  #  
 #      , &# #   ,  '
%   ( # .
  '  ( #                 
 #  #  ! 
store
.        
 !  :
store
variable
.    , ! &
store
 ' 
 #   #  ,    $ #& &   
 $: $ 
store
variable
   $     $
   (& (=  
    (&     
 =   
     $$   (  (& (
   (.
 2. IPython
 IPython.     &  $       $
 &    %  IPython. * &
run
   ! 
$:
run
options
specified_file
args
  #$   
   &
__name__
 &  %
 %   $% & $  &,     
'__main__'
. |
  , %  #  & &  ,     
     .
  #$   
 #  & &     
       %  IPython,  & %   #  %
       ,     .
  #$   
  %  IPython    
 # $  ! 
sys.exit()
  % 
SystemExit
. Y' 
    #   ,   %  IPython  '    .
  #$   
  %  IPython  ! 
      &  &.
  #$   
 $  #  $ 
     %  Python +pdb-.
  #$   
 $  #  $ 
     !  .
* &
save
 (&  $        $ !.
 &  #$ & ! 
save
save
options
filename
lines
      $ #&   ' !  , %   ! 
macro
{      #  
 & , %  !
   ( #       $    ,  #   ,
     #.   %     (& &   
$  ,      & &$  Python,  .
  && ! &,  #$ &
&   $  " & $
%,  ! &
rep
. * &
 '  # &  
 ,      $. $  ! 
 $  
   $    %   $#        
             . ; :
In [1]: def format_str(s):
 "!   % !
$  ! 
rep
  
[z]
        
. @ &     #  $ &       # 
   % IPython. |        #$  
         .
% ! &
 $     #
$ &     
  $  #$ & ". {    &    &,  
'&   $%  ,    #   !    ' 
    #       .  %       ,
%   & ! &, &  $   
bin
,   
       . H  (&    
bin
    
    
In [2]: a = some_blackbox_function('s~uiggly')
In [z]: a
Out[z]: '/opt/local/s~uiggly/bin'
{ $ # ! 
&  %,   %   
/opt/lo
cal/s~uiggly/bin
       ,       
  , "     :
In [q]: rep
In [5]: /opt/local/s~uiggly/bin-@7 �
{    &  ( #    
,         
,   '      #
bin
    , ' #    
%    #  %      &        
    &:
In [5]: new_a = '/opt/local/s~uiggly'
@  #    &  &   
&,  '&       
         .
;    ,          #    #     ,
 &   " #    #  #" ?   . % 
   #&  #     , %  & #&
"F @  #   '
 #$  #    
new_a
 %  
      &   & (  ( (  
 .
   ! 
rep
 %        & % ,  
 $%            $    ,
 &                 
    . |    & $ ,    &    
  $  #(    '   #"(    
. ; :
In [1]: map = (('a', '1'), ('b', '2'), ('c', 'z'))
In [2]: for alph, num in map:
100
 2. IPython
...: print alph, num
...:
...:
@  #  '     #     
[2]
 , %  
 # $% &,  '   2. Y&    '     
 
for
   #$  #& !  
rep
In [z]: rep 2
In [q]: for alph, num in map:
print alph, int(num) * 2
...:
...:
   , ! &
rep
    # $    . 
  $   %  , %  #$ &  ! 
macro
& '  # "     .    ! 
   & $    ,   & &     ,  :
In [1]: i = 1
In [2]: i = 1
In [z]: print i
In [q]: rep 2 z
lines [u'i = 1\nprint i\n']
In [^]: rep 2 z
lines [u'i = 1\nprint i\n']
 #    ( 
[1]
[z]
      ,  %
  1,     $%  .    (

[^]

  ' ! 
rep
   #    2  3.   
    (   +5  6-           
  
[q]
     ! 
rep
,    ,   .
| %  ' $ #  :   %   ! 
rep
 ' :   % ! 
rep
       $ % . ;
 :
In [1]: a = 1
In [2]: b = 2
 "& 
101
In [z]: c = z
In [q]: rep a
In [5]: a = 1
 #      # 
  (      ! 

rep
   #   ,         a.   $#
   %   ,    " 
[1]
,   %
  $ '  #     #  $  #    .
 ; 
  %  IPython && &         "  
  . H    &  $ '  &     
  &      : %   #"      
,      " #   # $ %. Y'   #
  $ ,    # %  #$  #   %  IPy
thon,  '   #      .  (    #
 %#   #" . * &
grep
       
      ,  $ ' ( &  ,    $ 
 &   &    $(   (  $ '  &(,   
% # (     '   & #& &   
  IPython. H  & #       '  $  #&
   %  IPython.     '      
 , (    &  ' #.
 
 %   '         (  &  #
         !  ,  ,  ! ' ,
  ' ,  XML, VTML  !  !
      ( 
. % &     (
  (   , 
grep

awk
,     & 
" &  '( $
%  (        $ #    .   
 $      #  $  # !  , $ %  $ 
( ! , %    %    #    
  +$ # & # ( &  
grep

-  !. ;   
   &  ,   &   & $ &   & 
      "   $ '  &.
  '      , "   $ , % &$
Python  '   #      , $ #
"& , %  Perl, Bash   &$    
&,    #$  
    .    
%,  %      Python
   , %  Perl  Bash
+ '    &
sed

-,   &   1.    &
  &$  Python,      &$      
  &         % &  ( ! , 
 &    $ % & !  $  ( !
 . ^$ Python     &         
 !  #  $ '  &        #
    , !   
  &  &( ' .
;              # ElementTree
% $%         !  XML.    
   ' ,  !!   #$  #      
               !  .
      Python  
103
   
Python  
         #  #   .    
    !     %   &  '   
  #         ?       #  #
  ( ? .    ,
str
,    ,    
  &    
.    $   $
&,   $  #          '  & # 
   (  $ &.
    
%     $  &   $ % &       
% :
In [1]: string1 = 'This is a string'
In [2]: string2 = "This is another string"
In [z]: stringz = '''This is still another string'''
In [q]: stringq = """And one more string"""
In [5]: type(string1), type(string2), type(stringz), type(stringq)
Out[5]: (type 'str�', type 'str'�, type 'str'�, type 'str'�)
K   !  % , %    ,  $%   ' :
   $  ? 
str
. K   !  %    % 
     && & $ $ & . |  &$ Python
% &  (   % UNIX,     !  % 
 && & $ $ & . ; :
jmjonesYdink:$ FOO=sometext
jmjonesYdink:$ echo "Here is $FOO"
Here is sometext
jmjonesYdink:$ echo 'Here is $FOO'
Here is $FOO
 &$ Perl    !  %   '    $  #  
   $    . ;'   &  ( '    &$
Perl.
#!/usr/bin/perl
$FOO = "some_text";
print " $FOO \n";
print ' $FOO \n';
)     $#       #"     &$ Perl:
jmjonesYdinkgutsy:code$ ./~uotes.pl
some_text
$FOO \njmjonesYdinkgutsy:code$
104
 3. + 
| $%     &$ Python.   & # $%&
Python  & $   . ; ,   '  #$ 
 #    !,        ' (  #& % 
  (  #     # ( +       "-.
@ %  '   '  #$  # % ,       
'     #    ! 
  (  #     #
(,   $    3.1.
% F.. 3+    +  #+  Python
In [1]: s = "This is a string with '~uotes' in it"
In [2]: s
Out[2]: "This is a string with '~uotes' in it"
In [z]: s = 'This is a string with \'~uotes\' in it'
In [q]: s
Out[q]: "This is a string with '~uotes' in it"
In [5]: s = 'This is a string with "~uotes" in it'
In [6]: s
Out[6]: 'This is a string with "~uotes" in it'
In [^]: s = "This is a string with \"~uotes\" in it"
In [8]: s
Out[8]: 'This is a string with "~uotes" in it'
   , %  2  4   (   +
[q]

- %        ( %  ' , %  
'   ,     $    '( 
% . +   #      '    
#     % $(  .-
)     (  , %       ? & #  
 #   . )         '  " #,  &&  
,   (   $  # $   ,    #   
   . Y&,   && #   $ % &   #
$   ( % ,   $ &  & #   
  %  .    3.2
   &   %&   
 #$  #    ! &   &     %     
 "&     #$  #      !.
% F.=. H &+ + 
In [6]: s = 'this is

File "ipython console�", line 1
s = 'this is

SyntaxError: EO while scanning single ~uoted string
(SyntaxError: +   Q      Q      X)
      Python  
105
In [^]: s = '''this is a
...: multiline string'''
In [8]: s
Out[8]: 'this is a\nmultiline string'
             $% &   , 
 &$ Python $ &    .      $ 
 &     
          
% .    ,     % & %(  
, %  (   ( Python       
   #     ,     %(   (   
  &.       (    # 
   &$ Python    &  %   '   , 
  &     &$  q. ; ,  %(   
(    #  #
   &    &,
         
      .  . 3.1
  &    (    #    &$ Py
thon.
H-AF.. I  + "/  #+  Python
         
\newline
)  &
      "
K   !
% 
ASqII  $   
ASqII  $ &
ASqII     
!   + -
ASqII       
\N{-}
)       + # &  
    -
ASqII   $   
ASqII   $  #  &
\uxxxx
}    % 16    
+ # &       -
\Uxxxxxxxx
}    % 32    
+ # &       -
ASqII     #  &
\ooo
 # %  
\xhh
}    %  
106
 3. + 
   (    #
 &(  (   (    
 #,    ,   (  &  #    & ' 
&,           .    3.3 
   &  #$    (    #  
  !   (   .
% F.F. I  + "/  + +   
In [1]: s = '\t'
In [2]: s
Out[2]: '\t'
In [z]: print s
In [q]: s = r'\t'
In [5]: s
Out[5]: '\\t'
In [6]: print s
In [^]: s = '''\t'''
In [8]: s
Out[8]: '\t'
In [9]: print s
In [10]: s = r'''\t'''
In [11]: s
Out[11]: '\\t'
In [12]: print s
In [1z]: s = r'\''
In [1q]: s
Out[1q]: "\\'"
In [15]: print s
    & &   &   (    # 
 ,
  &    &.      & 
 & &,   &    #  #
  
&,     $ (   ,

.   , '  % 
     !, % 
  ,  $  , %
   #  #
     #&    &
. { '      & &   
,   
#  #
   &
   ,

{  !      $%&  ' 
__repr__

__str__
.  
  &        &    " &   %  IPython
      Python  
107
 ' & " Enter, $%       ' & 
$    
__repr__
.      &   &
print
,     
 & &     ,  '
& " Enter,    &
' & $    
__str__
. )  &
print
  
       #       ' (  
   $ .   
__repr__

__str__
 $ 
&   2,  $  J$   & &.
      $   
    &$ Python  ? ,        , 
   $ #& &   &   (  . 
      $    #  , 
  
,       ,  $ & $  #
 $ ?  
.   ( &    
str
,   '
  

not
,      ,    ' .
 (%   %  $ &,         &

not
$ 
__contains__()
? 
str
.    #  ! 
  ,        ,  #  ' 
.   

not
   #$  #& &    , &
& &   &    % #     ,   $  
  3.4.
% F.G.   + in  not in
In [1]: import subprocess
In [2]: res = subprocess.Popen(['uname', ' sv'], stdout=subprocess.PIPE)
In [z]: uname = res.stdout.read().strip()
In [q]: uname
Out[q]: 'inux #1 SMP Tue Feb 12 02:q6:q6 UTC 2008'
In [5]: 'inux' in uname
Out[5]: True
In [6]: 'Darwin' in uname
Out[6]: False
In [^]: 'inux' not in uname
Out[^]: False
In [8]: 'Darwin' not in uname
Out[8]: True
{   
string2
 '   
string1
, ' 
string1
string2
  $% 
True
,     % $% 
False
      ( ' &   
"inux"
   
uname
 "  
%    $#  $%  True,      ( ' &   
"Darwin"
   
uname
 $% 
False
.      
   &  .
108
 3. + 
)      % $ #, %  &    && &  
       . K      & $ #,     $
(  &  &    . & #   '    #  

find()

index()
,   $    3.5.
% F.6. "+ find()  index()
In [9]: uname.index('inux')
Out[9]: 0
In [10]: uname.find('inux')
Out[10]: 0
In [11]: uname.index('Darwin')

type 'exceptions.alueError'� Traceback (most recent call last)
/home/jmjones/code/ipython consol�e in modu�le()
type 'exceptions.alueError'�: substring not found
In [12]: uname.find('Darwin')
Out[12]: 1
{   
string1
     
string2
+      
 -, 
string2.find(string1)
        
string1
  
string2
,     %   
. +;    #,
       %  $    -. @ %  ' ,    
string1
     
string2
, 
string2.index(string1)
 
       
string1
  
string2
,     
%   $   % 
alueError
.      
find()
'    
"inux"
 %   ,       $
% 
.  
find()
   ' #    
"Darwin"
    ,       $% 
.        
  Linux          #    
"inux"
  #  
index()
,   %  '  $#  , %   
%   &  
find()
. ;      #    
"Darwin"

index()
 $   % 
alueError
,  $&, %
     #      .
)  , %  '  #    %   F %  
 'F       &      . )
,   $ &  
find()

index()
,    
$ , %&        #"     ' 
   ,   $    3.6.
% F.;. ? #   
In [1z]: smp_index = uname.index('SMP')
In [1q]: smp_index
Out[1q]: 9
In [15]: uname[smp_index:]
      Python  
109
Out[15]: 'SMP Tue Feb 12 02:q6:q6 UTC 2008'
In [16]: uname[:smp_index]
Out[16]: 'inux #1 '
In [1^]: uname
Out[1^]: 'inux #1 SMP Tue Feb 12 02:q6:q6 UTC 2008'
H $#    &  #
  , %&   ,
      %  
 $#        
"SMP"
    ,   #$ "
#   %      
$ % &  $
string[index:]
. H  '    #   
 %   
uname
 ,    %    $#
       
"SMP"
,     %     
$ % &  $
string[:index]
.  $%&  '    &
  & $ % &      '     %&
-   #  .
~ #     $ %   $       &    

not
    , %   $ # , %    && &  
  #  &        '     &, %
     #  ,     . J      
 #   '  &  $  Seuence Operations   4
 Python in a Nutshell +$  #  OReilly- K  H 
+Alex Martelli- + $      )    $  # 
:
http:44safari.oreilly.com4569;55G;94pyt&#x-7.5;V.6;V.6;&#xG-6.;5.;ڔ.;dp5;&#x.8yt;.3h;&#xonia;&#xn000;honianC&#x-7.5;V.6;V.6;&#xG-6.;5.;ڔ.;dp5;&#x.8yt;.3h;&#xonia;&#xn000;KPG&#x-7.5;V.6;V.6;&#xG-6.;5.;ڔ.;dp5;&#x.8yt;.3h;&#xonia;&#xn000;SEC&#x-7.5;V.6;V.6;&#xG-6.;5.;ڔ.;dp5;&#x.8yt;.3h;&#xonia;&#xn000;T;
{    (  ,
startswith()

endswith()
,    $ (
$,      #, % &   $ % &
           ,   $    3.7.
% F.7. "+ startswith()  endswith()
In [1]: some_string = "Raymond uxury acht"
In [2]: some_string.startswith("Raymond")
Out[2]: True
In [z]: some_string.startswith("Throatwarbler")
Out[z]: False
In [q]: some_string.endswith("uxury acht")
Out[q]: True
In [5]: some_string.endswith("Mangrove")
Out[5]: False
   ,     Python  $ ! , &
   , %    Raymond Luxuryacht % &   
   Raymond  $ % &     Luxuryacht. 
 % &      Throatwarbler   $ % &    
 Mangrove. Y   %   '  $#    '  % #
 3. + 
   #   $ % &  $,     (  " 
&    &    '  $ #&   #   #
   $,   $    3.8:
% F.8. L%A %" startswith()  endswith()
In [6]: some_string[:len("Raymond")] == "Raymond"
Out[6]: True
In [^]: some_string[:len("Throatwarbler")] == "Throatwarbler"
Out[^]: False
In [8]: some_string[ len("uxury acht"):] == "uxury acht"
Out[8]: True
In [9]: some_string[ len("Mangrove"):] == "Mangrove"
Out[9]: False
 & $ % &  $  $    $     
 ? ,   $ &    . {   $ % 
&  $ %  #$ &   ,    $ #
    &      &     $ 
#  #. Y'  $   &&   $  #
  #   &,     , %"  $ ' #& 
 #$ &   $ % &  $  %&(,    
%   &  
startswith()

endswith()
H     #&, %       
some_string
, %
(      Raymond,       Ray
mond. Y  ,      #&, %   
some_string
% &      Raymond,  $  #$ &  
startswith()
. @ %  '      #&, %    $ %
 &     Luxuryacht.
H 
lstrip()
rstrip()

strip()
 $     &   ,
$ % # ,     $ % #   #  ,
     .  %    (   #(     ' 
$ #   &,   ,    $      
    . H
lstrip()
 $     &    #
 ,  ( & &  %   ,   $  
  . H
rstrip()
 $     &    # 
 ,  ( & &     ,   $     .
H
strip()
 $     &    #  , 
 ( & &  %      ,   $     
,   $    3.9.
    $    
strip()
 $ &    ,
 $    $      ? .  $ ' ,
        #          
 ,   ' $ #  .
      Python  
111
% F.9. "+ lstrip(), rstrip()  strip()
In [1]: spacious_string = "\n\t Some Non Spacious Text\n \t\r"
In [2]: spacious_string
Out[2]: '\n\t Some Non Spacious Text\n \t\r'
In [z]: print spacious_string
Some Non Spacious Text
In [q]: spacious_string.lstrip()
Out[q]: 'Some Non Spacious Text\n \t\r'
In [5]: print spacious_string.lstrip()
Some Non Spacious Text
In [6]: spacious_string.rstrip()
Out[6]: '\n\t Some Non Spacious Text'
In [^]: print spacious_string.rstrip()
Some Non Spacious Text
In [8]: spacious_string.strip()
Out[8]: 'Some Non Spacious Text'
In [9]: print spacious_string.strip()
Some Non Spacious Text
   ,
lstrip()
rstrip()

strip()
,    #  
   &$ #   :      ,   
  # $           . | $% , %  
   
strip()
    &   #     
 & #   ,     ' :
In [1]: xml_tag = "some_t�ag"
In [2]: xml_tag.lstrip("")
Out[2]: 'some_tag�'
In [z]: xml_tag.lstrip("�")
Out[z]: 'some_ta�g'
In [q]: xml_tag.rstrip("�")
Out[q]: 'some_tag'
In [5]: xml_tag.rstrip("")
Out[5]: 'some_ta�g'
 #    $  XML         ,  
  $ $. K   #,      &   #      
   F   #   '      :
In [6]: xml_tag.strip("").strip("�")
Out[6]: 'some_tag'
 3. + 
H     
strip()
 $   ,      '  
$ #       &  $ $    
strip()
.       ?  $   
strip()
  
 % .   $   
strip()
 & %#   + 
     -   $   ,     
strip()
 
& $ "   +     -   $
  
"some_tag"
.            :
In [^]: xml_tag.strip("�")
Out[^]: 'some_tag'
 $ ' ,   , %      
strip()
 & %
( '   $     , 
   #    & &
    # ( ' &  $(        
       .           
strip()
     #
"�"
. |  $% %      
    $% , %
'  #    ( ' &  (
(   ,  (  $         & ,
 $% , % '  #     
""

, ( &
 &  %      .
;'   &,  $ ' ,    &   :
In [8]: gt_lt_str = "���gt lt str���"
In [9]: gt_lt_str.strip("�")
Out[9]: 'gt lt str'
In [10]: gt_lt_str.strip("�")
Out[10]: 'gt lt str'
 #     ( ' &   

�""
  (  
  . @        ' 
    # 
   
  .
  $  #, %    
 '   #   #   ,
  '  ,  :
In [11]: foo_str = "fooooooo�blahfoo�"
In [12]: foo_str.strip("f�oo")
Out[12]: 'blah'
D      ' #&   , % 
strip()
    
    ,    .   '   
    # ( ' &   
""
"f"
"o"

�""
. |
 " ,          
"o"
.   , $ 
% #    #$ &  
strip()
,   &
   '  :
      Python  
113
In [1z]: foo_str.strip("�of")
Out[1z]: 'blah'
 #  & &  
�""
""
"f"
"o"
, ( &       
 & .
H 
upper()

lower()
   #$  #,    (  
  #   (    $ %       . H
per()
 $         $ #    
 (     . H
lower()
 $        
 $ #      '     ,   $  
  3.10.
% F.5. "+ upper()  lower()
In [1]: mixed_case_string = "Orpal BUnny"
In [2]: mixed_case_string == "vorpal bunny"
Out[2]: False
In [z]: mixed_case_string.lower() == "vorpal bunny"
Out[z]: True
In [q]: mixed_case_string == "ORPA BUNN"
Out[q]: False
In [5]: mixed_case_string.upper() == "ORPA BUNN"
Out[5]: True
In [6]: mixed_case_string.upper()
Out[6]: 'ORPA BUNN'
In [^]: mixed_case_string.lower()
Out[^]: 'vorpal bunny'
{   (  $ %# % #   , %    
  $  &, 
split()
       $
 '  #,   $    3.11.
% F.. " split()
In [1]: comma_delim_string = "pos1,pos2,posz"
In [2]: pipe_delim_string = "pipepos1pipepos2pipeposz"
In [z]: comma_delim_string.split(',')
Out[z]: ['pos1', 'pos2', 'posz']
In [q]: pipe_delim_string.split('')
Out[q]: ['pipepos1', 'pipepos2', 'pipeposz']
H 
split()
   &   $ 
#,     ( 
 $ #        .       , 
  $& &     #& %  ,    '  #   ,
 '&      .       $
 3. + 
  
comma_delim_string
 $& ,    
pipe_delim_string

     #  %   +
-,   &   $&     
#  %    
split()
.  $  $%     &&
&    , ' & $ (   &      
  #(   , ( &(&  '  $  &.   
 %   $  &  (   #$  #    
 ,      , 
split()
 &    .   
   &  (    &$
Python      #
,    ( &   ( 
split()
 %   
 ,   &      .   ,    

split()
   &   #   ,     (,   
$    3.12.
% F.=. ? .4=;.4.;&#x-2 ?;.4;&#x-3.; 7;&#x.4 ;  #"/  %" split()
In [1]: multi_delim_string = "pos1pos2posz"
In [2]: multi_delim_string.split("")
Out[2]: ['pos1', 'pos2', 'posz']
In [z]: multi_delim_string.split("")
Out[z]: ['pos1', 'pos2', 'posz']
In [q]: multi_delim_string.split("")
Out[q]: ['pos1', '', '', 'pos2', '', '', 'posz']
   , % %   #$   %   $ 
&   
""
& $  &   
multi_delim_string
. 
 '  #,   $#    %  
['pos1',
'pos2',
'posz']
 ,   #$   %   $  &   
""
 
split()
 
['pos1',
'pos2',
'posz']
.  # 
split()
 
 , ( & &  '     $  &
""
  
"pos1"
% &  %        &   
$  &
""
=    
"pos2"
  & $ $  
( '   $  &
""
    &     ( ' 
&=     
"posz"
  & $ $   ( '  
    &    .    $   
split()
 %  %   $  &     
.  
 , %  $&  '      
""
   
      +
-   $#    . | $% , %  
'      
""
%   .
;   #,   (  $ #    #   
( 
' &  $  $  &F Y&    
split()
 
   #      ,    
max_split
.        
 
max_split
 
split()
   &   %  $%  , 
  #  $ % $  (     :
In [1]: two_field_string = "86^5z09,This is a freeform, plain text, string"
In [2]: two_field_string.split(',', 1)
Out[2]: ['86^5z09', 'This is a freeform, plain text, string']
      Python  
115
 #  $      $&       
split()
  # #  $  . ;  &  , %    
     # $& (,   
 $  #  $.
{  (  $ #       ,  , %  $
 %# $   #  ,   $ %    '  " # $ 
   
split()
 $   :
In [1]: prosaic_string = "Insert your clever little piece of text here."
In [2]: prosaic_string.split()
Out[2]: ['Insert', 'your', 'clever', 'little', 'piece', 'of', 'text', 'here.']
   
split()
  %   ( 
  ,   %
  & $        #  .
      % # 
  $#  ,  ' 
  % #.   %     %     $#   '
 % #&  '  & .         %
    (   & #        
$ $. ;   '      ' #, %   $
     #  :
In [1]: multiline_string = """This
...: is
...: a multiline
...: piece of
...: text"""
In [2]: multiline_string.split()
Out[2]: ['This', 'is', 'a', 'multiline', 'piece', 'of', 'text']
Y&  ( %  %"  (  
splitlines()
In [z]: lines = multiline_string.splitlines()
In [q]: lines
Out[q]: ['This', 'is', 'a multiline', 'piece of', 'text']
H
splitlines()
 $   (   $     % 
    (&   .      '   #  
  #       $ %# #  :
In [5]: for line in lines:
...: print "START INE::"
...: print line.split()
...: print "::END INE"
...:
START INE::
['This']
::END INE
START INE::
['is']
::END INE
 3. + 
START INE::
['a', 'multiline']
::END INE
START INE::
['piece', 'of']
::END INE
START INE::
['text']
::END INE
)     (   
$  #     $  # $
 ! ,  ?  #     '   &  .
  %     #  
join()
In [1]: some_list = ['one', 'two', 'three', 'four']
In [2]: ','.join(some_list)
Out[2]: 'one,two,three,four'
In [z]: ', '.join(some_list)
Out[z]: 'one, two, three, four'
In [q]: '\t'.join(some_list)
Out[q]: 'one\ttwo\tthree\tfour'
In [5]: ''.join(some_list)
Out[5]: 'onetwothreefour'
D% &, % (   (& &    ,   ' 
?  #   
'one'
'two'
'three'

'four'
  #    
. H ? &       
some_list
   # $& , $
&     ,   &      . H
join()
     ,    $    %      ,
  
','
, && &  . H
join()
  % 
        #  #    ? & (     
  , %        
#    #  (  
 &  &#   , &   $ & 
join()
H '    #  
    &(   &  
join()
    ,   '   % #.   
 : 
join()
'   % #    #  #   . K %
 $  ,      #    #  #  ( % F
$& 
In [1]: some_list = range(10)
In [2]: some_list
Out[2]: [0, 1, 2, z, q, 5, 6, ^, 8, 9]
In [z]: ",".join(some_list)

exceptions.TypeError Traceback (most recent call last)
/Users/jmjones/ipython console�
      Python  
117
TypeError: se~uence item 0: expected string, int found
(TypeError: K -  0   3 :    , +  Q  )
Y  %  & ! &,  ' &  % ,  $'
   
join()
,   % & ?&&  " " , 
    #    & " ,      $ 
 #&.     ' $ ' #    "     #   
      . ;'           
 , %   $  #       
some_list
,   
'   %,    :
In [q]: ",".join([str(i) for i in some_list])
Out[q]: '0,1,2,z,q,5,6,^,8,9'
)  '  #$  # '     :
In [5]: ",".join(str(i) for i in some_list)
Out[5]: '0,1,2,z,q,5,6,^,8,9'
   #  !     #$       
   # $  qontrol ]low Statements   4 
 Python in a Nutshell + $      )  ,  
$  # :
http:44safari.oreilly.com4569;55G;94pytho.25;.25;&#xG6.2;&#x;6.2; -6.;鐐&#x.5p6;&#x.4yt;&#xh14.;o-1;&#x.5ni; n00;nianC.25;.25;&#xG6.2;&#x;6.2; -6.;鐐&#x.5p6;&#x.4yt;&#xh14.;o-1;&#x.5ni; n00;KPG.25;.25;&#xG6.2;&#x;6.2; -6.;鐐&#x.5p6;&#x.4yt;&#xh14.;o-1;&#x.5ni; n00;
SECT�5
    ,  #$  &  $ &  $  &  (
  ,  
replace()
. H
replace()
    :
  ,    & $  #,     $ ,     
 . ;'   &       #$ &  
replace()
In [1]: replacable_string = "trancendental hibernational nation"
In [2]: replacable_string.replace("nation", "natty")
Out[2]: 'trancendental hibernattyal natty'
   , % 
replace()
     & , && &
$  &    % #    #   .     
replace()
 '  #$  #& #  %&(,    
  & $  #    
  #  #    
         #  #   .
)     &         $ ,  
    $     
 #       
   (  .   ( %&( %   (   #
 $ '  #   # "     #     , 
   &    $  #.    "    '  '
  %#           &     $ % & $
  (.  ( %&(,     %  #  #$  #
" ,      & ' &.  & ' 
&     .
 3. + 
@ ' ,   & $ % &  $  
strip()
, 
replace()
 $ &      ,   $   .
    
Y (     (  (      ,    ,
 #$ #  % #    ?      
,   &$ Python         ,  
     $  #&:  
  . /  , 
  & &     &,   #     
%. Y  & &          '  
$ $(    ' &
% (      $
   &$    ! .      ,   %
  '  % (    ,  $
&$ ,  !   '  ,  &   
 .    $      &        
       ,   &  &$ Python.    
        (   %  |. H. %
+A. M. \uchling-    :
http:44www.amk.ca4python4howto4unicode
 $      &  % #   ' , %   $ 
%(   :
In [1]: unicode_string = u'this is a unicode string'
In [2]: unicode_string
Out[2]: u'this is a unicode string'
In [z]: print unicode_string
this is a unicode string
)  '   #$  #&     !  
unicode()
In [q]: unicode('this is a unicode string')
Out[q]: u'this is a unicode string'
;   $& ,     %   % #  ,    
%  #, % $ #          &$ . ; 
 #,   (  &   #    $   # ( &$ F
 #     #   .        
 $  #       %  ,  '   #$ 
 #&   
\u

\u
. ; , '   &
    ,  '& 
  ,  %   !
  :
In [1]: unicode_string = u'abc_\u0za0\u0zaz\u0za9_\u0q1q\u0q2q\u0q2F'
In [2]: unicode_string
Out[2]: u'abc_\u0za0\u0zaz\u0za9_\u0q1q\u0q2q\u0q2f'
      Python  
119
)          +
str
-  $    #$  
  .    Python, &   & &    #
 Mac,     #&       $      
    #   
print
,   %      " :
In [z]: print unicode_string

UnicodeEncodeError Traceback (most recent call last)
/Users/jmjones/ipython console� in module�()
UnicodeEncodeError: 'ascii' codec can't encode characters in position q 6:
ordinal not in range(128)
(UnicodeEncodeError:   'ascii'      3 -
 Q q 6:    X    range(128))
H '   #   ,  $ ,   
 #       :
In [q]: print unicode_string.encode('utf 8')
 #        ,  '     
,  %   !   ,     UT]8, &
  %  #$ & 
&  & (  .
        '  $ '  &,     $
 '  #   &        #   
,   ,
%  %   , (  '   :
In [5]: u'abc' in unicode_string
Out[5]: True
In [6]: u'foo' in unicode_string
Out[6]: False
In [^]: unicode_string.split()
Out[^]: [u'abc_\u0za0\u0zaz\u0za9_\u0q1q\u0q2q\u0q2f']
In [8]: unicode_string.
unicode_string.__add__ unicode_string.expandtabs
unicode_string.__class__ unicode_string.find
unicode_string.__contains__ unicode_string.index
unicode_string.__delattr__ unicode_string.isalnum
unicode_string.__doc__ unicode_string.isalpha
unicode_string.__e~__ unicode_string.isdecimal
unicode_string.__ge__ unicode_string.isdigit
unicode_string.__getattribute__ unicode_string.islower
unicode_string.__getitem__ unicode_string.isnumeric
unicode_string.__getnewargs__ unicode_string.isspace
unicode_string.__getslice__ unicode_string.istitle
unicode_string.__gt__ unicode_string.isupper
unicode_string.__hash__ unicode_string.join
unicode_string.__init__ unicode_string.ljust
unicode_string.__le__ unicode_string.lower
 3. + 
unicode_string.__len__ unicode_string.lstrip
unicode_string.__lt__ unicode_string.partition
unicode_string.__mod__ unicode_string.replace
unicode_string.__mul__ unicode_string.rfind
unicode_string.__ne__ unicode_string.rindex
unicode_string.__new__ unicode_string.rjust
unicode_string.__reduce__ unicode_string.rpartition
unicode_string.__reduce_ex__ unicode_string.rsplit
unicode_string.__repr__ unicode_string.rstrip
unicode_string.__rmod__ unicode_string.split
unicode_string.__rmul__ unicode_string.splitlines
unicode_string.__setattr__ unicode_string.startswith
unicode_string.__str__ unicode_string.strip
unicode_string.capitalie unicode_string.swapcase
unicode_string.center unicode_string.title
unicode_string.count unicode_string.translate
unicode_string.decode unicode_string.upper
unicode_string.encode unicode_string.fill
unicode_string.endswith
 $ ' ,        
 &      . ; '
 $ #  (    ,     #  ' #  
  #  &$ Python.
$     &$  Python 
 &       
       % ,  '   '  #, %    
          %    &     
& ' &. @    #. K      $   
  #$   &$
Python  &( ' ,     
   &( (   .   ,    $    &
 ' &,            Mastering Re
gular Expressions +OReilly- Y' !! {. *. *  +`effrey E. ].
]riedl- +    '  )    $  #     :
http:44safari.oreilly.com4569;6=8=G
Y     , % 
  %       & ' &,   
  %      ' #  *    .
{  $   &$  Perl, ,  $ ' ,  '  #$ 
 & ' &     
.  &$ Python  ' 
 &( '   $ 
   
 ,   
    %  (      &$ .    &     
& ' &  (      #  #
Y' !! *   & ' &, 3 $  .  .  .
.:  , 2008.  )   ' $  #&  5  
      
http:44www.books.ru4chapterMidN 69=FG;OnumN.
%.  .
      Python  
121
'   &      
$ &   #$ &  & 
 ' &,   $    3.13.
% F.F. &  % /#   + 
In [1]: import re
In [2]: re_string = "{{(.*|)}}"
In [z]: some_string = "this is a string with {{words}} embedded in\
 3. + 
   #  !    ( ! &(,  (&   

,  # $  Module qontents   % Py
thon Library Reference,
http:44docs.python.org4lib4nodeG;.html
.  
  #  !    ? (   (  &
( '   # $ 
 Regular Expression Objects
 % Python Library Reference,
http:44docs.python.org4lib4
�reobjects.html
   3.14      $&         
 !   ,   &     #$ &
?       &  ' &.
% F.G.    + ,  % +& '-
In [1]: import re
In [2]: re_obj = re.compile("{{(.*|)}}")
In [z]: some_string = "this is a string with {{words}} embedded in\
      Python  
123
infile = open('large_re_file.txt', 'r')
match_count = 0
lines = 0
for line in infile:
match = re.search(pattern, line)
if match:
match_count = 1
lines = 1
 3. + 
infile = open('large_re_file.txt', 'r')
match_count = 0
lines = 0
for line in infile:
match = re_obj.search(line)
if match:
match_count = 1
lines = 1
      Python  
125
In [5]: re.findall(raw_pattern, some_string)
Out[5]: ['a', 'few', 'little', 'words']
In [6]: re.findall(non_raw_pattern, some_string)
Out[6]: []
}   
  &( ' &(     
  . @  #,   %   &     , 
%   & %    ,        #
#  ,   & $ 
   '    .  
 , %   #$ 
raw_pattern
 '  
#   
some_string
,    #$ 
non_raw_pattern
 
 %      .   
raw_pattern
&
 
  &   #(  ,   &    
non_raw_pattern
    &    $ & +backspace-.
 $#  ! &
findall()
    # #     
 #  !        " .    #$ 
 "    %     ! &
findall()
   
    $ & +backspace-.
    # " 
non_raw_pattern
 '    #  
      ,  (  ' #       
,   $ ' :
In [^]: some_other_string = 'a few \blittle\b words'
In [8]: re.findall(non_raw_pattern, some_other_string)
Out[8]: ['\x08little\x08']
    "    % !  $  
"\x08"
    ,    !  
findall()
. |  "   
%& !  $       $ & +backspace-, 
       #        # 
 
   ,  !    
      #&,  
   &  #$  #  
#    #  ,  

"\b"
,  $%   ,
"\d"
,  $% !,

"\w"
,  $% !  !    .     
% #  #(    #  , %(&    
    ",    $  Regular Expression Syntax
 % Python Library Reference,
http:44docs.python.org4lib4
�resyntax.html
   3.14  3.17  % #   .  (   (  #$ 
#  & ' &  $
%  ,  &  .
)     %   
#$ &  &( ' 
    % . )     (   %     ,
%   &    &( ' .
 3. + 
     + ! &-  &( ' , 
 #$ &   % ,  & &
.   '       #&  

,  ,
  &  ,   % ,    .
H
findall()
   ( ' &  $  "     
. { 
findall()
    & " ,   $ 
     (  $ # %&   "  .
   :      &( ' &(
 $ &  $ #     &  ' &, 
   $ %# $  $#  .    #  
!    # $  qommon Metacharacters and
]ields   *  +]riedl-
Mastering Regular Expres
sions
  )     :
http:44safari.oreilly.com4
569;6=8=G4regexF.8=;.8G;&#x-4.6;H.8;&#xr0.8;gex;.1F;.80;CK.8=;.8G;&#x-4.6;H.8;&#xr0.8;gex;.1F;.80;PF.8=;.8G;&#x-4.6;H.8;&#xr0.8;gex;.1F;.80;SE.8=;.8G;&#x-4.6;H.8;&#xr0.8;gex;.1F;.80;CT6MimagepageNF7
{   &  '     ,     
 ,  
findall()
     . ; :
In [1]: import re
In [2]: re_obj = re.compile(r'\bt.*|e\b')
In [z]: re_obj.findall("time tame tune tint tire")
Out[z]: ['time', 'tame', 'tune', 'tint tire']
   "     ,   
findall()
 $
   .  #  '   #      % !!
         '   , tint  tire. ) #$ 
 $ #  & '       , %&
   t  $ %&    e. ; % # ' &
.*|
      ,  %&   . H
findall()
   , %    #.      , % &
  t +tint-,   '      ,    '
  , $ " &    e +tire-.        tint
tire     &  "  .   % #   ,  '
   #$  #  & ' 
r'\bt\w*e\b'
In [q]: re_obj = re.compile(r'\bt\w*e\b')
In [5]: re_obj.findall("time tame tune tint tire")
Out[5]: ['time', 'tame', 'tune', 'tire']
       (,   '  #  % , 
  ' . {      '   
     ,
findall()
    ' .  
"       $    3.18.
Y' !! *   & ' &, 3 $  .  .  .
.:  , 2008.  3. $        
 $ '  .
%.  .
      Python  
127
% F.8.       %" findall()
In [1]: import re
In [2]: re_obj = re.compile(r"""(A\\b(bigsmall)\b\\b
...: (brownpurple)\b\\b(cowdog)\b\\b(ranjumped)\b\\b
 3. + 
 . &         $ #    $ '  #,
    ,     %  '  $ &  & #   
    '      &  ' &, %   #,
%    &  % #.
 $  (  '  , &
$(   & ' &,     , % 
"  %  % #     & % &. ~ #
re.ERBOSE
    , %     #   &( 
' ,   # ,   
   ,  %    
'     ,  '   & ' &.
H
finditer()
&& & $    #  
findall()
.  
 %   $ #   ' ,    
find
all()
finditer()
 $   ,     $    
. '         ?      &,
         .   3.19  $ '
    , #
      
findall()
 #$ &

finditer()
% F.9. % /# %" finditer()
In [q]: re_iter = re_obj.finditer('A big brown dog ran down the street. \
...: A small purple cow jumped to the moon.')
In [5]: re_iter
Out[5]: callable iterator object at 0xa1^ad0�
In [6]: for item in re_iter:
...: print item
...: print item.groups()
...:
_sre.SRE_Match object at 0x9ff858�
('A big brown dog ran down the street.', 'big', 'brown', 'dog', 'ran',
      Python  
129
& , %        .    ,    
      #    $  &   .
{       
 
    ,
% '     ,  $   
finditer()
,  ?
match
,            ' ,    
(     .
H 
match()

search()
  %  ( ' !  #
 $ '  .     &  & '    =
  $ ,     $ % #     $ % #   
" =   $ ?
match
&        
  & $   " . $  '    &  
    , % 
match()
  &   #    #
%      $        ,    ( &  
  $    ,  
search()
   #&   #  
   "            '  %#    %
   $ ,    ' ,   $    3.20.
% F.=5. ?  %" match()  search()
In [1]: import re
In [2]: re_obj = re.compile('FOO')
In [z]: search_string = ' FOO'
In [q]: re_obj.search(search_string)
Out[q]: _sre.SRE_Match object at 0xa22fz�8
In [5]: re_obj.match(search_string)
In [6]:
Y'  , %   
search_string
 &     " 
,       $  
match()
,     ,  
$ " &   % ,   %     
search_string
,   
 & " , (  &   %   . H
search()
, 
 , "         ?
match
H 
search()

match()
  ,  & 
%#   %  $   
   ,   $   
 3.21.
% F.=.  % +   A    %"0 search()
 match()
In [6]: re_obj.search(search_string, pos=1)
Out[6]: _sre.SRE_Match object at 0xabe0z�0
In [^]: re_obj.match(search_string, pos=1)
Out[^]: _sre.SRE_Match object at 0xabe09�8
 3. + 
In [8]: re_obj.search(search_string, pos=1, endpos=z)
In [9]: re_obj.match(search_string, pos=1, endpos=z)
In [10]:
 
pos
  ,  &      ,   
'  % #&    " .
    
  % 
 
pos
 
search()
  &   $#
 ,    % 
 
pos
 
match()
  , %  "     
" , ( &  $  
pos
    ' #    #.
D     
endpos
 $%  3   , % 
  
match(),

search()
 "     ,   %  
   "   %     #   $.
H 
findall()

finditer()
 %    : %     
  " F,     ,    %  
search()
match()
:  &        " F. H 
search()
match()
 %  '    :          
 " F,  %  
 , %   & $ #,  :
 &        " F. ; ,    ',
%  (   #  ,  '  %  #    $
! '     # '       VTML, %   
 % #   %   '  .    (  # , %  
  ,  '  ERROR, '#   ,
& %   '     #          ! ,  
  # (    #  &  ' & ,  
search()
'  ERROR,  '     #   ! 
   , %   '#   .
H 
search()

match()
   # , %   &
%    &,   , %   $ ?
match

match
 ' $%   $ % & (, 
    #&  (  %
(  $#  .    
    &     ? 
match
, 
start()
end()
span()
groups()

groupdict()
H 
start()
end()

span()
 &  $      ,
     "   % &   $ % &. H
start()
 $   % ,  &  $    
%       &. H
end()
 $   % ,
 &  $           &.
K
 $  ',  '  $ %  
   &.
H
groups()
 $  '   &, '     
       ,   &  "  . |  '  
  '   ,  $    
findall()
groupdict()
 $  #   ( , %  
      , 
  (         
&  ' ,  :
(|Pgroup_nam�epattern)
      Python  
131
  &  ,  '  $ # %  !!   #$  #  
& ' &,   $& #  %   #$  # ? 
  (  &( ' . ) #$  
findall()

finditer()
,    (   % # %   ,  
   " .   , % 
finditer()
   
    #, % 
findall()
,   %  $    
? 
match
. J     $     &( 
'      9  Python in a Nutshell K  H
 +Alex Martelli- +OReilly-.
  $  #&   &
' &   ,  #  [ata qrunching  
 D  +Greg Wilson- +The Pragmatic Bookshelf-.
=' !    !" Apache
@  #,     %        & 
' &  &$ Python,   
    #  ! 
 !      Apache:
NameirtualHost 12^.0.0.1:80
irtualHost localhost:8�0
DocumentRoot /var/www/
Directory �/
Options FollowSyminks
AllowOverride None
/Directory�
Errorog /var/log/apache2/error.log
ogevel warn
Customog /var/log/apache2/access.log combined
ServerSignature On
/irtualHos�t
irtualHost local2:80�
DocumentRoot /var/www2/
Directory �/
Options FollowSyminks
AllowOverride None
/Directory�
Errorog /var/log/apache2/error2.log
ogevel warn
Customog /var/log/apache2/access2.log combined
ServerSignature On
/irtualHos�t
|    $   !  ! Apache  Ubuntu.
H  $      # (   &  (  (
' . H  '   !
4etc4hosts
    :
12^.0.0.1 local2
  $ &  $ #  $ , %       
local2
   
 IP   127.0.01,  #  # # . )  %  ' $ #
F {   $       
http:44local=
,       
 3. + 
 $ &  $   VTTP. ;'   & VTTP$ , 
    
local2
      Python  
vhost_end_match = vhost_end.search(line)
if vhost_end_match:
in_vhost = False
yield line
if __name__ == '__main__':
import sys
conf_file = sys.argv[1]
vhost = sys.argv[2]
docroot = sys.argv[z]
conf_string = open(conf_file).read()
for line in replace_docroot(conf_string, vhost, docroot):
print line,
|   %  $   ?    (  
&( ' :        
irtual
Host
,  $   
irtualHost
      
 
DocumentRoot
. H  '  $  ! , &  &  
  #  . * & $ &
replace_docroot
 
 %       !   !     ,
& $ 
irtualHost
,    &   #,  $%  
 
DocumentRoot
,    & $% # &    #
  (  . * &   $   &&,   
$ , (  &  & $ &     $ 
irtu
alHost
.    ,  (& & &    #  (  . 
$    $ 
irtualHost
  ! &   &   #
      
DocumentRoot
 $ &  $%  .   # 
! &
replace_docroot()
 &    '     
!   ! ,   $   $   ( 
  ,  $         
DocumentRoot
H  $      !          ! .
      &  #$  %      ,  
 ! &
optparse
,    & &      %   ( 
(   ,     . @  #       # 
  !   !     Apache,   
   " ,  $     
irtualHost
local2:80
 , % 
  #$    
4tmp
 %          
.       !          
    ,  $  !  
replace_docroot()
,   $ &
 !:
jmjonesYdinkgutsy:code$ python apache_conf_docroot_replace.py
/etc/apache2/sites available/psa
local2:80 /tmp
NameirtualHost 12^.0.0.1:80
irtualHost localhost:8�0
DocumentRoot /var/www/
Directory �/
Options FollowSyminks
 3. + 
AllowOverride None
/Directory�
Errorog /var/log/apache2/error.log
ogevel warn
Customog /var/log/apache2/access.log combined
ServerSignature On
/irtualHos�t
irtualHost local2:80�
DocumentRoot /tmp
Directory �/
Options FollowSyminks
AllowOverride None
/Directory�
Errorog /var/log/apache2/error2.log
ogevel warn
Customog /var/log/apache2/access2.log combined
ServerSignature On
/irtualHos�t
{   &   , & $ #,        
DocumentRoot
 $ 
irtualHost
local2:80
. ;'  & & $
%&,  %     ,    &     
!:
      Python  
   !"
|  '  $ #&  ,  %   %  #  ' 
    !,  (   $  #   ? 
file
     #    $
&    ?    $    
  !.    #   $  !,  ( 
 $  #   ?
file
,  $ ' ,  $  #   !   ,
         $  ? 
file
      
&  , %   $  ? 
file
& % &.  $  # ?
file
&$ # ,   %   (  & $ $  
  !    .
Y&  $ & ? 
file
 #$ &   & ! &
open()
;'   & !     ,  
! & % &:
In [1]: infile = open("foo.txt", "r")
In [2]: print infile.read()
Some Random
ines
Text.
* &
open()
   & ! &,         
(        #    #. * &
open()

    : & !,  '  &  $  ! .
&$ # && & #     & !. ; 
 %  #$ &  ': r
+ ' % &,  #$ & 
 %-, w + ' $-  a + ' $    !-.
      &  !    '   '  #$ 
 #&   #  !   b,  &  %
 '  . @    , $  ! ,  &   
! $    ! .
           # !
foo.txt
  '
 & % &   ( #     $  ? !    
infile
.    % &    ?      
infile
 &#  $ '  #   #&  
read()
  ? , 
 %   ' !   .
 $  ?  
file
& $  !  & &  %  
' ,   $  ?  & % & $ !.      
!    '
"r"
   #$  #  !  
"w"
In [1]: outputfile = open("foo_out.txt", "w")
In [2]: outputfile.write("This is\nSome\nRandom\nOutput Text\n")
In [z]: outputfile.close()
       &  # !
foo_out.txt
  '
& $   ( #  
  #  $  ? 
file
 3. + 
    
outputfile
.    % &    ?   
   #&  
write()
, %  $ #  !  
  $  #  $    
close()
;  &       $ & ! ,    '  & #&
'   $  # !    ,    %  & 
" . %  & (  "        # $  ! 
open()
   
try/finally
,    ,    $   $
 & 
write()
. ;'   &    $ $
!   #$     
try/finally
In [1]: try:
...: f = open('writeable.txt', 'w')
...: f.write('~uick line here\n')
...: finally:
...: f.close()
    $ $ !  
close()
$ &,  
  #  
try
 $   %  .    #  
  (  $ &  
close()
$  # !, '     

try
  $   %  . J
finally
 & &   $
 " &    
try
  ,  $  ,  $  
%    .
   Python 2.5  &#  &      &
with
, 
&  $ &  #$  #   '    . H  ' 
      ?   
__enter__()

__exit__()
.  
  ?  $  &    #   
with
, $ & 
__enter__()
  '    .        
with
$ 
" &, $ & 
__exit__()
  '    , ' 
 $   %  . ?  
file
   
__enter__()
__exit__()
.  
__exit__()
?  
file
$ & 
close()
. ;'   &    #$ &   
with
In [1]: from __future__ import with_statement
In [2]: with open('writeable.txt', 'w') as f:
...: f.write('this is a writeable file\n')
...:
...:
&    !     $   
close()
? 
,  
 '     $  !   (  $  
with
In [z]: f
Out[z]: closed file 'writeable.txt', mode 'w' at 0x1z82^�^0
In [q]: f.write("this won't work")

alueError Traceback (most recent call last)
/Users/jmjones/ipython console� in module�()
      Python  
alueError: I/O operation on closed file
(alueError:  Q     - -)
    '  #, !  $  . &  (  "&  
    #   $ '  % &     # $
  !,     (  ,        &   
      #       (  (.
    % #   ?  
   $  ]ile
Objects   % Python Library Reference    :
http:44
docs.python.org4lib4blti��nfileobjects.html
�   !"
 #  && & ? !,   & % &  ! 
  %  $ '  #  #$  #  %(   ? 
file
,  ( &  % & (,  '(&  ! :
read()
readline()

readlines()
. H
read()
%  , %    # , 
 $ ?    !   $        
. H
read()
  &$ #   ,   
$ %  ,    &  %  # $ !. { 
     , 
read()
   &  %  #  '
!   . { $  !  #" , %   %   ,

read()
 %  #  ,   
     !   
 , %   #  %  #.
Y  , %  &   !:
jmjonesYdink:/some_random_directory$ cat foo.txt Some Random
ines
Text.
@   
read()
   #    ! ,   $ ' :
In [1]: f = open("foo.txt", "r")
In [2]: f.read()
Out[2]: 'Some Random\n ines\nOf \n Text.\n'
   , %         ' &   
  #  
         $% &  
     .
{     #  %  # #   5  ,   # 
 '        :
In [1]: f = open("foo.txt", "r")
In [2]: f.read(5)
Out[2]: 'Some '
   ,  $ &  
% #  $ !, 
readline()
. H
readline()
%   $ !      $
 3. + 
$. |     &$ #   :
sie
. 
 &  # %  ,  
readline()

%  # $ !,  ' %    #   ,  $  ,
          .         
  %       $   $ !
foo.txt
, $  %
   7     $      ,      % 
       :
In [1]: f = open("foo.txt", "r")
In [2]: f.readline()
Out[2]: 'Some Random\n'
In [z]: f.readline(^)
Out[z]: ' in'
In [q]: f.readline()
Out[q]: 'es\n'
     % &   $ ?  
file
,  
 ,  
readlines()
. )&
readlines()
   % 
  " , $ "&&        $  
   . H
readlines()
%  $     $ !.
 % ,   %   . H
readlines()
  
siehint
 &  # %  ,    &  %
 #.         $  !
biglines.txt
,  '
10000   ,  '  $ ( 
80   .      
 !,  $, %   
 &  %  # $ ! N  (
  ,  ?  (   &   1024  ,  
 %  % (       $   %   "
& % # !:
In [1]: f = open("biglines.txt", "r")
In [2]: lines = f.readlines(102q)
In [z]: len(lines)
Out[z]: 102
In [q]: len("".join(lines))
Out[q]: 8262
In [5]: lines = f.readlines()
In [6]: len(lines)
Out[6]: 9898
In [^]: len("".join(lines))
Out[^]: 801^z8
      3  $ , %   %  102   ,  
     4  $, %  %  % (    
  8262.   " , %
  $   % 
,    &  %  #,  1024,   % 8262F 
      Python  
139
   $      ! ,    
  8   .  #  , %  
siehint
    $
 &  ,    (  # ,         #.
@   !"
)    $      # 
# %  #  $ ! , 
 '  $  #     !
 $ #  (  . ?
 
file
  &    ,   $ 
&  $ #   !.    ,  ' 
   & " ,  
write()
write()

   :   ,    & $ #  !.   
       
& $# (  !:
In [1]: f = open("some_writable_file.txt", "w")
In [2]: f.write("Test\nFile\n")
In [z]: f.close()
In [q]: g = open("some_writable_file.txt", "r")
In [5]: g.read()
Out[5]: 'Test\nFile\n'
   1  !  !   '
,  #   ' &
$.    2 $  !    .    4  $ 
  ? !              ,
   
, %  $ ' #  , ( &    $ '  
 #$  #     
. )   5  $ , % 
read()
 $ '   ,   $  !.
      $ (  !  
write
lines()
writelines()
  &$ #  :
   #  #, & '  # $  !. Y  
&  #$  #    #         , 
   ,  ',       +   ' %
 #  -     . ;'
  &   $   

writelines()
,   %  & $  ! 
' &   :
In [1]: f = open("writelines_outfile.txt", "w")
In [2]: f.writelines("%s\n" % i for i in range(10))
In [z]: f.close()
In [q]: g = open("writelines_outfile.txt", "r")
In [5]: g.read()
Out[5]: '0\n1\n2\nz\nq\n5\n6\n^\n8\n9\n'
)     !    , &  '  #$ 
 #& & $ (  ! +
  !  #  
140
 3. + 
      ,  &   $     #  #
 #"    -:
In [1]: def myRange(r):
...: i = 0
...: while i r:
...: yield "%s\n" % i
...: i = 1
...:
...:
In [2]: f = open("writelines_generator_function_outfile", "w")
In [z]: f.writelines(myRange(10))
In [q]: f.close()
In [5]: g = open("writelines_generator_function_outfile", "r")
In [6]: g.read()
Out[6]: '0\n1\n2\nz\nq\n5\n6\n^\n8\n9\n'
  $  #, % 
writelines()
 $     
   +
-   %     '  % # (    
 #  #,  $%  & $  !.    ,  
$ #, %    '  #$  #  # &    % 
$ (  !.  $ ' ,     %"  "  
$
writeiter()
[email protected] % #, %    (  (  $
  ,  '  '
        ,  
  ( %,      ( %&.
    
   #  !    ? ( 
file
 #
 7   Learning Python Y  K"  +[avid Ascher-
H  /  +Mark Lutz- +OReilly- + &  '  )  
  :
http:44safari.oreilly.com4569;55=864lpython=-10;&#x.247;&#x.2lp;&#x-9y6;&#xt-6.;ho7;&#x.2n=;&#x-10.; c-10;&#x.247;&#x.2lp;&#x-9y6;&#xt-6.;ho7;&#x.2n=;&#x-10.; hp7-10;&#x.247;&#x.2lp;&#x-9y6;&#xt-6.;ho7;&#x.2n=;&#x-10.; sec-10;&#x.247;&#x.2lp;&#x-9y6;&#xt-6.;ho7;&#x.2n=;&#x-10.; t=
$  ]ile Objects  
% Python Library Reference
+     )     :
http:44docs.python.org4lib4blt�inf�i
le�objects.html
   #  !   ' &(   ( 
 # $  generator expressions   % Python
Language Reference +     )     :
http:44
docs.python.org4ref4genexpr.html
-.    #  !   
  
yield
 # $  yield statement   %
 Python Language Reference +     )     
:
http:44docs.python.org4ref4yield.html
  "  
  % &   $              $
         
   $   #"  
      Python  
141
(     .   
    %  ,
     ,     ' %  #  (
   .        ,   
        &.      #$ &  
            , %   $ & ? & #
          .
   &   &$  Python  '     #
  
,    %          
            .    &    
 &       
      ?  
file
,   &  , %         " & !
  . K     ?    ?  
file
, &
     '  #$  # '   ,  
 #$ &    !.   '   #  ,  
    !   ,   #&      
 &   &   (  .
     &  &
        & 
      
stdin
   & +
sys.stdin
-. K 
sys.stdin
   & % & ? 
file
.    , %
 $  ,   $  #  & ? 
file
,  !
   
foo.txt
  ,  $   #   ? 
sys.stdin
In [1]: import sys
In [2]: f = open("foo.txt", "r")
In [z]: sys.stdin
Out[z]: open file 'stdin�', mode 'r' at 0x1q02�0
In [q]: f
Out[q]: open file 'foo.txt', mode 'r' at 0x121^9b�0
In [5]: type(sys.stdin) == type(f)
Out[5]: True
)      (  ?      ' ,
         '  . ;  &  ,
%  (%   %  $ &   ?    '  
  '      
 '  ,     
    % #&. ; ,  
sys.stdin.seek()
sys.stdin.tell()
 ,       $'  & 
%  +   %  % 
IOError
-.     
#           ?  
  $% #      '   # (  %
  !.
Y  
   % Python +    % IPython-  
%   "  &  .        #  #
$ # 
sys.stdin.read()
  $      % .
      # ,    ?
142
 3. + 
  ,  %   $
sys.stdin
   
  '   %              ,
  $    3.22.
% F.==. % A   , %+0 %"% sys.stdin.readline
#!/usr/bin/env python
import sys
counter = 1
while True:
line = sys.stdin.readline()
if not line:
break
print "%s: %s" % (counter, line)
counter = 1
       $     
counter
,    #  
    $     (   . Y    
while
,      & & %
          
. Y& '       &  &       '
 . @      & (  &       &
 ,       ,      , ' 
 $ &  . ; '            :
  '         +
-.      '
$  !,       .
;'   &  $#  
?  &      
who
  
    &:
jmjonesYdink:/psabook/code$ who ./sys_stdin_readline.py
1: jmjones console `ul 9 11:01
2: jmjones ttyp1 `ul 9 19:58
z: jmjones ttyp2 `ul 10 05:10
q: jmjones ttypz `ul 11 11:51
5: jmjones ttypq `ul 1z 06:q8
6: jmjones ttyp5 `ul 11 21:q9
^: jmjones ttyp6 `ul 15 0q:z8
Y   %    , % 
     '  $  #
 $     % ,   #$  # ! 
enumerate()
, 
 $    3.23.
% F.=F. % /# %" sys.stdin.readline()
#!/usr/bin/env python
import sys
for i, line in enumerate(sys.stdin):
print "%s: %s" % (i, line)
      Python  
143
  % #         ,  (     
 #  #
sys
 $    #$  #&   
stdin
. @ % 
' , %   % #         ,  (  
    #  #
sys
   #$  #&   
stdout
. @ ' ,

sys.stdin
  & ? !,    & % &, ?

sys.stdout
  & ? !,    & $.
)  ' , 
sys.stdin
 ' , %  ? !,  
  & % &, ?
sys.stdout
 ' , %  ? !
,    & $:
In [1]: import sys
In [2]: f = open('foo.txt', 'w')
In [z]: sys.stdout
Out[z]: open file 'stdou�t', mode 'w' at 0x1q068�
In [q]: f
Out[q]: open file 'foo.txt', mode 'w' at 0x121^96�8
In [5]: type(sys.stdout) == type(f)
Out[5]: True
' $ % :     '   '  #  '
,   #    !,   & % &,    !,
  & $,  & &     ' :
In [1]: readable_file = open('foo.txt', 'r')
In [2]: writable_file = open('foo_writable.txt', 'w')
In [z]: readable_file
Out[z]: open file 'foo.txt', mode 'r' at 0x12qz5z�0
In [q]: writable_file
Out[q]: open file 'foo_writable.txt', mode 'w' at 0x121^968�
In [5]: type(readable_file) == type(writable_file)
Out[5]: True
' $ #, %
sys.stdout
 '  $% #      
 #&  ? 
file
,   & $, %  ' 
sys.stdin
 '   #&  ? 
file
,  
& % &.
  #  % ,   ! &,  &&    ,
 $%  &    ?  
file
,   , 
     #,          ,    
? 
file
F     "      , %    #$ 
 #&   
StringIO
In [1]: from StringIO import StringIO
In [2]: file_like_string = StringIO("This is a\nmultiline string.\n
144
 3. + 
readline() should see\nmultiple lines of\ninput")
In [z]: file_like_string.readline()
Out[z]: 'This is a\n'
In [q]: file_like_string.readline()
Out[q]: 'multiline string.\n'
In [5]: file_like_string.readline()
Out[5]: 'readline() should see\n'
In [6]: file_like_string.readline()
Out[6]: 'multiple lines of\n'
In [^]: file_like_string.readline()
Out[^]: 'input'
       $  ?
StringIO
,       
  &   
"This
a\nmultiline
string.
\nreadline()
see\nmul
tiple
lines
of\ninput"
.      &#  $ '  # $ #

readline()
? 
StringIO
. &       #$ &
# 
readline()
,          ,
$    ?  
file
In [8]: dir(file_like_string)
Out[8]:
['__doc__',
'__init__',
'__iter__',
'__module__',
'buf',
'buflist',
'close',
'closed',
'flush',
'getvalue',
'isatty',
'len',
'next',
'pos',
'read',
'readline',
'readlines',
'seek',
'softspace',
'tell',
'truncate',
'write',
'writelines']
  % ,  '  !        $%&,  
!   $ &     ( 
#  '   #$   ! 
  . ;'   &         ? 

file
 ?  
StringIO
      Python  
145
In [9]: f = open("foo.txt", "r")
146
 3. + 
     #, %    #   %  $
)  ,    #   $ % &  $  & &  
    80     %  
  .    ,
% ?  ! ,  $    
urllib
,  '  
read()

close()
.    ,   '  
read
line()
readlines()
fileno()
info()

"  
147
J  ?G:
apache_log_parser_split.py some_log_file
 Q  -    -  -  : - 
,    +   3.    - 
      ,  7    3  X X    + ,
  X -  X.
import sys
def dictify_logline(line):
'''7 3,  7  -Q@,   @ 
-+  
G  7  -    @ 3    X X 
      X + ,       -
+ +   .
'''
split_line = line.split()
148
 3. + 
except IOError:
print "ou must specify a valid file to parse"
print __doc__
sys.exit(1)
log_report = generate_log_report(infile)
print log_report
infile.close()
|   % $%   .  $ 
__main__
 & &  
  #  .   (,   & & #  ( 
&             , %    #&, %
   %      . {  #$  # $
     $   ,        
&  #$ &  $ "  . J    '  ,
 %"   #            ,
  &   13. Y ,  $ 
__main__
  &  
   #  $ ! '. {     #
! $ " &   % ,        &
 #$ &  $ "  .         
! ! 
generate_log_report()
    $#  .
* &
generate_log_report()
 $   #,    #
% .       & (  (    !    
'     ! 
dictify_logline()
, &    %  #  $
  #,  '  (   ! .  
   & , && &  $% 
bytes_sent
  % . {
   % ,       ' &,    &
&   (      .      &   #
%   ,  %  ! 
dictify_logline()
. ;  ,
  $ !    # %     
$ 
__main__
* &
dictify_logline()
  $       , $
         $  %       $
 #  , $
%  $   .
J    #    F        #  #
    $   3.25.
% F.=6. "/+&  A  # &   -�  
Qpache #-   -%
#!/usr/bin/env python
import unittest
import apache_log_parser_split
class TestApacheogParser(unittest.TestCase):
def setUp(self):
pass
def testCombinedExample(self):
"  
149
#  -+ -     apache.org
combined_log_entry = '12^.0.0.1 \
' frank [10/Oct/2000:1z:55:z6 0^00] '\
'"ET /apache_pb.gif HTTP/1.0" 200 2z26 '\
'"http://www.example.com/start.html" '\
'"Moilla/q.08 [en] (in98; I ;Nav)"'
self.assertE~ual(
apache_log_parser_split.dictify_logline(combined_log_entry),
{'remote_host':'12^.0.0.1', 'status':'200', 'bytes_sent':'2z26'})
def testCommonExample(self):
#  +7  -     apache.org
common_log_entry = '12^.0.0.1 '\
' frank [10/Oct/2000:1z:55:z6 0^00] '\
'"ET /apache_pb.gif HTTP/1.0" 200 2z26'
self.assertE~ual(
apache_log_parser_split.dictify_logline(common_log_entry),
{'remote_host':'12^.0.0.1', 'status':'200', 'bytes_sent':'2z26'})
def testExtrahitespace(self):
#      3- + - -  -
common_log_entry = '12^.0.0.1 '\
' frank [10/Oct/2000:1z:55:z6 0^00] '\
'"ET /apache_pb.gif HTTP/1.0" 200 2z26'
self.assertE~ual(
apache_log_parser_split.dictify_logline(common_log_entry),
{'remote_host':'12^.0.0.1', 'status':'200', 'bytes_sent':'2z26'})
def testMalformed(self):
#      3- + - -  -
common_log_entry = '12^.0.0.1 '\
' frank [10/Oct/2000:1z:55:z6 0^00] '\
'"ET /some/url/with white space.html HTTP/1.0" 200 2z26'
self.assertE~ual(
apache_log_parser_split.dictify_logline(common_log_entry),
{'remote_host':'12^.0.0.1', 'status':'200', 'bytes_sent':'2z26'})
if __name__ == '__main__':
unittest.main()
|          !   $
   ' ,    #" $ 
      , %
 $ " &   % . ;'  & &  $#     
&:
jmjonesYdinkgutsy:code$ python test_apache_log_parser_split.py
...F
======================================================================
FAI: testMalformed (__main__.TestApacheogParser)

Traceback (most recent call last):
File "test_apache_log_parser_split.py", line z8, in testMalformed
{'remote_host': '12^.0.0.1', 'status': '200', 'bytes_sent': '2z26'})
 3. + 
AssertionError: {'status': 'space.html', 'bytes_sent': 'HTTP/1.0"',
'remote_host': '12^.0.0.1'} != {'status': '200', 'bytes_sent': '2z26',
'remote_host': '12^.0.0.1'}

Ran q tests in 0.001s
FAIED (failures=1)
    , %      
 &#  "(   , 
    &    $   #    $  .
  &  $ #  # (  " %   .  &#   
! &( !   $   '
 ,  '   %   
 $  #      ( (
   %   (  ,
&#       &       .   3.26  
 &  $  '    &,      
    &( ' .
% F.=;. ?A & # &   -�   Qpache
#!/usr/bin/env python
J  ?G:
apache_log_parser_regex.py some_log_file
 Q  -    -  -  : - 
,    +   3.    - 
      ,  7    3  X X    + ,
  X -  X.
import sys
import re
log_line_re = re.compile(r'''(|Premote_hos�t\S) #IP ADDRESS
\s #whitespace
\S #remote logname
\s #whitespace
\S #remote user
\s #whitespace
\[[\[\]]\] #time
\s #whitespace
"["]" #first line of re~uest
\s #whitespace
(|Pstatu�s\d)
\s #whitespace
(|Pbytes_sent� \d)
\s* #whitespace
''', re.ERBOSE)
def dictify_logline(line):
'''7 3,  7  -Q@,   @
 -+  
"  
151
G  7  -    @ 3    X X 
      X + ,       
- + +   .
'''
m = log_line_re.match(line)
if m:
groupdict = m.groupdict()
if groupdict['bytes_sent'] == ' ':
groupdict['bytes_sent'] = '0'
return groupdict
else:
return {'remote_host': None,
'status': None,
'bytes_sent': "0",
}
def generate_log_report(logfile):
'''7 3  - :
remote_host=�[    X + ]
 Q - +W   file,  +X
 X             + ,
  X  - +7    X    +   .
'''
report_dict = {}
for line in logfile:
line_dict = dictify_logline(line)
print line_dict
try:
bytes_sent = int(line_dict['bytes_sent'])
except alueError:
## [email protected]  3    - +
continue
report_dict.setdefault(line_dict['remote_host'],
[]).append(bytes_sent)
 3. + 
{   & ! &, & $ #      
 ,    $     ,  ! &
dicti
fy_logline()
.     $  &, %  $% &,  $ 
    !  ,  &  '     ,    
    &( ' .    , %  $ #
   $ '    ,    #$ # ?   
    &  ' &,
log_line_re
, & & &  
      #  
match()
. {     '  ,
  #  
groupdict()
$  &  %      $
   ,  $% 
bytes_sent
  &  0, 
   '  %  +
- +  %  %  $%  # -.
{         ,
 $ &  #   ' 
 %,   $% &    , 
 0.
Y   #   &  &,  &   #$   
&( ' ,   %" , %    &F Y,   .
;'   &  #  &       & $
!  '     Apache:
#!/usr/bin/env python
import unittest
import apache_log_parser_regex
class TestApacheogParser(unittest.TestCase):
def setUp(self):
pass
def testCombinedExample(self):
#  -+ -     apache.org
combined_log_entry = '12^.0.0.1 \
' frank [10/Oct/2000:1z:55:z6 0^00] '\
'"ET /apache_pb.gif HTTP/1.0" 200 2z26 '\
'"http://www.example.com/start.html" '\
'"Moilla/q.08 [en] (in98; I ;Nav)"'
self.assertE~ual(
apache_log_parser_regex.dictify_logline(combined_log_entry),
{'remote_host':'12^.0.0.1', 'status':'200', 'bytes_sent':'2z26'})
def testCommonExample(self):
#  +7  -     apache.org
common_log_entry = '12^.0.0.1 '\
' frank [10/Oct/2000:1z:55:z6 0^00] '\
'"ET /apache_pb.gif HTTP/1.0" 200 2z26'
self.assertE~ual(
apache_log_parser_regex.dictify_logline(common_log_entry),
{'remote_host':'12^.0.0.1', 'status':'200', 'bytes_sent':'2z26'})
def testMalformed(self):
#   - Q -   +-    apache.org
#malformed_log_entry = '12^.0.0.1 '\
ElementTree
#' frank [10/Oct/2000 1z:55:z6 0^00] '\
 3. + 
 #$  ?        +[ocument Object Mo
del, [OM-.            &$  Python ( 
  [OM XML.   , $  [OM  % &
     #      &  #" & , %  SAX,  
 %  %    XML  & #      $  #
 ?  & '  $  .      #$ &
[OM $ % &  , %    &  ' # ! 
   &,   '  $  ( !   
# (  % ( $(.       !  [OM  %
"  % (  & $ #   %   $ .
) &   #&  $ '  # ElementTree. ElementTree  
    %   $ XML, & (       
     &$  Python, %&    Python 2.5. J
  ElementTree  '    #   ,      
$  [OM,            !  .    
         #$   $    &
 $% # ?  & . H  & #      
 #$  # ElementTree. {  
  $      #  & #
  %   $    XML,    %  
 #$  #&   ElementTree.
    # ElementTree   # $ !  ! 
XML,   %       #       #   
 ! ! 
parse()
ElementTree
  & $  XML! 
parse()
$   ElementTree
 $    $ ?  ,     $ &
    
tcusers
.     &    &  '  #
$  #& & $   $% $    !
XML. ; #"    &    &     
? :
find()

findall()
. H
find()
    $ ,  
   $ ,      &,   $ ?
Element
,   &  $ . H
findall()
   $
,     $ ,   $  ? 
Element
   &   $.
  % # "  , 
 '    #  
find()

find
all()
, %    '    '
  &$ XPath.  % 
         '  $ # & ,  
,  
     %     =  
,    
   $=  
,    
    
%  $, %&
%    .    " +
-  '
 #$  #&  %   $  &      .    #
 
find()
           #   $ 
user
 !  #$    Tomcat:
In [q]: first_user = tcusers.find('/user')
In [5]: first_user
Out[5]: Element user at abdd88�
H     
find()
 
"/user"
. ;%#    
"  $      #  %      $ . @ 
'user'
 & & , 
  &   #.    
 , % 
find()
    $    
user
.  #   , %
?    
first_user
  ' 
Element
 %     ( &        ? 
( &
 3. + 
ElementTree
array�
dic�t
ke�y_name/ke�y
string�os_overview/strin�g
ke�ykernel_version/key�
string�Darwin 8.11.1/string�
ke�yos_version/ke�y
string�Mac OS 10.q.11 (8S216^)/strin�g
/di�ct
/arra�y
   ,  %   " $&
 !  XML !    
 % F Y   , %    
$   XML      
.         
 &  (. )  
      $% &, 
key

string
, $ %   
 '   #  . $&    3.28.
% F.=8. R#- &,   #/ +# +
system_profiler  Uac VS X
#!/usr/bin/env python
import sys
from xml.etree import ElementTree as ET
e = ET.parse('system_profiler.xml')
if __name__ == '__main__':
for d in e.findall('/array/dict'):
if d.find('string').text == 'SPSoftwareDataType':
sp_data = d.find('array').find('dict')
break
else:
print "SPSoftwareDataType NOT FOUND"
sys.exit(1)
record = []
 3. + 
dink:/code jmjones$ python elementtree_system_profile.py
_name � os_overview
kernel_version � Darwin 8.11.1
os_version � Mac OS 10.q.11 (8S216^)
J      
        
&$  Python. H   &  #$ &    , %    #
 &  $ '  #.   '     #  #$  #&  
 SAX  [OM,  &        &$  Py
thon,    , %    $     # 
ElementTree.
 ; 
      $%    !   # 
     &$ Python. H        
string
,   & ' &,        
 ,   &
StringIO

urllib
$       .  
   #$    %  $&  (  ( $
!  '      Apache.  $ %     
     &   ElementTree      
     #$ & 
&  " &  %  ( $ %.
   &  %   , %  #"       
     UNIX,    %# $(       
 ' , %   $ &
grep

awk
,  &    # 
 &$ Perl. & Perl   &    % #   &$
  &,          ,   
, % &$ Python  '   ' # % #   #"  $ ' 
 . * %  ,     %  # %        
,     '         ?      
      &,  %  , % &$ Python  
      &$  Perl.      &, %
  $,     &    #&   (   #
 $  #    ,  %   &$ Python.
    
 "  %  $ &,  $ (   #(    ' 
 #(            && &  
$%  !          &  #$  
 . |     '    &   "  #$  &,
   %  #   
, ,  $ ' ,   
   #$  &,   %   %   , " "  
$ ,  '   #&  
  (       $  
&    .    %  $     && & 
%   '   "  & #  . ;      
,        (  #  $& #&,   ,  
  ,  ' .   #        ' Python. ; ,
Python  " $   
,     '   #, 
!    #   #    $    .
       %      ( (:
 , !       % !  ( 
 (. /& ! &,
       
 #&,      :   ' (  #&  !( ' ,
      ,   '  #      $#     
&  (  ,   ' 
' (  #& 
 #  $
(.    , %  (    #,    #  ( 
 ! .   "      % ! 
  & $ % &  , %  !  #   ! 
. Y& !  &  '  #$  #   !  , 
P[], PNG, `PG, VTML  ' %  . ;  ,  ( 
    #   !   &
,  $      .
;  & #,   $  $       
 % #    ! : 
     % ,   
   & !       #$    .
 4. )"     
*  " ' ! 
  "          #$  !  $ 
% &  , %    # .       &  ,  
  &      ! : @  + 3-  SNMP
+ 7-.   #    ' &  ,   
$%    $  $ %
& ( $  .  %  
 ,    $      
 $ !  '     
Apache $  & IP     , %     ( 
 '        &&   VTTP.   7  
 &     & $  
    %   
$ $  ! , %& ?  D    
      (  !  .
  !   ' $ #&    '  , %    
   $ %    ( (.       '
$ #& &$   %  
!  $      
&,  , $ ! '
    Apache,   (  
      ' %   &      #$ 
&. ; ,     #,
%   (   $  # 
,  $ %    , $' ( '  
#      # IP    $  &     
    Apache,        !      % #
  & '   $ ! '     Apache,  (
  $  &  ( & ! & +   % : IP
    %     (   & '  $ -,   
(      ( (,      '
  % #.    ( ( (   ' #
 &  $ (, ?  $ (, !(
 ? , !  !  qS  %   !.
  " & %    $       ?  #  
  & & $ ,  & (
    (  
(.  %   , $ #   
$ ,    #    
$ % & ( $  3     ( & (, '
    12.        #$  # '  
, % #   , 
&        .
H  '    #$  #  #
shelve
,     
    12, &  ( & !   VTTP$ (,   
( '        .
;'   &     #,     #$ &  #
$ !  '    
 Apache,  $     
   ,   #
shelve
#!/usr/bin/env python
import shelve
import apache_log_parser_regex
 "  *  
161
logfile = open('access.log', 'r')
shelve_file = shelve.open('access.s')
for line in logfile:
d_line = apache_log_parser_regex.dictify_logline(line)
shelve_file[d_line['remote_host']] = \
shelve_file.setdefault(d_line['remote_host'], 0) \
int(d_line['bytes_sent'])
logfile.close()
shelve_file.close()
     %    &  
shelve

apache_log_
parser_regex
. H #
shelve
(            
&$  Python. H #
apache_log_parser_regex
  #, 
  $     3.    & ! '   
  Apache
access.log
 !,     (& #& $ % &
! &,
access.s
. Y  & & (  (    !
'     #  & $  ' & '    
 $  &  #.  #  '   && $  VTTP, IP
       %  , 
 (   .     
&  %   &   $    %  ,
 '   (    ?
shelve
&   IP 
 . {  ?
shelve
    $# &  $  IP
  ,  %   ( 
    %    
&  .   (   (    ! '  $
   !,   ' ?
shelve
. |     #
$  #&      ,          !   
& ! .
 C " 
   '   #   , %   &  %   '
 #  #      !  ,     ,   .  
 # , %    &   #    ,   $ ( 
 '  & #&  ,  '  $ (    $ ' 
 # & #   &      % .  %  
&,  &  
    '     % &
 '    #  ,  '      %  #
$  #     %    (
$   % ! .  
%  %     %   % &  '   & #
  &      %   !     (    % .
)     &  '    #$  # &    & % 
   #    #       %  & &
  .
Y&  % &            %  % 
 #$ &   : IMAP  POP3.          Py
thon,   ( &    ,   &  ,  '
    .
 4. )"     
)$  ( (   ,  ',   %  #$ &  
 POP3         % %  $     
 ' $  #    #  &
poplib
.    4.1   
 &   ,  #$  #
poplib
&  % 
&  (   , (&(&   $     ,  $
 (  # !   .
% G..  !  & +     PVPF
#!/usr/bin/env python
import poplib
username = 'someuser'
password = 'SzCrz^'
mail_server = 'mail.somedomain.com'
p = poplib.POPz(mail_server)
p.user(username)
p.pass_(password)
for msg_id in p.list()[1]:
print msg_id
outf = open('%s.eml' % msg_id, 'w')
outf.write('\n'.join(p.retr(msg_id)[1]))
outf.close()
p.~uit()
   ,      & %  & &
username
+&
 #$  &-,
password
+ #- 
mail_server
+        %
-.    & &  % 
  ,      &
    &  #$  &   #.    ', %  
       " ,    %  $ '  #  
  #     %  &   %   $.    
     & & (     , $ %   $#
 (     !   . {    , %     
        & 
 & &       (  
% &.    #     &,   %    #
  $   
dele()
 
retr()
      IMAP  $ &  %   '   , 
   POP3,       (  "   
         &$  Python.    4.2 
  &   , 
 & '   &,
%      ,   
 #$     IMAP.
% G.=.  !  & +     WUQP
#!/usr/bin/env python
import imaplib
username = 'some_user'
password = '^0P5zCrz^'
mail_server = 'mail_server'
)*    &
163
i = imaplib.IMAPq_SS(mail_server)
print i.login(username, password)
print i.select('INBO')
for msg_id in i.search(None, 'A')[1][0].split():
print msg_id
outf = open('%s.eml' % msg_id, 'w')
outf.write(i.fetch(msg_id, '(RFC822)')[1][0][1])
outf.close()
i.logout()
         , $ 
#  '    %  &
 & &
username
+&  #$  &-,
password
+ #- 
mail_
server
+        % -.    & &  % 
   IMAP %  $ SSL.    & & (     
     % 
INBO
.   % & (
  , %  
   . H
search()
 (         
   &$  Python. |    &$ #( 
             .       
&& &  F    !   '   $ #&F 
         #$  #&F  # ! &
&  F H  ' ,  %
,    #, % %  IMAP
R]q ' &   $,  , % #,     #$ &  
 IMAP  &   % ! ,  $ &  
$  # $ %   (   , (&(&   . ; ' 
     & & $#  '    &   .
  $  #, %       &       % 
  %  . Y&    '     & #  #" 
  ,       $  #" ,     &
 &#,     $ #        .
' !   ;
   '    '      !  %
.  #  $  & ! &, &   & 
        %.
 %       ' 
              IP    
 ! ,              % ,   
  !       IM        % 
  "   . { #,  % ,    ,    
& #,    ,  #"  % #   ! . 
 4. )"     
     :   RESTLESS
  (Aaron Hillegass)
K   ,  "  &( NeXT
 Apple, && &        $ 
  '  &       Mac.
 && &     qocoa Programming
for Mac OS X +Big Nerd Ranch-      
    !  qocoa  
Big Nerd Ranch.
$   (      ReSTless $   $ 
&              :
http:4
4www.oreilly.com4978569;668=9
. ;'  $ ,  $ #
   &$ Python $ "   qocoa ' &:
#import "MyDocument.h"
Yimplementation MyDocument
(id)init
if (![super init]) {
)*    &
165
[super windowControllerDidoadNib:aController];
// + 3  - X7     - 
[self prepareEditiew];
#pragma mark X   
// X  (UR   -  file:)
 4. )"     
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
path = Y"/ibrary/Frameworks/Python.framework/ersions/
/Current/bin/rst2html.py;
}
[task setaunchPath:path];
// @ 3    ReST
NSPipe *inPipe = [[NSPipe alloc] init];
[task setStandardInput:inPipe];
[inPipe release];
// @ 3    HMT
NSPipe *outPipe = [[NSPipe alloc] init];
[task setStandardOutput:outPipe];
[outPipe release];
// ?  3 Q 
[task launch];
//  3     
NSData *inData = [[textStorage string] dataUsingEncoding:
NSUTF8StringEncoding];
//   3      3 
[[inPipe fileHandleForriting] writeData:inData];
[[inPipe fileHandleForriting] closeFile];
//   3   
NSData *outData = [[outPipe fileHandleForReading]
readDataToEndOfFile];
// ?  3 
[task release];
return outData;
(IBAction)renderRest:(id)sender
// ?  3  ,  + 3 3  ,
//    ++ 
[progressIndicator startAnimation:nil];
//  3 html   NSData
NSData *htmlData = [self dataForHTM];
// G 3 html   ebFrame
ebFrame *wf = [webiew mainFrame];
[wf loadData:htmlData
MIMEType:Y"text/html"
textEncodingName:Y"utf 8"
baseUR:nil];
//   3  ,  + 3 3  ,
//   ++   
)*    &
167
[progressIndicator stopAnimation:nil];
// G   +   - @
(IBAction)startSavePanelForHTM:(id)sender
//  X 3  -@|
NSString *restPath = [self fileName];
 4. )"     
;  &  % $%( #
 ,    &   
' # $ #   !  ,  $ & reStructuredText
+ reST-.    & !  reStructuredText    :
reStructuredText    & & % &,   %& 
'      ' %  "#,   % "#   & 
 & $           %   $.
{    #$  # &         
+ ,    (    & &$  Python-, &   
  $ &   , &  $ &   & #(  
. $  reStructuredText     $ '  # 
" &  '  $%(   (  .   % 
  $  reStructuredText
&& &     % #  
[ocutils. $  reStructuredTe
xt   &       
   $    (
  $  StructuredText
Setext.
*  ReST %  &   %  # !   &  $ &
    &$ Python. {   $    
 &$ Python   "  ' #     $  PyPI, 
  '  #, %     #&   &   
 # !  ReST. H    & #  ,  #$
)*    &
169
 &$ Python,  & !  ReST  %      &
!  &     .
)  ,   '       ReST  !  ,  #
$  &  $ &   F   (,    %   .
  (, $    $   (   %   $.
 #    $ &      ,   
%   #, %     
 . ;'   & % #
     !  !  ReST:
=======
Heading
=======
SubHeading

This is just a simple
little subsection. Now,
 4. )"     
In [q]: html = docutils.core.publish_string(source=rest, writer_name='html')
In [5]: print html[html.find('bod�y') 6:html.find('/body�')]
div class="document" id="heading"�
h1 class="title"�Heading/h1�
h2 class="subtitle" id="subheading"�SubHeading/h�2
�pThis is just a simple
little subsection. Now,
)*    &
171
gibson 192.168.1.z2 print server
============== ============ ================
In [8]: html = docutils.core.publish_string(source=server_list,
writer_name='html')
In [9]: print html[html.find('bod�y') 6:html.find('/body�')]
div class="documen�t"
table border="1" class="docutils"�
colgrou�p
col width="zz%�" /
col width="29%�" /
col width="z8%�" /
/colgroup�
thead valign="bottom"�
tr�th class="head�"Server Name/th�
th class="head�"IP Address/th�
th class="head�"Function/th�
/t�r
/the�ad
tbody valign="top"�
tr��tdcard/t�d
td�192.168.1.2/td�
td�mail server/td�
/t�r
tr��tdvinge/td�
td�192.168.1.q/td�
td�web server/t�d
/t�r
tr��tdasimov/t�d
td�192.168.1.8/td�
td�database server/t�d
/t�r
tr��tdstephenson/td�
td�192.168.1.16/t�d
td�file server/td�
/t�r
tr��tdgibson/t�d
td�192.168.1.z2/t�d
td�print server/t�d
/t�r
/tbo�dy
/tab�le
/div�
{  $ % #&    &  & $  $ & Tex
tile.       : Textile  %    
  $     $    $  XVTML.
| !   #$ &   
 ' &(,   (  &
 ',     %       !  . {
Textile && & &$  $ ,  %    &   ,
 4. )"     
 &   &$  PythonF %  , % & &$  Python 
    , &  $ 
&   # $  Textile
  $  #  XVTML.   '  # #  
      , &    #     $ 
 # ! $ !   Textile  !  XVTML. )  ' $
 #  #,  &  $  !   Textile,   
             #  %  $ 
 XVTML.    % $  Textile   #   Textile
  $ #&   (   #    $    .
D   #  # Textile  '    #  
easy_install
textile
    #    &  ,   &
"     .  Ubuntu,  ,  $ &
python
textile
    #   '  
get
install
python
textile
 #  # Textile 
   ,   '   #
  #$ ,     &  ,  $ & ?
Textiler
 $&       ? . ;'   & 
   $ &       $ !   Textile  ! 
 XVTML:
In [1]: import textile
In [2]: t = textile.Textiler('''* item one
...: * item two
...: * item three''')
In [z]: print t.process()
ul�
li�item one/l�i
li�item two/l�i
li�item three/l�i
/u�l
H      #&  # $ #  !   Textile.   
 &  '         !  . ; ,    
http:44hobix.com4textile4
  %       #$ 
 Textile. &      & "  & #&  
 !   Textile,     ,    ,    # ! 
 Textile & !  & ! ,    %, 
           IP    ! &:
In [1]: import textile
In [2]: server_list = '''_. Server Name_. IP Address_. Function
...: card192.168.1.2mail server
...: vinge192.168.1.qweb server
...: asimov192.168.1.8database server
...: stephenson192.168.1.16file server
...: gibson192.168.1.z2print server'''
In [z]: print server_list
_. Server Name_. IP Address_. Function
)*    &
card192.168.1.2mail server
vinge192.168.1.qweb server
asimov192.168.1.8database server
stephenson192.168.1.16file server
gibson192.168.1.z2print server
In [q]: t = textile.Textiler(server_list)
In [5]: print t.process()
tabl�e
tr�
th�Server Name/th�
th�IP Address/t�h
th�Function/t�h
/t�r
tr�
td�card/td�
td�192.168.1.2/td�
td�mail server/td�
/t�r
tr�
td�vinge/t�d
td�192.168.1.q/td�
td�web server/t�d
/t�r
tr�
td�asimov/�td
td�192.168.1.8/td�
td�database server/t�d
/t�r
tr�
td�stephenson/t�d
td�192.168.1.16/t�d
td�file server/td�
/t�r
tr�
td�gibson/�td
td�192.168.1.z2/t�d
td�print server/t�d
/t�r
/tab�le
   ,  !  , ReST  Textile,   !!   #$ 
 #&   &(  &$ Python &  $ &  (
(. {     #   &    ,   
       ,    &  $  #  ! 
VTML  $    #      #  &
+ , & # VTML 
     %     #
VTML    #         ]TP-, 
  docutils  Textile  ' $ #& &    $  
  .
 4. )"     
&   
! 
         %
!     (,  
 ( , $ % &  !    (  , %  (
   '    #    #. H %  , % ! 
& '  #        ,   ,     
 ,      #,   %" ,  !   
    #.  (
%   %  $ &   
!   ReST  Textile (  $       ! 
 & ! ,    (  (    %
&  % #   $  '  ( (   
   #  .
D !    ' % $
  ( (  (   '   $ !
'     Apache, $   $  & IP   
   %     ( 
.      $  ,  
'&   ,   $    ' % !,  '
! ,          #&  .   
        ' %  !   $   ,
%          #:
#!/usr/bin/env python
import gdchart
import shelve
shelve_file = shelve.open('access.s')
items_list = [(i[1], i[0]) for i in shelve_file.items()]
items_list.sort()
bytes_sent = [i[0] for i in items_list]
#ip_addresses = [i[1] for i in items_list]
ip_addresses = ['...' for i in items_list]
chart = gdchart.Bar()
chart.width = q00
chart.height = q00
chart.bg_color = 'white'
chart.plot_color = 'black'
chart.xtitle = "IP Address"
chart.ytitle = "Bytes Sent"
chart.title = "Usage By IP Address"
chart.setData(bytes_sent)
chart.setabels(ip_addresses)
chart.draw("bytes_ip_bar.png")
shelve_file.close()
            &,
gdchart

shelve
. 
   ! ( ? ,  $      
  . ?
shelve
   '  !  , %    
,    
 
dictionary
,     &  $ '  # $ #  
items()
. |   $ 
 ' ,      
 '     %  
&,        $% 
  %.     
items()
  %  $ '  #
     (, %      # ,   
%    # .    ,    #     
    &   &  &       '(. @  #
   '      
(ip_address,
bytes_sent)
  % 
 '
(bytes_sent,
ip_address)
.    & &      
'    ,    #   '   '       &
& & $% 
bytes_sent
, 
list.sort()
       
     . Y    #       $  &
$% &
bytes_sent

ip_address
.    , %   
   IP   , $  ( $%  
...
,  
%  &       %   $ ! '
      .
     (,   
(      
,  '   #  $  !%      &, 
 #$&  #
gdchart
. %  $  & ?
gdchart.Bar
. |  
  ? ,     (     # $% &
 (   ,  $      #  '  $ #
  ! PNG.      & & $  
    &(,  !           $  & $  
. D  &     & ,  % 
 $#  $ ! '     Apache.  $ % 
$ & 
draw()
,      !,   $
  & $   ! (. )$ '   %   
  $  . 4.1.
;'   &    
 &,  &  $
$ (, ( &(&  !
(,    $  
  $    ,    :
#!/usr/bin/env python
import gdchart
import shelve
import itertools
shelve_file = shelve.open('access.s')
items_list = [(i[1], i[0]) for i in shelve_file.items() if i[1] � 0]
items_list.sort()
bytes_sent = [i[0] for i in items_list]
#ip_addresses = [i[1] for i in items_list]
ip_addresses = ['...' for i in items_list]
chart = gdchart.Pie()
chart.width = 800
chart.height = 800
chart.bg_color = 'white'
 4. )"     
color_cycle = itertools.cycle([0xDDDDDD, 0x111111, 0x^^^^^^])
color_list = []
for i in bytes_sent:
color_list.append(color_cycle.next())
chart.color = color_list
chart.plot_color = 'black'
chart.title = "Usage By IP Address"
chart.setData(*bytes_sent)
chart.setabels(ip_addresses)
chart.draw("bytes_ip_pie.png")
shelve_file.close()
  &    &  %     %    
  $   #   % &.   (,     
 $  &  $ & ? 
gdchart.Pie
,  
gdchart.Bar
.   (,
   #   & '    . |
 &     , 
      %   
,       $ ' %  #,  &$  %  
 &  "  $  # %    (     
  .    (  (     $     #
.4.1.
 %%  -&,  "+0  # %
 " WP�" 
,    
! 
cycle()
$  &
itertools
. H         #
    #
itertools
.     & $% # %
  ( ! ,   
       
?  +  ,   -.  $#       &,
 $     ,   &  . 4.2.
{               , %  
$ "  '  +   - IP   ,    (  
 # $% &   (  .    
        %
  &  (, ( &
(&  ! (,     $ &  $& 
     ,   %  (    #   
 .
.4.2.
3  " %%  % -&,  "+0
 # %  " WP�" 
 4. )"     
PFG
Y        & !  $ !    $
% &   (  (  !  P[]. *  P[]     
     '  ,   
    #, %   
  '  $  #  P[].      $  #   
 !  P[]  '      % # '$#    
    .    % &   $    '
 & #  %  $& &
 $ & %   !  P[]
$'     ,  % ( $
&(  #$       .
H  ' "       %    &   
P[]    &      % 
  #$   &$  Python.
J  ReportLab    ,  $% ( &  
  !   P[],  '  #  350       .
   ,   '      
http:44www.reportlab.com4
docs4userguide.pdf
,   $% # %     #
$ &   ReportLab.     $    & #
      $  #&  !#       
 ReportLab. Y&     
  ReportLab  Ubuntu  
%  #  
apt
get
install
python
reportlab
. {   #$ 
#     ,   #$ #   #   '  
          . )%       #  $ '
  #  % #     (   .
   4.3   &  
 #$ &   Report
Lab &  $ &       P[] Vello World.
% G.F.  % PDY Kello Zorld
#!/usr/bin/env python
from reportlab.pdfgen import canvas
def hello():
c = canvas.Canvas("helloworld.pdf")
c.drawString(100,100,"Hello orld")
c.showPage()
c.save()
hello()
; (  #    #   # $ %     $ &
P[]    Vello World.   (, %   $  ?
canvas
. Y   #$  
drawString()
,   ' %
 #      
file_obj.write()
 %  ( ! .
 $ %   $ 
showPage()
, $ "   
 &,  
save()
,  ! %    $  ! P[]. {
   #   ,   $#    %     
 %   P[]   # Vello World    $.
{  $$     (      Re
portLab,   '   #$  #
&  ,    % 
,    
179
   !  &   . @  #  $   
  $   !  P[],   ' $% #    
 #,     #   ReportLab  '  #& $%
( $#( !! .
@  #,     ,     #   ReportLab  $
 &    P[],   ,   '   #  $  # 
%   #$        . @  %  ' 
$ #&  #   $. $&    4.4.
% G.G.  - /# "    
#!/usr/bin/env python
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
def disk_report():
p = subprocess.Popen("df h", shell=True,
stdout=subprocess.PIPE)
 4. )"     
beginText()
.    & &    $  & (   
 . ;"     ' #   $   8.5
11 
 ,   , %      #      (  ,   
     ? , % 
 (  #&  11 (
%   .      $  & $       
   ? ,   $ "   ,  && (  
  ,  % (   $#     
.   
 : $ #  #$  
line.strip()
&   &     
    . {      #,           
    #      % (   .
) &  $ '  #  $  #      '   
P[], &&    $ ' &,         '
$ #   & % &   ( 
      #$  &,  
 &        ReportLib.  , %   $
 (   ,  && &   ? , (& 
 ,    & $ #.
=      ! 
          !   ,  ( 
    # ( , $  
  (  % .    $ 
   %       %      
 #      % . { 
    &    #  
       ,     # "  #$  
,   '  #$  # &     ]TP. ) #$ 
      & Python &       ]TP  
       .
   C " 
        %  && & '    &   &
#         . H  , %  (  &
& #  %    ,   % (  &  
 #        '        % .  
 &   &$  Python    &   ' 
 $ '   & #   &      % ,   (
     & % #  . /       
'   #  # ' 
  ($   $  
       % ,       $    $ ,
  '  " # $ $ $ %, &$     
 % ,  #$& &$ Python.
      ': "
    Python ( &   $(    ,  $ 
&( & #   &       % .  $ 
    , smtplib,   &     !   
-     
181
SMTP,  %   & $%(  !  R]q. Y
   , email,     
& # $   $    
     % .   
4.5    #     
smtplib
 $  &   ,   &&    &,  $     #
  email  $  & 
          % .
% G.6.    -&     SUTP
#!/usr/bin/env python
import smtplib
mail_server = 'localhost'
mail_server_port = 25
from_addr = 'senderYexample.com'
to_addr = 'receiverYexample.com'
from_header = 'From: %s\r\n' % from_addr
to_header = 'To: %s\r\n\r\n' % to_addr
subject_header = 'Subject: nothing interesting'
body = 'This is a not very interesting email.'
email_message = '%s\n%s\n%s\n\n%s' % (from_header, to_header,
subject_header, body)
s = smtplib.SMTP(mail_server, mail_server_port)
s.sendmail(from_addr, to_addr, email_message)
s.~uit()
 #    & (                
 % ,   '    to + % #-  from +  #-. 
  $  &        &   ?  & $ 
        &.  $ %   & &  % 
   SMTP   $  &     &    
to_addr
   
from_addr
.    ' $  #, %   
   
\r\n
  &
From:

To:
           
& R]q.
  10  $        Python   &
       &$ Python,  $  & 
$     cron  &       
    % . K  #             
 '  &       % ,   '  $ 
 #  &$ Python.
* !  $    SMTP
;"       % $%   ,   #   % 
 '   , %   $  #    %   &$ Python,
 ,  ' ,  &  #"      SMTP  &
  (  #      ! ,       
    (  &( ' &    $.  &   &
  !     &    4.6.
 4. )"     
% G.;.  A     SUTP
#!/usr/bin/env python
import smtplib
mail_server = 'smtp.example.com'
mail_server_port = q65
from_addr = 'fooYexample.com'
to_addr = 'barYexmaple.com'
from_header = 'From: %s\r\n' % from_addr
to_header = 'To: %s\r\n\r\n' % to_addr
subject_header = 'Subject: Testing SMTP Authentication'
body = 'This mail tests SMTP Authentication'
email_message = '%s\n%s\n%s\n\n%s' % (from_header, to_header,
subject_header, body)
s = smtplib.SMTP(mail_server, mail_server_port)
-     
183
DEIERB
HEP
send: 'STARTTS\r\n'
reply: 'q5q q.z.z TS not available after start\r\n'
reply: retcode (q5q); Msg: q.z.z TS not available after start
       ,      #    #   
 SSL,   '    $ '  #. H '  $    
         #   ,  $ &  ,
  %   &   "      
 % ,  $&     
%  $      ,  #
    #  %  %  $  #   .
=  $   % "  $ Python
    ,   &(  % # $  ,  &
& % #   .   &$
Python  '  $  # 
      #$       MIME, % $%  $
 '  # & #  ' & 
( &   &.    
  $         $ '  #  $ & 
%   !  P[].         
 ,             ( '  MIME  
$ '           %    ' &,   
$    4.7.
% G.7.    " % PDY,   -
!  & +
import email
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import encoders
import smtplib
import mimetypes
from_addr = 'noah.giftYgmail.com'
to_addr = 'jjinuxYgmail.com'
subject_header = 'Subject: Sending PDF Attachemt'
attachment = 'disk_usage.pdf'
body = '''
This message sends a PDF attachment created with Report
ab.
m = MIMEMultipart()
m["To"] = to_addr
m["From"] = from_addr
m["Subject"] = subject_header
ctype, encoding = mimetypes.guess_type(attachment)
print ctype, encoding
maintype, subtype = ctype.split('/', 1)
 4. )"     
print maintype, subtype
 "& 
185
H        $  #
&     Trac  ' , % 
 & #,  #     % "     &. H '
 #,     &  %         , %  #
   ,         , %   $  #&     
' .
 ; 
          $   %    
  ! . H  '       ?  &  
( (          ( !  ,
  : VTML, P[]  PNG.  $ %        
  % !  $       .   '  
   % ,         '  #  
  &   % # "   .  $ ' ,      
   '    &   , %  & $ #& 
   . ; &&   & &
  &  % $%
'          &. H  &, %
   $         #   #     
 $           # .

  & %  $  & ?    '   #
    #   % # $    $  &  '  .
     %  # 
   $  &  ' 
# ,  $  &  '    .   ,  %
 $ &   ,     &      #,  
 "   ' ,  & & $      
$( # (       ' #  .
      &  
  $ &    &$
Python,   & &         #  
    
)    
187
H #
socket
 ' !% ! 
 5. ) 
    '    %       '  '   
            . $&    5.1.
% 6..     TCP
#!/usr/bin/env python
import socket
import re
import sys
def check_server(address, port):
# 3  TCP
)    
189
    $ " &    $      %
$%  ,     '  $   $%  ! 
check_
server()
.    &  , %     #      
    $   . %   ,    ,  $
      % $% 
 %  (    
$%  , %
+ %     ' # % -,
%   %. ;'   &
     &,  
%     "          ,    '
 %#  :
jmjonesYdinkgutsy:code$ python port_checker_tcp.py a 192.168.1.15 p 80
options: {'port': 80, 'address': '192.168.1.15'}, args: []
Attempting to connect to 192.168.1.15 on port 80
Connected to 192.168.1.15 on port 80
check_server returned True
  &&      ,  '& 
check_server
returned
True
, $% , %       %     .
;'   &    
 &,  %     $# 
  %       &:
jmjonesYdinkgutsy:code$ python port_checker_tcp.py a 192.168.1.15 p 81
options: {'port': 81, 'address': '192.168.1.15'}, args: []
Attempting to connect to 192.168.1.15 on port 81
Connection to 192.168.1.15 on port 81 failed: (111, 'Connection refused')
check_server returned False
  &&      ,  '& 
check_server
returned
False
, $% , %      &   #.      
   ,  '  
Connection
192.168.1.15
port
failed
,  '  # %:
'Connection
refused'
+   
  -.     '    #  $ $    ' 
&  ,  $ ' , %          (  
  ,  (        81.
H  $    , %  
    #,   ' 
 #$  #        &(  &$      % .
      &   
 , & $   
     
SUCCESS
+ " -  %  (.  #  
 #$    
,   #       ifthen:
$ python port_checker_tcp.py a 192.168.1.15 p 80 echo "SUCCESS"
options: {'port': 80, 'address': '192.168.1.15'}, args: []
Attempting to connect to 192.168.1.15 on port 80
Connected to 192.168.1.15 on port 80
check_server returned True
SUCCESS
   %     %       ,   
   ,    &     $#  ,  &  
 %   %   
SUCCES
 5. ) 
$ python port_checker_tcp.py a 192.168.1.15 p 81 echo "FAIURE"
options: {'port': 81, 'address': '192.168.1.15'}, args: []
Attempting to connect to 192.168.1.15 on port 81
Connection to 192.168.1.15 on port 81 failed: (111, 'Connection refused')
check_server returned False
;  $   $ "&   % ,  ,   &   , 
      
FAIURE
+  %-.
$ python port_checker_tcp.py a 192.168.1.15 p 81 echo "FAIURE"
options: {'port': 81, 'address': '192.168.1.15'}, args: []
Attempting to connect to 192.168.1.15 on port 81
Connection to 192.168.1.15 on port 81 failed: (111, 'Connection refused')
check_server returned False
FAIURE
   %   '      %,    $  $
    
   
. |   $% , %  % ,
    $ $   %,       
FAIURE
, %     .
 ! , %     $ &   #  %       
   80,   $%    #    . J  %  
 #   &       '
 ,   & ,   
           # $    VTTP  '     
 && & $   URL.      5.2  $  
   .
% 6.=.   -�    %/  
#!/usr/bin/env python
import socket
import re
import sys
def check_webserver(address, port, resource):
# 3    HTTP
if not resource.startswith('/'):
resource = '/' resource
re~uest_string = "ET %s HTTP/1.1\r\nHost: %s\r\n\r\n" % (resource,
address)
print 'HTTP re~uest:'
print '%s' % re~uest_string
# 3  TCP
)    
191
print 'Received 100 bytes of HTTP response'
print '%s' % rsp
 5. ) 
         
 & $  VTTP.  
   %       $     .     
 $  " , ! &  $ $% 
,  $& 
, %         
    %.     
 ,  %    ,  $  $     &&. {
  &&  $%  200, % $% O\ +   & -,
 301, % $% Moved Permanently +$ " &  
     -, ! &
check_webserver()
 $ $% 
True
,     %   $ $% 
False
.  $ 
main
   & $          ,  % 
(  #$  &,  $ ! 
check_webserver()
.  
  & ! 
check_webserver()
   $  
    % $%  ,     ' $% ,  %  
! .      '
%, %       
  . ; (  #   #  $ '  # $ #    $
        %    & # %  (    
%. ;'   &  
 #$ &    &:
$ python web_server_checker_tcp.py a 192.168.1.15 p 80 r apache2 default
options: {'resource': 'apache2 default', 'port': 80, 'address':
'192.168.1.15'}, args: []
HTTP re~uest:
ET /apache2 default HTTP/1.1
Host: 192.168.1.15
Attempting to connect to 192.168.1.15 on port 80
Connected to 192.168.1.15 on port 80
Received 100 bytes of HTTP response
HTTP/1.1 z01 Moved Permanently
Date: ed, 16 Apr 2008 2z:z1:2q MT
Server: Apache/2.0.55 (Ubuntu)
Closing the connection
First line of HTTP response: HTTP/1.1 z01 Moved Permanently
ersion: HTTP/1.1, Status: z01, Message: Moved Permanently
Success status was z01
check_webserver returned True
   %        $ , %   && VTTP
&   
/apache2
default
       $%  301, % $
%  (.
;'   &         . ;  $   $
 ,        
, %       #, %
 $  ,   ! &
check_webserver()
  $% 
False
$ python web_server_checker_tcp.py a 192.168.1.15 p 80 r foo
options: {'resource': 'foo', 'port': 80, 'address': '192.168.1.15'}, args: []
HTTP re~uest:
ET /foo HTTP/1.1
Host: 192.168.1.15
)    
193
Attempting to connect to 192.168.1.15 on port 80
Connected to 192.168.1.15 on port 80
Received 100 bytes of HTTP response
HTTP/1.1 q0q Not Found
Date: ed, 16 Apr 2008 2z:58:55 MT
Server: Apache/2.0.55 (Ubuntu) DA/2 PH
Closing the connection
First line of HTTP response: HTTP/1.1 q0q Not Found
ersion: HTTP/1.1, Status: q0q, Message: Not Found
Status was q0q
check_webserver returned False
   %             #  
  "     ,    
% %       
   $ , %     $ "#   % . ;    
           
/foo
,    ! &      
 $% 
False
   $    $ ,   $  # $     
,               &
  "    . ~ #  (      &  , %   
$ # ,         $      .
{    &  $ '  #  #      
   ,  #$        , %   
#
socket
,     #$  # .
;    #   
&   $   (  (    ,  #$( 
 $     ,   #
 5. ) 
% 6.F.   �-    %/ httplib
#!/usr/bin/env python
import httplib
import sys
def check_webserver(address, port, resource):
# 3   
if not resource.startswith('/'):
resource = '/' resource
try:
conn = httplib.HTTPConnection(address, port)
print 'HTTP connection created successfully'
#G 3 
)    
195
  &  
httplib
 
re~uest()
, 
   &    $  VTTP.    ,  ? 
   &  & 
getresponse()
,   $  ?
 %   . ?     &  $ '  #  
% #   &&   VTTP,  "#   
status
& ?            #"&   
 ,     ,    # $ #&  (    %
 $  #, & #   % # $    VTTP. Y  & 
       .
;'   &  $#  $   &   '   
     ,            (.
H $"        
      (   :
$ python web_server_checker_httplib.py a 192.168.1.15 r /
options: {'resource': '/', 'port': 80, 'address': '192.168.1.15'}, args: []
HTTP connection created successfully
re~uest for / successful
response status: 200
HTTP connection closed successfully
check_webserver returned True
K '  $#  $   &          
,             % . H $"
        
/foo
       (   :
$ python web_server_checker_httplib.py a 192.168.1.15 r /foo
options: {'resource': '/foo', 'port': 80, 'address': '192.168.1.15'}, args: []
HTTP connection created successfully
re~uest for /foo successful
response status: q0q
HTTP connection closed successfully
check_webserver returned False
 '    # " , &  $,    &  $ '  # 
 #$  #        ,    #$  #
. ) #$ 
httplib
   &
 5. ) 
H ' '   #$  #&   $  '    ! ,  
$% ( &  $ !%    ! ,  (  &$
Python,   $  # &       ]TP   ' 
!%    !  .
   %   #   $   ,    
  5.4  $   &,     .
% 6.G. 1 #  &  %/ ftplib
#!/usr/bin/env python
from ftplib import FTP
import ftplib
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option(" a", " remote_host_address", dest="remote_host_address",
help="REMOTE FTP HOST.",
)    
197
ftp.login()
except ftplib.error_perm, e:
print "Anonymous login failed: %s" % e
sys.exit(1)
try:
local_file = open(options.local_file, 'wb')
ftp.retrbinary('RETR %s' % options.remote_file, local_file.write)
finally:
local_file.close()
ftp.close()
    %   & +$  $   &,  &
 $          -  $  & ?
FTP
$ 
    
FTP()
,      &      . H '
   $  # ? ]TP, $
    $   ,  $
 $ # 
connect()
,           ]TP.    
  & (    ,  #$& &  #$  &  
 #,      $,     %  & &
  ( . Y   $  ? 
file
,      (
& #&  ,  %  $ !     ]TP.     
$ & 
retrbinary()
? 
FTP
retrbinary()
,   
$   ,  %  % !     ]TP. H 
   :  , $  !,  !   
  $ .    , %  %   !    
$   #$ & 
write()
? 
file
,    $  
    " . '   #, %
   %    
$  
write()
. H     
write()
 
 5. ) 
  ]TP  '  '   !  #      URL.  
  ,  $ ' , ' 
  , %  
urllib
 
$ &  #&   ]TP, ( &  &  $ '  #   
 .   5.5    ' !  #  #, %    
  ,  $  
   #$ &
ftplib
,   #$
 #
urllib
% 6.6. 1 #  &  %/ urllib
#!/usr/bin/env python
)  "  /   
199
urllib.urlretrieve(url, filename)
   % &             #
sys.argv
      &   $     URL   (&  
%     #  !   $   . |  
    #      VTTP,       ]TP,  
  #, '   &  #$ 
&   #  %   URL.
~   #     $ % &
   :      
', %  &$ Python    & '  & #&
  , %   ( &$ (  
 &,      
 ' &. ; &   & 
& #    & 
 , &  $   , %   (  ,    
  (         
   &$  Python.  
  %  
urllib
 $   , %  (  ,
 $ #   % $& #          
 , %  $ #   .  % ,    ,  $ ' , 
&    #          #    Py
thon,         Python +Python Package Index, PyPI-
   :
http:44pypi.python.org4pypi
            && &  
urllib2
. |     $ 
%   '  !  
#  $ '  , %   
urllib
. ; ,
urllib2

  %"    '    !   %"    
'  cookie.   ,    %  #$  #  
urllib
 ' , %  %    (  ,   #  

urllib2
 $ ' ,  %" 
     # "  
   &.
        
  , %   $ &    &     #   
 &  (   # $ $    '    .
      % % #&    $  
&,  ,    #   VTTP   .  ,
    $   (   #  & #    $
(   (  '  $( # (,     
  '   . {     #  $ '  #  & #
     ,  
       , $ 
  $    &$ Python, ,     , (  ,
%   $  $% &  (   ( $    ? 
 &$  Python,   #       , %   !
    ,   (  $  # %. @
 ,      #    ,  $ &( $  #
$    (    +Remote Procedure qall, RPq-.
200
 5. ) 
XMLRPH
@ (  & XMLRPq,  $ && $  # $    (
  ,       # !    
 XML  '  &   .   #     
% # XML  $ ,   
 , '   &   #
!    ,      #&   . { 
   , %    #  (  $ #, %   #$ 
 # (   XMLRPq  , %       
&$  Python   &  $     ,      
%    (  .   ' ,    $  $ #, %  
$ XMLRPq   &   #"  &$    
&  %   (  & % #      #$ .
   5.6   &  $&       XMLRPq.
% 6.;. &   XU�[\PC
#!/usr/bin/env python
import SimpleMRPCServer
import os
def ls(directory):
try:
return os.listdir(directory)
except OSError:
return []
def ls_boom(directory):
)  "  /   
201
 %    $ (    XMLRPq.      
 (      %  
serve_forever()
,     ' 
   & $         (. ;'   
&   $  &           % IPython:
In [1]: import xmlrpclib
In [2]: x = xmlrpclib.ServerProxy('http://localhost:8^65')
In [z]: x.ls('.')
Out[z]:
['.svn',
'web_server_checker_httplib.py',
....
'subprocess_arp.py',
'web_server_checker_tcp.py']
In [q]: x.ls_boom('.')
Out[q]:
['.svn',
'web_server_checker_httplib.py',
....
'subprocess_arp.py',
'web_server_checker_tcp.py']
In [5]: x.ls('/foo')
Out[5]: []
In [6]: x.ls_boom('/foo')

class 'xmlrpclib.Fault'� Traceback (most recent call last)
+3 +     -Q��
^86 if self._type == "fault":
� ^8^ raise Fault(**self._stack[0])
^88 return tuple(self._stack)
^89
class 'xmlrpclib.Fault'�: Fault 1: "type 'exceptions.OSError'�
:[Errno 2] No such file or directory: '/foo'�"
(:[Errno 2]     : '/foo')
 '     $  ?
ServerProxy
,  $       
XMLRPq.    $ ! 
, %   % #  
'    %    .     $  $   
,  '    
     ,    
  % !   .     , %     
  ! &
x.ls('.')
 $  &$  Python. ; $
202
 5. ) 
&$   $    `ava, Perl, Ruby  q  ' 
%  #   %    
 $#  . ; &$  $
    '  #  
%    % # !      ,  $  
 ,    &   ! =      
   XMLRPq  '  $  #    
!  XML     #      . H  '    
$ # ! 
ls_boom()
. J & , %  ! 
ls_boom()
    &    % ,  %
ls()
, 
   #,   %     &      . J 
 ,           '   %   ! 
.
 $ '   !  #       ,   
(  & XMLRPq,  $    . ;  $    
   ! , %     $ '  #  #    
 , $  #    $ #  % "  $ 
$ #      %  (   .
  (   XMLRPq   &   % &. |  
% &     & # 
    ,   ( 
 &  '       # '   %&& $ % . ;
 ,        
     &     
 ?  &$ Python,   XMLRPq  $ 
?   #,       !  XML  &    
   . J $  ,   '   #    ,  &  
    &  #   ,   $  #
 $ XML   &, %     #     
# ? . @  %   
 #$  # ?     
       RPq, %  $ ' #  (  '     
$ &F |  #$&   #    # XMLRPq,    
  $ '  .
Pyro
Pyro   ! , & "   (    ,  
  ( XMLRPq. ;$ Pyro  (  Python Remote Ob
jects +   ?  Python-.   $ &  $  # ' 
  &,   $ &
XMLRPq,     , % 
 $  # ?   !   &,    %  $ '
  #   % !  
    ? . { 
  # $(    #$  #&  !   Pyro,  
&    # # .     & &    Python.
   ,  '   #, % Pyro   #   
&  &$ Python,    (  & XMLRPq    &
  % # $    '   &  &$ Python   
, 
 ( &$ (.    5.7   &
 $&  '   ! 
ls()
, %    
,  #$
  (   XMLRPq.
)  "  /   
203
% 6.7. &   Pyro
#!/usr/bin/env python
import Pyro.core
import os
from xmlrpc_pyro_diff import PSACB
class PSAExample(Pyro.core.ObjBase):
def ls(self, directory):
try:
204
 5. ) 
Out[q]:
['pyro_server.py',
....
'subprocess_arp.py',
'web_server_checker_tcp.py']
In [5]: psa.ls("/foo")
Out[5]: []
In [6]: psa.ls_boom("/foo")

type 'exceptions.OSError'� Traceback (most recent call last)
/home/jmjones/local/Projects/psabook/oreilly/ipython consol�e in modu�le()
+3 +     -Q��
� 115 raise self.excObj
116 def __str__(self):
11^ s=self.excObj.__class__.__name__
type 'exceptions.OSError'�: [Errno 2] No such file or directory: '/foo'
(type 'exceptions.OSError�': [Errno 2]     : '/foo')
% . H  % '  $#  , %     XMLRPq.
)      ' . ; %  $  ,      #  
  #      ? F 
     #   ,
 $  # $   ?     #  ! 
cb()
  $ 
  XMLRPq   
cb()
  $    Pyro.   
 5.8   & !   
  ,   
 & #&.
% 6.8. R# %" XU[�\PC  Pyro
import Pyro.core
import xmlrpclib
class PSACB:
def __init__(self):
self.some_attribute = 1
def cb(self):
return "PSA callback"
if __name__ == '__main__':
cb = PSACB()
print "PRO SECTION"
print "*" * 20
psapyro = Pyro.core.getProxyForURI("PROOC://localhost:^^66/psaexample")
print " �� ", psapyro.cb(cb)
)  "  /   
205
print "*" * 20
print "M RPC SECTION"
print "*" * 20
psaxmlrpc = xmlrpclib.ServerProxy('http://localhost:8^65')
print " �� ", psaxmlrpc.cb(cb)
print "*" * 20
  ! 
cb()
  (  $&(, XMLRPq  Pyro,
'    $   
cb()
    ? . )   (
%&(   '    #   
PSA
callback
. ;'  $
 , %  $ " ,    $    :
jmjonesYdinkgutsy:code$ python xmlrpc_pyro_diff.py
/usr/lib/python2.5/site packages/Pyro/core.py:11: Deprecationarning:
The sre module is deprecated, please import re.
import sys, time, sre, os, weakref
PRO SECTION
********************
Pyro Client Initialied. Using Pyro z.5
� � PSA callback
********************
M RPC SECTION
********************
� �
Traceback (most recent call last):
File "xmlrpc_pyro_diff.py", line 2z, in modul�e
print " �� ", psaxmlrpc.cb(cb)
File "/usr/lib/python2.5/xmlrpclib.py", line 11q^, in __call__
206
 5. ) 
OB`ECT:: {'some_attribute': 1}
OB`ECT.__class__:: type 'dict'�
localhost [1^/Apr/2008 16:z9:02] "POST /RPC2 HTTP/1.0" 200
   $ &   # ? ,    $    
,  $    $ XMLRPq,  
some_attribute
 
&  %  &. K   (&    % ?  
  ,  
cb()
  % .
;'   &     Pyro:
OB`ECT: xmlrpc_pyro_diff.PSACB instance at 0x9595a8�
OB`ECT.__class__: xmlrpc_pyro_diff.PSACB
   , %  ? 
PSACB
, . . ,   
 $ . ;          Pyro  '  % #  
 ,    '   , 
 #$ &   . | $%
, %    Pyro '  
    #   
 . Y&  $ ? 
 !  Pyro  #$      #
pickle
, % ?&&
,  %  Pyro   ( '    .
  &  ,  '  $ #:    (     " 
RPq,     "( $
 ,     "  
 & % & XMLRPq,   '  '  !  #
          &$    &, ,  
  , (  "     XMLRPq.      ,  
% & XMLRPq "   & ,    $'  
      #( 
   
% #&
# &$  Python, %"   &   Pyro.
SSV     &     "  #$   . {
 '  '   #      ,   %  
   &   $&   '  &. SSV   
%  $            ,    
   % ,   % !     $%       ( 
 &( %  $    .
{    &         
ssh
,  %     
  #$  #&    SSV   F &    # $ #  
   , %   %   #   SSV  
 "   $ '  & &$  Python.
  SSV2  $   &$ Python       
 
paramiko
. )$   ,   ' #  
 &$ Python,   ' $  #  %    
SSV   $  #    $
% SSV.    5.9   
 &,   '   #         SSV    #
    .
207
% 6.9. ?"    % SSK  + %"+
 "& %
#!/usr/bin/env python
import paramiko
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
password = 'xxxxxx'
if __name__ == "__main__":
paramiko.util.log_to_file('paramiko.log')
s = paramiko.SSHClient()
s.load_system_host_keys()
s.connect(hostname, port, username, password)
stdin, stdout, stderr = s.exec_command('ifconfig')
print stdout.read()
s.close()
   $  ,       #
paramiko
  & 
     .    $   ?
SSHClient
.      $ 
 & $$  %  (  ,         Linux
$  & $ ! known_hosts.    & &   
     SSV. ;    $  (    %   '  ,
   ,   ' $   SSV.
@  #      #          . H
exec_command()
 &  $     $  ! 
(   ,   
(   &    :  
   ,               
" (.   $ #, %    & &  "  IP 
  ,    #$  &  $ &   & SSV,  
   $#     &  
ifconfig
        :
jmjonesYdinkbuntu:/code$ python paramiko_exec.py
208
 5. ) 
&   ,        
ifconfig
  #
  " , # IP   % &.
   5.10  $ ,   '    #  &
paramiko

 & #   % !   
 S]TP  '        
#  ".    %   #  % !
    ",  #$& &   
get()
. {    $
      #    # !
    ",   '
  #$  #&  
put()
% 6.5.  &     SSK
#!/usr/bin/env python
import paramiko
import os
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
password = 'xxxxxx'
dir_path = '/home/jmjones/logs'
if __name__ == "__main__":
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
files = sftp.listdir(dir_path)
for f in files:
print 'Retrieving', f
sftp.get(os.path.join(dir_path, f), f)
t.close()
 % ,   $(   #$  # �   $   %
    ,    5.11
  &  ! &  
&  &,  &           ,   #
$   % RSA.
% 6.. ?"    % SSK  " + %"+
 /#% # + 
#!/usr/bin/env python
import paramiko
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
pkey_file = '/home/jmjones/.ssh/id_rsa'
if __name__ == "__main__":
key = paramiko.RSAey.from_private_key_file(pkey_file)
s = paramiko.SSHClient()
s.load_system_host_keys()
s.connect(hostname, port, pkey=key)
Twisted
209
stdin, stdout, stderr = s.exec_command('ifconfig')
print stdout.read()
s.close()
)    5.12   &  ! &  &  &,
 &    % !    #$  % RSA.
% 6.=.  &     SSK
#!/usr/bin/env python
import paramiko
import os
hostname = '192.168.1.15'
port = 22
username = 'jmjones'
dir_path = '/home/jmjones/logs'
pkey_file = '/home/jmjones/.ssh/id_rsa'
if __name__ == "__main__":
key = paramiko.RSAey.from_private_key_file(pkey_file)
t = paramiko.Transport((hostname, port))
t.connect(username=username, pkey=key)
sftp = paramiko.SFTPClient.from_transport(t)
files = sftp.listdir(dir_path)
for f in files:
print 'Retrieving', f
sftp.get(os.path.join(dir_path, f), f)
t.close()
Twisted
Twisted   !  $   (  '   &$
Python, & (   &. |   !   $ &  " #
 %    $ %,    "     . 
      "  ,    !  % & 
   '  #. Twisted %    #&  &   #  
         ,     %     !    
' $ #&      . 
  , $%  Twisted  
 &     #  #"   , %      
  "         %  ' $ #&  "
@     ,   & #
      $  #&   
 !      #,  #      "  $
 . {     ' 
   #&    " 
 , $%   !  Twisted         
'   . %    %   $%   ' 
' #  Twisted Network Programming Essentials | * 
 5. ) 
Twisted   &  ! , & &   &,  # 
 &      #& 
     ,
 $  $    &  $  (,  
$   ( &(   (,      , 
    ( &   &.
        %   #$   ! 
TwistedF |   !   
,     ' '  
$ #   $ %   #  % . $&     
 &          ,  ( &(  
    &   &. |   !       
  %   %    $ '  #      #$ 
& "     . {      ,   
        !  Tw
isted, $ % &  , % 
  &    #& $
  (  % &(  $
 #&   " ,  $ (  (. "  & $ 
% $ % &  , %   " #, %  (   & # 
 &    (   .
   5.13   &  ,   &        
$    !  Twisted. | % #     ,  
&     &
   &   Twisted,
%     #  $%   &     . ;
      &   # (  (  , 
  (  $ #.  %  (   ( &   , !
 ,     '     .      
            ' &,   
  !  Twisted.    $
 &      ,  
 $  &     %    . *  
 % $  $   (  $ &    . '   $ 
Twisted
D  #"  $ (, "   ,   
& % &  &     &   
 &:   ( '  % ,      ( , 
&   ,  &&  .. @   
   #  ' #.   ,  #$
      !  Twisted,   "   .   
(         '  #   
& ' &, %   %# ,     ,    
   $ % &.  !       
  :   ( %    +  -  .  
 #    #   ,  #$ Twisted, 
& $ #& %(  '   % # $   #
         &.
Twisted
211
& !   '   '  #  $ & #     
.    &   &      
 &.   &   &  ' & & '    &
 $  &    $ &  . K  ($  '    
 &   %  $ '  # ?  &      % .
% 6.F.    , 
#   % Twisted
#!/usr/bin/env python
 5. ) 
    !  Twisted.  &&   ,   
   &       %.       
  %     ,  !  Twisted $  
connec
tionMade()
   .    $  &,    
          . +      
 % #   .-
 #   
connectionMade()

clientConnectionFailed()
 
  &    &    !  Twisted. D
          . @ %  '     && 
&    %       #    .     $  
   &,  !  Twisted $      ,
 & (  ,    $ &  % 
  .
    $     &   $    $ & 
PortCheckerClientFactory
.          ! 
Twisted    # $   !    #  %  $
      $    
+  $% &    &  
          -.        
  $  % #& $       $    ,
 $      . {      #,     % 
  $  .
 %  $ & (   %    &    &  '  $ #,
%  $         ,      $ .  
  %   $    #            
 #$  # 
PortCheckerClientFactory
&      . {
     &   $    $   (    
  %,        $  
clientConnectionFai
led()

PortCheckerClientFactory
. {      "
    , !   $   $ &  
PortCheckerProto
 $  
connectionMade()
   $ &.  " & 
    % &  (  
  % ,     
 %   &          $ "    .
|  % #     ,       # &  
  &    !  Twisted. %   &
  & Twisted,        
    , && &  &
 '     &  ! 
   $ . H ($  '     &     &
&$ #    # $ "    . K !    
 $    %   ,   $ '  #   #  
    . * ,  &  '   &,  
 ? & #&    %      #  $#    . | 
    #  !  Twisted   # % #  ' &  
&. +H ($  ' (      &   
 5.14.-
Twisted
213
   5.14      ,  #$     
 +Perspective Broker-  #  ($ $    (
   +RPq-  Twisted. |     &     
 $    ls,      '    $ 
   #$   XMLRPq  Py
ro.    %  #  
 $   .
% 6.G. ?  -      +   % Twisted
import os
from twisted.spread import pb
 5. ) 
print print_result
reactor.stop()
if __name__ == '__main__':
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 98^6, factory)
Twisted
215
   &     !    $     ,  
    '   % #.
|   &    #  ' , %   '  '  #
&        RPq.      &   
  .  $      &    #   ' 
$$ ?  & !     $     ,  $ &
?   '    &,      ! . ;   % #
    .     
 !  Twisted  && &  
  & ,   $ %,    &  " #,    
    #  '  .
   5.16       
 ! &  & #
%              .  
    ! 
 $    ! 
ls_boom
. |
     ,   $
 & '  % 
          .
% 6.;. 3 -      +  %+ Twisted
- -  '-
#!/usr/bin/python
from twisted.spread import pb
 5. ) 
Peer will receive following PB traceback:
Traceback (most recent call last):
+3 +W -     -Q�
Scapy
217
   #$  & root,  
   &  % #  
       ! .
     $$     Scapy,     
 :
elcome to Scapy (1.2.0.2)
       '  #  , % %     
    %     Python,    #  " 
 &'      #   Scapy.   , % 
  ,  $   ! 
ls()
 Scapy, &    
��� ls()
ARP : ARP
ASN1_Packet : None
BOOTP : BOOTP
Cookedinux : cooked linux
DHCP : DHCP options
DNS : DNS
DNSR : DNS uestion Record
DNSRR : DNS Resource Record
Dot11 : 802.11
Dot11ATIM : 802.11 ATIM
Dot11AssoRe~ : 802.11 Association Re~uest
Dot11AssoResp : 802.11 Association Response
Dot11Auth : 802.11 Authentication
[+ ]
H  $  ,   %  "  ? . ;'  
    $  [NS  
www.oreilly.com
,  #$ 
       [NS !     (%   
   +qaltech University-:
��� sr1(IP(dst="1z1.215.9.q9")/UDP()/DNS(rd=1,~d=DNSR(~name="
www.oreilly.com")))
Begin emission:
Finished to send 1 packets.
...*
 5. ) 
       " :
��� ans,unans=sr(IP(dst="oreilly.com",
��� ttl=(q,25),id=RandShort())/TCP(flags=0x2))
Begin emission:
)"      $" Scapy
219
 5. ) 
if __name__ == '__main__':
if len(sys.argv�) 1:
for ip in sys.argv[1:]:
print "arping", ip
arping(ip)
else:
arping()
K  #   ,     # Scapy  '  $  # '
 ,   !   $    :
#!/usr/bin/env python
  
D  , !       $ %, 
 )@ $&  (
      .
D            $   (    
  #  !       ,   #  $ & #
   ,      " #  #  , 
       !       ,     
'      . |   &   &  # & #   
      , 
    , (  "    
   .        %    
(, !(    (.
    & '    & #  $     
  . {'        (  (  (  
      &  #" % # (  ,  (  #".
     $   #   ( !#    &&
     ( $        && &  ( 
  ,   % &  $   ! ( !#    &
        . $%   &  ?&
& &  &  �       , ( & $
%    $ " & $ ' &,       ' 
        . {   (     & #
 '    &   , %      &  
( !  , ? 
    &  
 '  '
    $% #    # ' & ! $ '   
  $ "  . ; (   #     & !    
 , %      
    #$ &  
   .       ,   ,    ,  '
      ,    &   ,   
 6. 
  &    `BO[ +just a bunch of disks     
-, ?     RA
I[ 0 &   % &  #"   
$  #  .     
  ,    '  
(  &  #   
,      % $
    (.
   ( '    &     #      #  
 $        .  &    #$ &  
  ,  rsync, scp  mv. |     ,      
    #$  #&   &(  &$ Python &   
& (    & (  .
   #        &$  Python  '  #  
&    $   #
( $  .      
       &  , % "       &
(     #  $ ,  $ %&  !  $
   ,  ,   
tar
   ,  $   $ 
  .    
      '   $    &, &  $ & 
(   &  (   ?       &$ Py
thon. H (     # ,
%  $    #( 
 &       
,  &   $  
  ,  # '  # ,    (  .  &$ #
'       # ,   !  #    ,
   #$    
   $    &.
   , %   (    #   ( ,
           &.
  % , Python    ( 
 &  " &   ( $ %. )    ,  #
   ,       !    &  
  &  , % #   $  #   ,   
  ' ,   $  #  . |  $         
&   (,  %  % (  &    #&
     .
+    $ OS
$  "  $ 
{    # (  
#  $  #   !  
       % ,         &
#  , %  # OS   &         
!      '.  Python 2.5  # OS  
'   200  ,   $ (  $%  &  
 .    $       $      
&,   & &      ,  %
(  &  #   .
#$" ! OS !"  ! 
223
&  $,   (  &   #    #,   % 
IPython $ &  $      &   ,   
 %  "  "  
   OS    #   % 
IPython,       & #  &,   %   
% &    .    6.1  $ ,    &.
% ;.. L" %" %" VS, - 
/#%+0   -  "+%
In [1]: import os
 6. 
#  K  : K    
   
    $           (,   
   '  #       ,   '  #$ 
 #  # OS,     #   '  $        
    #  
shutil
,   $%  &  
   "      (. H #
shutil
 
'    &,  
  &,     &    
& (,    # OS,     &    & #& 
   #& (.
)   &
shutil
   % IPython    
#    $    .    '     #$ 
 # 
shutil.copytree()
,        &  '   
(    &,   & (   # 
% &.   #,  %  $ % & $  '  $%
   &,  #         
 &$  Python. $&    6.2.
% ;.=. L/# %" shutil "   "  "+0
In [1]: import os
In [2]: os.chdir("/tmp")
In [z]: os.makedirs("test/test_subdir1/test_subdir2")
In [q]: ls lR
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test/
./test:
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test_subdir1/
./test/test_subdir1:
total 0
drwxr xr x 2 ngift wheel 68 Mar z1 22:2^ test_subdir2/
./test/test_subdir1/test_subdir2:
In [5]: import shutil
In [6]: shutil.copytree("test", "test copy")
In [19]: ls lR
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test/
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test copy/
./test:
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test_subdir1/
  0  %  0      /
225
./test/test_subdir1:
total 0
drwxr xr x 2 ngift wheel 68 Mar z1 22:2^ test_subdir2/
./test/test_subdir1/test_subdir2:
./test copy:
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test_subdir1/
./test copy/test_subdir1:
total 0
drwxr xr x 2 ngift wheel 68 Mar z1 22:2^ test_subdir2/
./test copy/test_subdir1/test_subdir2:
%   , %  % #    ,    ,    &    $
 &,     ,     '  #$  #    
      '  ,   !     
&,  &       
(.   , % (    
 ,      '  #$  # &    
 & ( $   !           
  .   $   #   ( !#  % 
  (  '  #& $ " &        
, %     $  # (     #  #,  
&    &.
H     #  ,   %   $ & & 
   cron '  &,        & & x   .
      ' , %     (  &  ( 
 %   ,          #         
 ,             ,       
 # (      #,   %  , %   #  $
 '  #   $  #  '  !#    $ "  .
  #
shutil
 '  #   # !,     '
  &   &     &    &  #  (.  
  6.3    &  $ '
 #     &
"   ,
   6.4  $ '  #    &.
% ;.F.  % "  "+0  %/ %" shutil
In [20]: shutil.move("test copy", "test copy moved")
In [21]: ls lR
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test/
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test copy moved/
./test:
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test_subdir1/
./test/test_subdir1:
 6. 
total 0
drwxr xr x 2 ngift wheel 68 Mar z1 22:2^ test_subdir2/
./test/test_subdir1/test_subdir2:
./test copy moved:
total 0
drwxr xr x z ngift wheel 102 Mar z1 22:2^ test_subdir1/
./test copy moved/test_subdir1:
total 0
drwxr xr x 2 ngift wheel 68 Mar z1 22:2^ test_subdir2/
./test copy moved/test_subdir1/test_subdir2:
% ;.G. ]" "  "+0  %/ %" shutil
In [22]: shutil.rmtree("test copy moved")
In [2z]: shutil.rmtree("test copy")
In [2q]: ll
       ( && &    % &   
, %     ,   #   
  &   %     
 #. H  $  (   (     '   ?  #
   &     '  .  $ $   
    , &     #   $    ,   
  $    &,          
    $   $  (, &    % 
    &.  % #,    &  ,  $  &$
Python      &,
   &  $   
,  &    $    .
=' $ K  !"
;  $ '    #   ,  &  
 ,     !. /        ' 
 #  #  ,   $  (   ,  
&       $    # $   
 $#  . H "   
     ,  $ &
   #.
   ,   (  &   & $ &    
 '          &$  Python. ^$ Python 
$&  #$ &         ( &      .
   6.5    &,   $  #   (    
,  ' ! ,  &  $ !,   
  .
% ;.6. ?A & -0" 
import os
path = "/tmp"
-*  ! 0 
    
227
def enumeratepaths(path=path):
"""G7     - -      """
path_collection = []
for dirpath, dirnames, filenames in os.walk(path):
for file in filenames:
fullpath = os.path.join(dirpath, file)
path_collection.append(fullpath)
 6. 
/tmp/launch hz6okI/Render
/tmp/launch ~y1S9C/isteners
/tmp/launch RT`Tw/:0
/tmp/launchd 150.wDvODl/sock
Recursive listing of all files in dir:
.aksusb
ARD_AB`MMRT
com.hp.launchport
error.txt
liten.py
itenDeplicationReport.csv
ngift.liten.log
58920
Render
isteners
sock
Recursive listing of all dirs in dir:
.11 unix
hsperfdata_ngift
launch hz6okI
launch ~y1S9C
launch RT`Tw
launchd 150.wDvODl
ssh cE2t6PfnO
;  #"  %     !      
: 
os.walk()
 $ ?    ,  &  
  '   # ( 
       & # :
In [2]: import os
In [z]: os.walk("/tmp")
Out[z]: [generator object at 0x508e18]
   &   $       % IPython.   ' 
$  #, % %        $ '  #  #$ 
 #  
path.next()
. H    & #&  '   
   ,   ' $ #, % 
os.walk()
 $ ?
   .     % #   $ &     
 &.  , %   (  $ #    (,   
 Y  J$ +[avid Beazely-    :
http:44www.dabeaz.com4
generators4
In [2]: import os
In [z]: os.walk("/tmp")
Out[z]: [generator object at 0x508e18]
In [q]: path = os.walk("/tmp")
In [5]: path.
-*  ! 0 
    
229
path.__class__ path.__init__ path.__repr__ path.gi_running
path.__delattr__ path.__iter__ path.__setattr__ path.next
path.__doc__ path.__new__ path.__str__ path.send
 6. 
def enumerateFiles(self):
"""G7 -   X       """
file_collection = []
for dirpath, dirnames, filenames in os.walk(self.path):
for file in filenames:
file_collection.append(file)
return file_collection
def enumerateDir(self):
"""G7 -   X        """
dir_collection = []
for dirpath, dirnames, filenames in os.walk(self.path):
for dir in dirnames:
dir_collection.append(dir)
return dir_collection
   ,       #"( $      #  $  # 
%  !  &  !     . &    #
      & $ % &  , %   '     #
   .
   
  ( % # '&  & &     
  .  %   $  #     :   !   (
(   ( $%F  #      ' ! 
     &    F   
$      , 
  $ &    #        .
   (  &  #     ?  '( (,
%   (   #  #&      ! , % 
$ #,   $  &    . |    &   
',    (  
$ &   ,    (
 .   #     ,  "    
   &  #"( ?   (        % 
  '  .
   $   %      #    (  
 & !      ,  $      %   
    #(  ! .
       &$ 
Python  &   #   ,       # 
  =   
filecmp

os.listdir
+    $ filecmp
H #
 ' !  &     !!   
 & !      . H #
$ ! 
& ( !    $ $% 
True
,   $#   $ 
os.stat()
  ' &  ( ! , 
False
,   %   
)   /
231
$#   % &. % ! &
os.stat()
$ &, % 
  #,   #$   !   '   $
        
 $ ,     
'  !       $  &.
    #  & #,     #
filecmp
,     &
 $  #  !. Y&          
,  $   !
  
file5.txt
 $"     0.    $   !    
file.txt
 $"     1. ;  ,  $   !    
file55.txt
 $"     0. |  !    #$  #&  
%   ?   &     !  :
In [1]: import filecmp
In [2]: filecmp.cmp("file0.txt", "file1.txt")
Out[2]: False
In [z]: filecmp.cmp("file0.txt", "file00.txt")
Out[z]: True
   , ! &
cmp()
  $% 
True
   !
 
file5.txt

file55.txt
False
   ! 
file.txt
file5.txt
* &
  '     ,    $
%&(  '  &  #&    . H     
 # '    ,         #    
  &  ,     #    $. Y&   
     
4tmp
  $      ,  '  $ 
(     ! $      .    
  $    # !    
file.txt
,  
 $    11:
In [1]: import filecmp
In [2]: pwd
Out[2]: '/private/tmp'
In [z]: filecmp.dircmp("dirA", "dirB").diff_files
Out[z]: []
In [q]: filecmp.dircmp("dirA", "dirB").same_files
Out[q]: ['file1.txt', 'file00.txt', 'file0.txt']
In [5]: filecmp.dircmp("dirA", "dirB").report()
diff dirA dirB
Only in dirB : ['file11.txt']
Identical files : ['file0.txt', 'file00.txt', 'file1.txt']
 $ ' ,    , %  
diff_files
  ' %  ,
( &   $  !
file.txt
  #  !     . Y 
  , %  
diff_files
&& $%& #  '  
   !.
 6. 
  $&   $#      
same_files
  
 , %       %( !(  (   (.
;  ,             % .  & 
  $%&(  '  & !. |  "# % #
  $   $ '    &
filecmp
,         
  #&           &$  Python,
%   % #        (&  $ '  &(,
& & (        %     
  .
+   os.listdir
{         
 & (       
 #$   
os.listdir()
. H
os.listdir()
 '  
 & #       
  $  
' ( ! . ^$ Python  '  '     (
        ,      '  #$  # 
os.listdir()
& & & $%  '    ,    
$&     '    $  % &   '   $ 
  . ;'  $ ,    &    % IPython:
In [1]: import os
In [2]: dirA = set(os.listdir("/tmp/dirA"))
In [z]: dirA
Out[z]: set(['file1.txt', 'file00.txt', 'file0.txt'])
In [q]: dirB = set(os.listdir("/tmp/dirB"))
In [5]: dirB
Out[5]: set(['file1.txt', 'file00.txt', 'file11.txt', 'file0.txt'])
In [6]: dirA dirB
Out[6]: set([])
In [^]: dirB dirA
Out[^]: set(['file11.txt'])
      '  #, %   $     
 '  ,  $      % &, %  & #
$%&.    , %    7   %  &
file11.txt
,   %
dirB
&& &   '    &
dirA
,     
6   %     $#  ,   %  '  
dirA
 
'    ,   ' &   '  
dirB
.   #$ 
  '      '  $  #   ?   (   
 (, % &           $     
   ,  &  
$%&. ?   ( 
      $  .
   (      % &. * % 
& ! %  '   #  $'  ,   #  %   
*7   /
"  # !    $  , &        
  !,   $  200  .     $  
     # %"    ' & $%  ' 
    ?  & (  '  .
  #,    (    
 # !  , 
  ?  #          F &     
   , %  ?  #  '        $
 $ &    ! .
           # ! $     
    $    #   
! ,   $ !! 
      $  # 
  . Y   %    " 
         , %   #        #
! 
dircmp()
$  &
filecmp
 $     #  #
!    #  , 
    #$ 
os.listdir
  " . ;%"  "
 $ % &   #$ 
  #(  M[5, %   $ &     $  .
      MF5
%    #   M[5 !     
 #      !     # $   
 ' & " . @  
'   &    ,
    &  &     #   (  &(, ( & 100 
      '  # #      ! .
  6.7  $ ! &, &   # !
 $    # .
% ;.7. 2+  /& %%+ UD6 &
import hashlib
def create_checksum(path):
"""
4  . G  3@ -- ,     .
G7 @  3@ --    .
"""
fp = open(path)
checksum = hashlib.md5()
while True:
buffer = fp.read(8192)
if not buffer: break
checksum.update(buffer)
fp.close()
checksum = checksum.digest()
 6. 
;'   &    #$
&   !     
    % IPython &  & ( ! :
In [2]: from checksum import createChecksum
In [z]: if createChecksum("image1") == createChecksum("image2"):
...: print "True"
...:
...:
True
In [5]: if createChecksum("image1") == createChecksum("image_uni~ue"):
print "True"
...:
...:
       #  !   & %, 
    '   #$  #   ,   ,
  $   , &    & 
        % #    .    #    API
    , %   #  '  #$  #    % IPython
 #   & "(  "        ' . 
,   "    ,   '   $  #    #.  
  6.8   &   ,     
 ! .
% ;.8. 2+  /+0 %% UD6  "  
 A/   "-  &
In [1]: from checksum import createChecksum
In [2]: from diskwalk_api import diskwalk
In [z]: d = diskwalk('/tmp/duplicates_directory')
In [q]: files = d.enumeratePaths()
In [5]: len(files)
Out[5]: 12
In [6]: dup = []
In [^]: record = {}
In [8]: for file in files:
*7   /
*     ,
     %&    
 (  (, % &    7.  #   $   
 #,  $   (&  %    #   
% . J &      '   #,    
%    &   #& . { ,     
!     . @  #    % #  
  ,   $    '   #$  #  $(  
&(.    ,  % #   .     #,  $
  6.9.
% ;.9.  "- 
from checksum import create_checksum
from diskwalk_api import diskwalk
from os.path import getsie
def findDupes(path = '/tmp'):
dup = []
record = {}
d = diskwalk(path)
files = d.enumeratePaths()
for file in files:
compound_key = (getsie(file),create_checksum(file))
if compound_key in record:
dup.append(file)
else:
#print "Creating compound key record:", compound_key
record[compound_key] = file
 6. 
In [1]: import os
In [2]: os.remove("10
10mbfile.0 10mbfile.1 10mbfile.2 10mbfile.z 10mbfile.q
10mbfile.5 10mbfile.6 10mbfile.^ 10mbfile.8
In [2]: os.remove("10mbfile.1")
In [z]: os.remove("10
10mbfile.0 10mbfile.2 10mbfile.z 10mbfile.q 10mbfile.5
10mbfile.6 10mbfile.^ 10mbfile.8
   ,  ! &   &  " &
   % IPython  $ &  #     ( !
 .  ' $ #, % 
os.remove()
 & !, %  
 &    , %  ' 
        # " ' 
&. D% &   & #  ,   '   $  #   
 ,    & #   ,  $  " #  .  
 #    &   %  IPython  $ &      #
   ,  "     % !  &     $ '
   :
In [1]: from find_dupes import findDupes
In [2]: dupes = findDupes("/tmp")
*7   /
  #&    . H  '   $  #    #,
   & # $%     &,  %& ?

file
. |  # '    & &$ #   
  ,   '  #$  # &   & ( ! . )
(    &   &    6.10.
% ;.5. "/ delete
#!/usr/bin/env python
import os
class Delete(object):
"""   , + @7  +W  -  file"""
def __init__(self, file):
self.file = file
def interactive(self):
"""    -  """
 6. 
 & '  !,     &   #. |  '
 $ #& $ ',  
   % (  " $
  & (,     
   '  #  $ & # 
  .
H     '   "#      . ),   ,
 &  ,   & !  $ $  .    &
 '  # $        #$ & ' 
 $  (  . ;' 
& &   '  $  
  :
   '
     8*
239
? 
file
  & '  !. )    #
        .
  !"   '
Y (                ! 
    &,      ,       ,    
         .   "       
              "      &
#   ,         . 
   %  &$ Python,  $
&     "  " 
&    !  & & % #   .    $  
       # (   , &$(     
" ,     , 
#$ " &  , &  $ &
  (,   (    .
% # %       (  &    #&
 (   #   #    #,      #,      # 
   # !   (  .      (  
"    $ %  &$ Python
$ % &   #$   
&
fnmatch

glob
.   %  '    &  &
$ % &  , % ! &
fnmatch()
       
!  "   UNIX  $ $% 
True

False
,  ! 
glob()
 $    !,   (   
  " . Y&  $ &    '(        
"   '  #$  #  & ' &.   #$ 
  &( '        $ &   3.
   6.11  $ ,   #$ & ! 

 #        #$    ,  $ 
  ,     
diskwalk
$  &
diskwalk_api
% ;.. L/#  A& fnmatch()  glob()
   % % "   &
In [1]: from diskwalk_api import diskwalk
In [2]: files = diskwalk("/tmp")
In [z]: from fnmatch import fnmatch
In [q]: for file in files:
...: if fnmatch(file,"*.txt"):
...: print file
...:
...:
/tmp/file.txt
In [5]: from glob import glob
In [6]: import os
240
 6. 
In [^]: os.chdir("/tmp")
In [8]: glob("*")
Out[8]: ['file.txt', 'image.iso', 'music.mpz']
     ,        #$ # "   
diskwalk_api
,    &&   (   !, ( &
&    
4tmp
.       #$  ! 
fnmatch()
, %    #     '  ! " 
"*.txt"
. * &
glob()
% & , %  $  &  
     "     $    ! . * &
glob()
&& &          "  ! 
fnmatch()
,    && &  $        
"     $( $ %.
* 
fnmatch()
      #$  #     
 ,  $  !#  &    (    
  .          (    #
!,   (        " .
  #      ,       " # % 
  $ %       &        (
!        ,  
 (     $  
" . )    , %      # !  '   ,
  & #, ' #    # (. Y&  " &  (
$ %  #$ &      :
1. % #  # !     .
2.  #   # !#
       '
 #   %    # !#  ,  (  & !, "
  , $ ,  #  #    .
3.  #    !     #,   #, ' #,
 %  #    .    &,  $    6.12.
% ;.=.  % &  ' % .mpF  &+
 ' % .txt
In [1]: from diskwalk_api import diskwalk
In [2]: from shutil import move
In [z]: from fnmatch import fnmatch
In [q]: files = diskwalk("/tmp")
In [5]: for file in files:
if fnmatch(file, "*.mpz"):
# 3 -   3  ,   :  3,   -   3
#  -  3 ...X- -,   -  3
move(file, "%s.txt" % file)

In [6]: ls l /tmp/
total 0
rw r r 1 ngift wheel 0 Apr 1 21:50 file.txt
*  ! rsync
241
rw r r 1 ngift wheel 0 Apr 1 21:50 image.iso
rw r r 1 ngift wheel 0 Apr 1 21:50 music.mpz.txt
rw r r 1 ngift wheel 0 Apr 1 22:q5 music1.mpz.txt
rw r r 1 ngift wheel 0 Apr 1 22:q5 music2.mpz.txt
rw r r 1 ngift wheel 0 Apr 1 22:q5 musicz.mpz.txt
  #$     , $    ,   
    ( !   "  
.mpF
     ' #
%       %         &$ Python.
{   $   (  (     ,   %
    $  $ BO]V +Bastard Operator ]rom Vell-,
  $   %   , %  '   #"   #
  !   .
  # , %    & (  %   !    , 
  #$ &  % #    $  #
( !      $%    #.    $
 % #, %        %
   & #&,   % 
 %       (  #$ 
  &# $  #  (
    !  MP3.   % ,          
        &  #$   ,      
   '   #"   , %   " .  $  "    
  , %   #   & $   $   
cron '   %#,     # ! MP3   
& #   %  .    #     
 #   ! " 
.txt
,     ' # (
ZIP(,        #    
4tmp
,  %  
 & # (   #  #      ( ! 
MP3       % . H   '     #    #  ,
,  % ,   && #  #  ,   
  ,  &  &  %          
 ' %  #       % .
'  $ rsync
  ' ,   , $ ,
rsync
         
,   %# $ "& |  @ '   +Andrew
Tridgell-     H  +Paul Mackerra-.   2007    
  &   &  & 3,  %&    " 
  % #   , %
 #&  &.
     & 
rsync
  &           
 & ( $   K   J. ?     % 
     %    $ '(       ' ,
          $ 
#&    ' . J $   
% &   
rsync
 ' %  #  #,     $
          
, $  (, %    $ 
# &  (     .
242
 6. 
      #, % &$ Python   &   #  
    &    
.  $   ,    
  #,   &  , %    % #   (
$   &. H  $      ,   
 (  ( $  #   (  '  & ! 
     #   ,  #   $ ' ,    
   (      #     %. |  $  
&,    Python   #  '  # $%
 #.
   # &$  Python  '   #  
rsync
    
           #    ' .     
    &$ Python  #$ &  &$  
 ,  $ &    UNIX  & #  
 , & (     
 $%#,   &  
   %  $ '  #  $  # % #       
     .  $ #   # %  # 
"  '  .    6.13.
  & % #     
,    &       &
rsync
% ;.F.  -   " rsync
#!/usr/bin/env python
#+    rsync  XQ  - X  
from subprocess import call
import sys
source = "/tmp/sync_dir_A/" #+  -   @7 -  
target = "/tmp/sync_dir_B"
rsync = "rsync"
arguments = " a"
*  ! rsync
243
& # $  #    #. ) #$& Python,   '
 $  #    ,      
rsync
    #    &  
rsync
F   
  # '  , %  ,          
( $ (    :       #&  ' # 
( $     $          
    %     , %    .    6.14
  &              &
rsync
% ;.G. 3%" rsync,    # ',
   + #"
#!/usr/bin/env python
#+    rsync  XQ  - X  
from subprocess import call
import sys
import time
"""K  -  - rsync +   3 X 3
 ,   X X"""
source = "/tmp/sync_dir_A/" #Note the trailing slash
target = "/tmp/sync_dir_B"
rsync = "rsync"
arguments = " av"
244
 6. 
  
J #"   (      %   #   # 
,    &     #&  # ,   
 (. H   ,   (, %   
 #   '  #, %    . ; ,    $
          '  % (& &    #
(   (   !   
   '  $( ! (
 (.  '  $    %    $ 
       &   .
H     ,  $     #$ 
&    !, %  '  # % # ' &  ' 
&, &     $   #     !# 
&        & $  $   . Python  '
 '   %#   ,   #     &$    '  $ 
 #  %  ,   $#   (.
   #$   &
    ORM +ObjectRelati
onal Mapping ?   & &  &- SQLAlchemy &  $
&   ( !     .  % #, & SQLAlchemy
 & % # %   &   &,     ,   
   SQLite. ; " $& ,   && &,  
$ && $  #    
 " &     
.
  ( "   & ( !       '
 #    ,  $  $    &  & 
'  !. |    &    ,     
 !   ,  '   ! , 
"          # &  , %    #
    .    6.15   ' ,  %  
 #  ( '        , ?    ( 
         ORM.
% ;.6. ?#" %"+0  && %
 %/ S^[Qlchemy
#!/usr/bin/env python
from s~lalchemy import create_engine
from s~lalchemy import Table, Column, Integer, String, MetaData, Foreigney
from s~lalchemy.orm import mapper, sessionmaker
import os
# 3
path = " /tmp"
#4 3 1:  - X-
engine = create_engine('s~lite:///:memory:', echo=False)
#4 3 2: - 
 :   /
245
filesystem_table = Table('filesystem', metadata,
Column('id', Integer, primary_key=True),
Column('path', String(500)),
Column('file', String(255)),
246
 6. 
  !        (      .  $ #
 &    (   .    , % & ' 
      !  $  & #& $#, & $   
(& &  $ (.       #  %     
'   $   "  $ (,   '    & .
;  ,   #  %   &
& $   &$ Python, 
 % ,  $ $,        $ (.
|        # &      $ '  #    
    #   $    
(  "   #$ &  
(      SQLAlchemy  "      
. |    ' " #     #  $
 '  &,      &
( $    $#  
$#    !    .
*    K % K ' % 
  
Y  &   #" ?  (   &      
,             & $ &
 #. Y&   &      %  #$
tar
gip
bip
bip2
hdiutil
asr
    .
  # , (   ,      %     ( &  
        &   &$  Python    
  '  TAR! , zlib!   gzip! . { 
  & '   (  , $% ,       (  
 , . . &$ Python         ( (  
  . Y  '     "   ( (  
tar   ,     & 
   $   ' .
+    $ tarfile $   $
   TAR
 $  # ( TAR % #   , ' "    .    6.16
  $   % #  #"  !.    , %   
 $ & (       , %  '     #$ 
&    
tar
% ;.;. ?#" -/'   &
In [1]: f = open("largeFile.txt", "w")
In [2]: statement = "This is a big line that I intend to write over and over
again."
ln [z]: x = 0
In [q]: for x in xrange(20000):
...: x = 1
#$" ! tarfile ! "!  / TAR
247
...: f.write("%s\n" % statement)
...:
...:
In [q]: ls l
rw r r 1 root root 12z6992 Oct 25 2z:1z largeFile.txt
@  #,      &  #"  !,      ,  
    (  TAR,   $    6.17.
% ;.7.  0  " % &
In [1]: import tarfile
In [2]: tar = tarfile.open("largefile.tar", "w")
In [z]: tar.add("largeFile.txt")
In [q]: tar.close()
In [5]: ll
rw r r 1 root root 12z6992 Oct 25 2z:15 largeFile.txt
rw r r 1 root root 12z6992 Oct 26 00:z9 largefile.tar
   ,   $  % ( TAR, %     
      , %    #$    
tar
. |   
    $      #$    %  IPython &
  &               .
;  &      $ & (  TAR    # Python, 
   ,  %      $   #  (   
  !. ) #$& ' 
   (     , 
  '  # $  &     ,  '   #
( TAR  #   
4tmp
, & %    %   # (
        #  ( '  !, ( &&  
 
4tmp
,   $    6.18.
% ;.8.  0  " % "  
In [2^]: import tarfile
In [28]: tar = tarfile.open("temp.tar", "w")
In [29]: import os
In [z0]: for root, dir, files in os.walk("/tmp"):
....: for file in filenames:
....:
eyboardInterrupt
In [z0]: for root, dir, files in os.walk("/tmp"):
....: for file in files:
....: fullpath = os.path.join(root,file)
....: tar.add(fullpath)
....:
....:
In [zz]: tar.close()
248
 6. 
 , %   #  (  '        
( ,  %   '  ,   % #   (   ,   %
  ' ?  #    ,  "&
   .   # , %  (   , $  
#   !. J   $ (  # 
 ,         '  & #& '    ( 
  $  #     %    .  & $
&,  %      ,     '  #  
,                 
  .
  #   $    ( (  TAR $&   #  %
 ,    '  
bzip2, % $  "   
    #  '  #&  ,         .
K   ' & bzip2     ' $ #& %  "  .
  ,  #  % &    #  '  #.
 $     ! $   60 H   '   10  ,
  $    6.19
% ;.9. ?#"  0 TQ\,    % bzip=
In [1: tar = tarfile.open("largefilecompressed.tar.bip2", "wb2")
In [2]: tar.add("largeFile.txt")
In [z]: ls h
foo1.txt fooDir1/ largeFile.txt largefilecompressed.tar.bip2*
foo2.txt fooDir2/ largefile.tar
ln [q]: tar.close()
In [5]: ls lh
rw r r 1 root root 61M Oct 25 2z:15 largeFile.txt
rw r r 1 root root 61M Oct 26 00:z9 largefile.tar
rwxr xr x 1 root root 10 Oct 26 01:02 largefilecompressed.tar.bip2*
   # ,    bzip2   # ' #  
! $   61 H  10  , ( &    " %, 
 #$&   '      .   % ,  !! 
 %       ,   %     $ (?& 
      AM[       #   #  .
@  #      #& #"   $  # '  ( 
    , %  gzip.        & &
 #  $% # ,   $    6.20.
% ;.=5. ?#"  0 TQ\,    % gzip
In [10]: tar = tarfile.open("largefile.tar.gip", "wg")
In [11]: tar.add("largeFile.txt")
ln [12]: tar.close()
#$" ! tarfile !        TAR
249
In [1z]: ls lh
rw r r 1 root root 61M Oct 26 01:20 largeFile.txt
rw r r 1 root root 61M Oct 26 00:z9 largefile.tar
rwxr xr x 1 root root 160 Oct 26 01:2q largefile.tar.gip*
K( gzip ' % &    &   #  $  ,  
 "#  160  , %     " '  ( TAR
  $  $   #   .   #"       
(   .
+    $ tarfile $   
  %  !" TAR
@  #,      &     $ & !  TAR,  #
     #    #  ' !  TAR.  $  # !
TAR  "#   . {         
     %  ' #  &, ,   &  , % #
   #   %      $      % #  # 
    $   %      $   .
   $         %   # '  #    
(  TAR,   &    "  "    ,
 $       "  ( TAR. ) , $
&  !  && & " . /   &   
#  # && & %.
;"            %       
     % $  '  ,      &  
 &    ' %   . D      &   
 &     , #
    '  %   .
{  $   &,    " "   "  (,
     &    
         
&   % #     
       ( 
  ,    #"   # 
          
   #    #   . %     # 
$& " ,      .
  ' , "   % $  '  $ (   
" "  . { '   $ #&, %    &   
 #   ,           '    ,   
   $ ,    ( 
 & #  $$  (   (
 & . {   #  ,  $ &&   #&, % 
(   $      ,          
  , & !
   '  ( ( 
TAR,    %    $ # &   " "  ,
   , %  '    #,   "#      ,
  " " & #   ' &         & 
% &  &.
 6. 
'  "   #&  $  %#   $:
#&, $       ,    &      $ 
 &. #& $ '  "  %#   $, % 
" ", K ,  #&    '  ( 
?    " , $$ %   $ " $ '     %   
   .  K      %   "    J ,
%#  K , $  &.
;%#  $ #&, % ,    K ,  $ & &
 ' #   '  !  % $$     
       " .   #&  $  , %   
   , %    $   &   % (    
    &$ Python  ,    &  
'  (  $  (  (  TAR  $ " 
 &    ( !      $    &.
$ #, % K         "   %  % 
   # (  &  (
 #  &  .
   K         ! ,     "    & 
    &      
    .   %
 # & K ,  %            & 
 &  % $   .  $ ' ,   (     ,  
'  ' , "   "
 "     "  (
TAR.
H #     $ % &  , % ,   (  &  #
   $  &,      #&   & 
 ' ,    $     ( #     
  , (  '   $  .
;'    &   #          ' 
! TAR,  $    :
In [1]: import tarfile
In [2]: tar = tarfile.open("temp.tar","r")
In [z]: tar.list()
rw r r ngift/wheel 2 2008 0q 0q 15:1^:1q tmp/file00.txt
rw r r ngift/wheel 2 2008 0q 0q 15:15:z9 tmp/file1.txt
rw r r ngift/wheel 0 2008 0q 0q 20:50:5^ tmp/temp.tar
rw r r ngift/wheel 2 2008 0q 0q 16:19:0^ tmp/dirA/file0.txt
rw r r ngift/wheel 2 2008 0q 0q 16:19:0^ tmp/dirA/file00.txt
rw r r ngift/wheel 2 2008 0q 0q 16:19:0^ tmp/dirA/file1.txt
rw r r ngift/wheel 2 2008 0q 0q 16:19:52 tmp/dirB/file0.txt
rw r r ngift/wheel 2 2008 0q 0q 16:19:52 tmp/dirB/file00.txt
rw r r ngift/wheel 2 2008 0q 0q 16:19:52 tmp/dirB/file1.txt
rw r r ngift/wheel z 2008 0q 0q 16:21:50 tmp/dirB/file11.txt
In [q]: tar.name
Out[q]: '/private/tmp/temp.tar'
#$" ! tarfile !        TAR
251
Out[5]:
['tmp/file00.txt',
'tmp/file1.txt',
'tmp/temp.tar',
'tmp/dirA/file0.txt',
'tmp/dirA/file00.txt',
'tmp/dirA/file1.txt',
'tmp/dirB/file0.txt',
'tmp/dirB/file00.txt',
'tmp/dirB/file1.txt',
'tmp/dirB/file11.txt']
In [10]: tar.members
Out[10]:
[TarInfo 'tmp/file00.txt' at 0x109eff�0,
TarInfo 'tmp/file1.txt' at 0x109efz0�,
TarInfo 'tmp/temp.tar' at 0x10aqz1�0,
TarInfo 'tmp/dirA/file0.txt' at 0x10aqz50�,
TarInfo 'tmp/dirA/file00.txt' at 0x10aqzb�0,
TarInfo 'tmp/dirA/file1.txt' at 0x10aqq10�,
TarInfo 'tmp/dirB/file0.txt' at 0x10aqq^0�,
TarInfo 'tmp/dirB/file00.txt' at 0x10aqqd�0,
TarInfo 'tmp/dirB/file1.txt' at 0x10aq5z0�,
TarInfo 'tmp/dirB/file11.txt' at 0x10aq59�0]
|     $ ,   % #   ! , (& &
( TAR, %       #  $ '  # (  $
  #   ,   &   . )$ %  !  $ (
   & & % #   ' .
{     & $ %# 
! $ ( TAR    %   ,  '   #$ 
 #&    !  :
In [60]: tar.extractall()
drwxrwxrwx ^ ngift wheel 2z8 Apr q 22:59 tmp/
{  % $%  $ #,    '  #,
     $  #  %   #(  M[5 %(
!   $ %  ( $ (   # (     
   # ,    (    
!   (. | % # !!       #&  , %
     # (  " .
;  $  "   '
   #&     ' 
, % (   $   $ " .      , ( &   
 %&     (  '  & #&   %  . ;
%" ,  $    $ & '  (   #&
  & #&.
SNMP
  
  SNMP  ' $  # " '$#      
. %  #$ & SNMP  &     , 
  # (        &$ Python,  &(
$ ! ',  ,    !   SNMP 
  ,      %  & #.
           SNMP:  
'  ,  �  ,  $    ,      
 ,   ,     &    SNMP. J $
  ,    '  $  #  &$ Python.
{   $   SNMP     &  ' #   $&
SNMP,   & #       %  #  Essential
SNMP Y H +[ouglas Mauro-    }  +\evin
Schmidt- +OReilly-  ( &  ' #   .  " 
 % && &    
     $ '  
SNMP.     $       SNMP,   
$%      (   $     .
   #     #$ & Python     SNMP
 # ", % $' #  .
#      SNMP
   3000    SNMP     &    
 IP &(.   ,          U[P 161
162, ( &    $ '  #$  #     TqP.  %  
           
(   (  '
      SNMP
       SNMP,   $% , %  &  $ '
  # & #  #     " $ , 
 '   ,  ,          &, 
 &      .
    SNMP      % (     U[P
 '   . @  $           $ 
 &       . @     ,   SNMP  
 $   "   $ '  &  & &  
     $ '    $ &   ,  %(  $ .
;  %    , %  $ '     
SNMP, && &    $
     ,  #$ &
   ?      & . |    '  '  #
$  #& &  &     ,     #
   $ ' '  & # $$   (    
      . H  $   , % %  '  '
  & #     
   % &,     
 ' &  $ (. ; 
,  &  '  RMON MIB
+Remote Monitoring Management Information Base $ & 
!  &      
-, &   %  
   ,     %   ' SNMP  &
& &      %  (  $  .
H '  &    MIB,     % ?&, %
  . SNMP    "#  ,       (
   '  (. ;    #(    (  & 
&   , snmpd,     &   % # ? ,    (
  . * %     % #   &    $ 
&  ! ,  MIB +Management Information Base-. D '
     &,      ,  $ MIB,    
       ! & MIBII,  &   R]q 1213.
J$ MIB  '    #    !,   #$ &
& &    % +%   ( '  [NS-, ( &   
      ' .
   ! ( & & & ?   &. D ' 
?   &    : &,        &  
 %. )$ (  %    &   #   . ) 
%  $   !   ? ,  OI[ +Object
Identifier-.   &  OI[   ,      , %
  (    % #. )     !     &:
%     %  .   #$ &   %  &
!   ,   % %       #"   (
 ' $  #.  $ ( %  #$ ( OI[ && 
& sys[escr. {    #$ #          
snmpwalk
, %   % # $%    !   sys[escr,   
'  #$  #    %  
,   %  !   
  &:
 9. SNMP
[rootYrhel][H:qq61]# snmpwalk v 2c c public localhost .1.z.6.1.2.1.1.1.0
SNMPv2 MIB::sysDescr.0 = STRIN: inux localhost
2.6.18 8.1.15.el5 #1 SMP Mon Oct 22 08:z2:0q EDT 200^ i686
[rootYrhel][H:qq61]# snmpwalk v 2c c public localhost sysDescr
SNMPv2 MIB::sysDescr.0 = STRIN: inux localhost
2.6.18 8.1.15.el5 #1 SMP Mon Oct 22 08:z2:0q EDT 200^ i686
        $        R]q,  
$      #    ' 
   #      #. H  
 , % % #   &    $  
  .
    " SNMP
Y&   & # "    
 &     #$  #
      SNMP
NetSNMP,     %#     ,   (   
  #     # " & & Python. { '    
      #   NetSNMP,   
 9. SNMP
   , %  $  &
configure
    &
$  #     %      . ;   &$ #
  #  .    
%  $  #   !
  !.  Red Vat     %  (& &  !
4etc4snmp4snmpd.conf
        :
syslocation "O'Reilly"
syscontact bofhYoreilly.com
rocommunity public
|     !      % &   &  
    " & %    $    &  #    SNMP.
 & SNMPv3    #    '        
   &     , ( &     (  
$  #, %   $   %"
 #$  # SNMPv3,  
  2  1       $ . | $% , %    
   #$  # SNMPv2  SNMP
v1 &   % $   %  $
)  ,   #   !  '  #   (% . )$  
%  ( $  ,     $ '  &
 #$   (  .
IPython NetSNMP
{  '      $# $  & SNMP,  
 '  $  #   , %   & & &  .  
   &,     #.    SNMP %         
 $$    '    , $$  (    %  #
 #" % R]q  $$  ( "    # " . 
$        #&  #    #     , %  & 
 & SNMP   % &    &  API  #$ 
 #   %  IPython.
   7.1     % #   !    
 & $    #  " .
% 7.. L/# WPython  `e&#x-6.9;&#x.-1.; L;.1;&#x-5;&#x.98;&#x.1/5;&#x.1#-;.5;.5;.8;.5;&#x W;&#xPyt-;.5;&#xho7.;n ;&#x -13;&#x.3`1;.1e;�.1t;tS`UP  ' % Python
In [1]: import netsnmp
In [2]: oid = netsnmp.arbind('sysDescr')
In [z]: result = netsnmp.snmpwalk(oid,
...: ersion = 2,
...: DestHost="localhost",
...: Community="public")
Out[q]: ('inux localhost 2.6.18 8.1.1q.el5 #1 SMP Thu Aug 2^ 12:51:5q EDT
2008 i686',)
     % #     #$  ! 
   &  '  " &.      
   #$  !   
&  IPython     #
 $  % #    $  SNMPv2.  %      %
&:   !   sys[escr,
   '    ,
  &    % # ' $ ,  $ &  % # 
$  (    ".        ' 
#  %  ( ' , ( &     % , , %    
uname
   $ '    
, $    $  sys[e
scr && & '  % #  &       (.
  ' ,       & SNMP,      
% . ;       
  $ #     ,
     $ # ( #    $,     ! 
,  : ]ibre Switch +       -,  
    $ #        !   $  
&. D     %   , %  & #&    " &
    ,  $ , %   $  #    $
%&  $   # ,  %   #" #%  $  #.
  ' $ $  2 IPython,     $ '  #  $
 #      !    #  ! &
$   %  IPython,   %"#     im,    
  :
ed some_filename.py
  (  $      %     $    &
           '    (  
who
. |
  % #    #$  #    SNMP,    
  #   &     $   &
       #. Y  & #"  $"   
 ' !       !    
snmp.py
   :
ed snmp.py
   7.2   &  
  #,   &   
"   $ &      # NetSNMP.
% 7.=. & %"/ #"   %/ `et�S`UP
#!/usr/bin/env python
import netsnmp
class Snmp(object):
"""     SNMP"""
def __init__(self,
oid = "sysDescr",
ersion = 2,
DestHost = "localhost",
Community = "public"):
self.oid = oid
self.version = ersion
 9. SNMP
self.destHost = DestHost
self.community = Community
def ~uery(self):
"""  SNMP"""
try:
result = netsnmp.snmpwalk(self.oid,
ersion = self.version,
DestHost = self.destHost,
Community = self.community)
except Exception, err:
print err
result = None
return result
      (  !    
,   
%   :
In [2]: who
'The MIB for Message Processing and Dispatching.', 'The management information
definitions for the SNMP User based Security Model.',
'The MIB module for SNMPv2 entities', 'The MIB module for managing TCP
implementations', 'The MIB module for managing IP and ICMP implementations',
'The MIB module for managing UDP [snip]',
'iew based Access Control Model for SNMP.', '0', '0', '0', '0', '0', '0',
'0', '0')
@   #        #    &
    SNMP   &  .       ,   %
         #,  '   #    $ 
    $% & OI[  '   # (    
MIB.  (      MIB  ' $& #    &,
  %    &   # $  &  '   $% 
OI[,          ( %   #$ &, 
        & #&       ".
; $ , % MIBII    "# !  $% &
OI[,  (       #"   ,  (
 '  SNMP. Y MIB,  # & '   
$  &,   &  #( !(,   
'  #&   , %    #   $ . { 
$(           #   ,  
&    $ 
    $ 
&     ,    $ MIB   $" #
   OI[.
@  #      #$         %  IPython, 
&  $ & $  #    $   !     ' :
In [11]: bg s.~uery()
Starting job # 0 in a separate thread.
In [12]: jobs[0].status
 9. SNMP
managing UDP implementations',
'iew based Access Control Model for SNMP.', '0', '0', '0', '0', '0', '0',
'0', '0')
 ' %      (  , $ "   #, % ( &
      !    
'    $   IPy
thon,     ,   '  '  #$  #& #   
  ,  ' (   #   
&. K " & Python & NetSNMP    (    
' .  (  (  , %    '  #    %
   , '   ,       '
    &$ q.
 % #,    $   ,  $    (
  $ %  ,    #  &      '  $
 # %     & 
 #    & $  
SNMP.     $         $ &  
&,     %     #     
(.
+     
' ' 
 $     $(    SNMP $ % &   #$ 
     &  &      (.  
   &,  (  &   & & #    ,  
% (  ,   $  &   !    (    
(. J  #        #$  #& &
& & &$   '   
 ,  , & 
%  MAq  ,      $      qisco,
 (    & &  &        
Brocade.
   $    $       ,   
 #   IP  , MAq  ,   ! ,  
 &     SNMP,     #  $. |  
 '  #$  #&  "  $    &  $
  ' ,  &(        
(.   $   &     #$  #  &, 
  #  ( (.
     # $%(      &,  
  (  #    #&,  #  $ (   
  "  .  #          :  
 #   $      IqMP= '   "   
     #    $  SN
MP=  $  #  =  
' #       % ( (. Y    
 $       $   SNMP         
#     ,  ,  '    # " ,    
%&   $      . $&    7.3.
#     * * /
261
;  #" $ %     ' :   # 
  NetSNMP     $ '  #  
#  (    ' ,   $   %    
$  
subprocess.call()
. |    $ '    & 
&    .  %   #$ &   
ping
  
    #$  #
subprocess.Popen
,  %   ( #
 $ ,   #$    '    & 
  & $   SNMP,     #$    
ping
% 7.F. & A & " A  - -  "+0
#!/usr/bin/env python
from processing import Process, ueue, Pool
import time
import subprocess
import sys
from snmp import Snmp
~ = ueue()
o~ = ueue()
#ips = IP("10.0.1.0/2q")
ips = ["192.19.101.250", "192.19.101.251", "192.19.101.252",
"192.19.101.25z", "192.168.1.1"]
num_workers = 10
class HostRecord(object):
"""?   -Q   X X"""
def __init__(self, ip=None, mac=None, snmp_response=None):
self.ip = ip
self.mac = mac
self.snmp_response = snmp_response
def __repr__(self):
return "[Host Record('%s','%s','%s')]" % (self.ip,
self.mac,
self.snmp_response)
def f(i,~,o~):
while True:
time.sleep(.1)
if ~.empty():
sys.exit()
print "Process Number: %s Exit" % i
ip = ~.get()
print "Process Number: %s" % i
ret = subprocess.call("ping c 1 %s" % ip,
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
 9. SNMP
else:
print "Process Number: %s didnt find a response for %s " % (i, ip)
pass
def snmp_~uery(i,out):
while True:
time.sleep(.1)
if out.empty():
sys.exit()
print "Process Number: %s" % i
    "    %$& SNMP
263
#1 SMP Mon Oct 22 08:z2:0q EDT 200^ i686',)')]
[Host Record('192.19.101.251','None','('inux linux.host 2.6.18 8.1.15.el5
#1 SMP Mon Oct 22 08:z2:0q EDT 200^ i686',)')]
Process Number: q didn't find a response for 192.168.1.1
 %   $#    $ ,       
    &      (.     
 '   %  #:
 ,  # $# MAq
    ?
HostRecord
,    #      ?
         ,    (     
,  $ (      .  &  , 
  (    $ .
  %   " :; SNMP
 %      $% &    &  #"   ' 
 , ( &     '  #
    #      #
    ,   , 
 ,       
,       
 # .    #
%    $% ,   (   % #   # $% 
    #     &  .
  $  $ %  $     $     
(      #  &  (  (  (
 (& ".       %    : 
  #     
      % &  
 $, % ' &   '  #   1  D.
   , %   #"  #       &  
  1  ,    &%  ' (  #  
 &   #  (,  &   #"     ? .
%   , %    &   #    .  
 '  $ (:
2 
*$%       #      # ?  D  '
 $ (, $         . Y 
 % %   , %  
   #  .
2  =
      '  #     #  , % 
  # ?  D. |  (        ,
  ( &   %    '  $  #    &,
 &       ssh.  $  (   
    , %   '  %  # $%&  ' 
 ! ,          %    
% &. Y&    $ % &   (    $ #,
    #    &.
 9. SNMP
2  F
; #   #"   ,        ,
 %    #,    ?
 &   '  $ (
  # SNMP.
 3,     #$  SNMP,  $ &    $
 # #,          # # # ,  
   1   D. @ %   !   OI[,    
 & $  #,   & hrMemorySize.   SNMP  
 & $&  (    ,        #$ 
 #    $ %   ' ,          $
%" $  #,    && &     ( .  &
  ,           &.
      # "  
,   #$ &   
 $      .
 %  ?  &     # SNMP:
In [1]: run snmpinput
In [2]: who
    "    %$& SNMP
265
@  #,       ,   '    $  #   
   & & . {    #      ,  
  #  # , & #,   ( $ (     
&    2  D  $  $ #  %  ! 
! !   qS
, %           #  Ex
cel  OpenOffice qalc.
Y  '  #         ,  
 $   (      
%   (      , 
  # , $%    ! 
 OI[,   %  #$&
  !   hrMemorySize.         ( 
    # (  (     $  $  $ .
&  $,         "  
,     &   
 % &.    &
     #   # %   '     $   #" 
?         &,     ' 
 #$  # &  " & ( $ %,   '    
% # ( &  $ #  $#  F ; " $& ,   #
"  %     '   #   $.  
 #$  IPython   '    $  # $    
  $    # ( % #    &&.    ( 
 "&  &  #         #$ &,
  #    % ,   ' ,      
' &.
; &, %  #    ,  %  $ % &  SNMP.
Y    $  "   &
  'Q $
          $       
  ,  & ?  & ,       # (,
   # SNMP:
#!/usr/bin/env python
# -  -  ,   @7 +7 +W - -   -[email protected] 
import netsnmp
import optparse
from IPy import IP
class SnmpSession(object):
"""     SNMP"""
def __init__(self,
oid="hrMemorySie",
ersion=2,
DestHost="localhost",
qS,  qomma Separated alues, $% &, $   $& .
%.  .
 9. SNMP
Community="public"):
self.oid = oid
self.ersion = ersion
self.DestHost = DestHost
self.Community = Community
def ~uery(self):
"""  SNMP"""
try:
result = netsnmp.snmpwalk(self.oid,
ersion = self.ersion,
DestHost = self.DestHost,
Community = self.Community)
except:
# -   ,   K    3 - ,
# -  -  ,   -,  @  
import sys
print sys.exc_info()
result = None
    "    %$& SNMP
267
 9. SNMP
@  #   &         , %   . H
$&    $               
 #.         ,  $
            #  &
optparse
. H #
IPy
    &   
 ,  #$ & &   
%     IP   . J &    '  $ #   #
IP     $     ,  "  #   # $
  SNMP   $ #  $#      &,     #
%     # IP  ,   # $%    SNMP.
{   &  '  #, & $ #  $ ,     
   (             $% &. @  #  
#  $ # $% & '  $    .  
 #$       '   % # $% &   $#  
 %  # $%&  ,  $ #  %& ? 
& .
     ,  %    $#       &:
    "    %$& SNMP
269
;"     &  $  ,    ' 
  #  % , %   $  #  . {     
&   #   # &% ", &   &    
   '     #&   #  '  #" . | ,  
'  #,    " ,  
   &  
% #  $#  
% #   ,   (     % #  $ '  # 
 #    &   # ( $        $ 
 #    & '  $ ,  #$& &    
     $  &. {
   "    , 
 '     ,    %   $  ! % 
!  qS $ "   &.
;  ' %        $  ( $ %,  $ # 
 # "       ,  ,  $ ' ,  $ 
.     , %
 $ & $" #   OI[,
 #  & # ?  & . | % #   ,   %
  #  &   
   & ?   & ,
   #    ,  $ &  & #  $
  SNMP.
   ,  &     , %   
  :
 9. SNMP
    '     SNMP
H '  $    # #(      (  
  #, %  #$      ' ?  # &  $
&  #  '(    . ;%    $ &    
 ( $  $ (    ,    (  $ 
   '   $  #  #"  .
;'   &   $      
snmpstatus
, 
 %   # $%( $   snmp   $ (
  & "   $:
import subprocess
class Snmpdf(object):
""" -  -   snmpstatus"""
def __init__(self,
ersion=" v2c",
DestHost="localhost",
Community="public",
verbose=True):
self.ersion = ersion
self.DestHost = DestHost
self.Community = Community
self.verbose = verbose
def ~uery(self):
"""   snmpstatus"""
ersion = self.ersion
DestHost = self.DestHost
Community = self.Community
verbose = self.verbose
try:
snmpstatus = "snmpstatus %s c %s %s" % (ersion, Community,
DestHost)
if verbose:
print "Running: %s" % snmpstatus
p = subprocess.Popen(snmpstatus,
shell=True,
stdout=subprocess.PIPE)
out = p.stdout.read()
-8  "    Net;SNMP
271
if __name__ == "__main__":
_main()
H  &, %      ! , %   
  # % &  
snmpdf
, $  %    
(  . | %  ,     '  #    
       #     $      #$  #
    . {    $   #,    # 
   , "   
   &    $  
 # (   . )   
 ,     &  .
Y     ,    "  SNMP,  ARP, 
  #$   ARP.    #   ARP  '  
% # MAq        ( IP  ,   , % 
( & &      '  . Y "    $  
$     .  
  &      $' .
!  #  &     ARP    &     
   =  ' $      #      ,
 #$&      %  IPython. )  , $  IPython
     :
import re
import subprocess
#     - 
ARP = "arp"
IP = "10.0.1.1"
CMD = "%s %s " % (ARP, IP)
macPattern = re.compile(":")
 9. SNMP
 $ '  # "& #    % #. H '    $ #   
  (   #   #    &  $   $ # (
   SNMP.
*
EXQUP[E.conf
,   &      NetSNMP,  
$ %"(  %  !   "   $ '  
-8  "    Net;SNMP
@  #,    
snmpd
  %  $   !
snmpd.conf
, 
 '   #& #"    #
"  " $     #
 
snmpwalk
 9. SNMP
  #  $  ]irefox.      (   $
   SNMP.    7.5   & (    
&,  $  &     $    OI[.
% 7.6. ?A &    - & -�   Qpache
# - #  Yirefox
import re
"""G7  +7   +  Firefox"""
def grep(lines,pattern="Firefox"):
pat = re.compile(pattern)
for line in lines:
if pat.search(line): yield line
def increment(lines):
num = 0
for line in lines:
num = 1
'       " SNMP
     '  & (    ssh        
$ #&       .
     "    SNMP
 $ (   (     & SNMP && &
 $ '  #  &         . %  
 , %       & " $       
        
 #$  ,  ,  &
Pexpect +
 9. SNMP
 #       ,   %     ,    
' #   ! , % %    ,.
)    $ % :   SNMP    & 
    &     ,     ,    &
"   $ '           % #
     ,   #  && &  #   !   &
   ,  "(& %&  1988  .      $ '
% #    $    SNMP v3.
+  $ SNMP      $ $
:;Zenoss
Zenoss   &    $ % #    &  
#  &  &  & 
&. H  , % Zenoss && 
&  '  ,   &     (   
,        
&$ Python.   Zenoss &
& &           &  '   &  
& &,  (  #"  $ '  &   (
"    #$    !  XMLRPq  ReST.  
  #  !   ReST  #  /  
%   +Leonard Richardson-    +Sam Ruby- RESTful
Web Services +OReilly-.
;  ,     & & '  %   #  $ Ze
noss,   '   #    &.
 "  !" Zenoss
     !        !  Zenoss 
 #  
http:44www.zenoss.com4community4docs4howtos4send�
events4
+   Zendmd
  Zendoss  #   & &        
   & SNMP,    %   &     
!     &     zendmd.   '  # 
       %  Python   & #   Zenoss
      .
   #$ & zendmd:
��� d = find('build.enoss.loc')
��� d.os.interfaces.objectIds()
#  ! SNMP   $   !!  %$&Zenoss
 "  !"      " 
    Zenoss  '  ' $    # %  $  ! 
XMLRPq  & #   & # 
  . ;'  & & 
 :
  #$   ReST:
[enosYenoss $]
wget 'http://admin:enossYMHOST:8080/port/dmd
/ZenEventManager/manage_addEvent|device=MDEICEcomponent=
MCOMPONENTsummary=
MSUMMARseverity=qeclass=EENTCASSeventClassey=EENTCASSE
q  #$   XMLRPq:
��� from xmlrpclib import ServerProxy
��� serv = ServerProxy(
'http://admin:enossYMHOST:8080/port/dmd/ZenEventManager')
      
  
J #        $%  $%  #  " 
  ?    . 
,   #  
 '         % ( & &  !  " 
 &&.   &  & %   # ( &   #  !
!        ,   (  $ # (
 ,            . Linux Solaris,
Mac OS X  ]reeBS[      '  #  $ .
@ #  &  ' ,  '         
      ,  AIX  VPUX,   
  (     &.
 % #, $ #     # & # (  &$ Python  
&, %     ,
%     &$  (    
" &    &  , &        #
 %              ( $ $(
  (  .              &  
,   $ &   
     $  #  ,
%   (  , ( &       & ! 
     $ ! ( ! .    # &$ 
Python         #    %    # % 
 , %      (        .
  (  ' "(  &( %   %   & #  ,   
 &        ,  (   $  
#   ( !#    % #(   (,  
(  $   & &$  Perl   #$ &$  Python,  
 %     $ &  #         %  
   . ^$ Ruby    %    &$
  &,     #$ &   ' #   
 ;       !" Python  UNIX
279
   &$  Python,  ,     ,    #       
  "   $ '   &$  Python        
 &$  Ruby   #$   %   &$      
  &.
        #&   #   (  ,
          
 #   $ (  
%  ,   &  # , %   $ #, % Python
 '  #  #   #
    !    &$ 
  ,    #        & '  $
  (  .    ,   $  $&%  &
  &  , &   !      
(. |   &  !   % $ +$- %& 
  ( +qloud qomputing-,       , %  
  Amazon  Google.
;  #  $ #% #   #.  (  & % 
 (  #  % ,  "  $   (  F
#  !      
$ Python  UNIX
&  '  $ UNIX      
     $% 
$%&,     (  
 #" .  $      # $%   nix   
 , %   $  #   !         
,    $%&  '      .
       #&    #$  #     ,
   &          .
^$ Python  $    !  !     ( &  
        &
    &  " &  
%       ,      '    #&. Y&  
 &   ! ,     & & "  
,     #
platform
. Y  '  $ &  
   #$ &    &.
        $  #&   $ '  &  &
plat
form
 #  ,     #    
!    ,   $    8.1.
% 8.. L/# %" platform "   %A
 %
#!/usr/bin/env python
import platform
profile = [
platform.architecture(),
platform.dist(),
 .  8 "  / 
platform.libc_ver(),
platform.mac_ver(),
platform.machine(),
platform.node(),
platform.platform(),
platform.processor(),
platform.python_build(),
platform.python_compiler(),
platform.python_version(),
platform.system(),
platform.uname(),
platform.version(),
for item in profile:
print item
;'   &  $#       &     
  OS X Leopard 10.5.2:
[ngiftYMacintosh 6][H:108^9][`:0]% python cross_platform.py
('z2bit', '')
('', '', '')
('', '')
('10.5.2', ('', '', ''), 'iz86')
iz86
Macintosh 6.local
Darwin 9.2.0 iz86 z2bit
iz86
('r251:5q86z', '`an 1^ 2008 19:z5:1^')
CC q.0.1 (Apple Inc. build 5q65)
2.5.1
Darwin
('Darwin', 'Macintosh 6.local', '9.2.0', 'Darwin ernel ersion 9.2.0:
Tue Feb 5 16:1z:22 PST 2008; root:xnu 1228.z.1z1/
REEASE_Iz86','iz86','iz86')
Darwin ernel ersion 9.2.0: Tue Feb 5 16:1z:22 PST 2008;
root:xnu 1228.z.1z1/REEASE_Iz86
|    $ &  % #     ,     
! &          .   " 
   $    !          
 (     $  #  #
fingerprint
,    # 
 %  # ,  &&,     !  ,       
    & &.        $&  % 
#    (   (  : Mac OS X, Ubuntu, Red
Vat�qentOS, ]reeBS[  SunOS. $&    8.2.
% 8.=.  "   A& %+
#!/usr/bin/env python
import platform
 ;       !" Python  UNIX
281
           @7X  QX  -:
* Mac OS
* Ubuntu
* Red Hat/Cent OS
* FreeBSD
* SunOS
class OpSysType(object):
"""      -[email protected] - platform"""
def __getattr__(self, attr):
if attr == "osx":
 .  8 "  / 
@  #   , %     #  $  $%(
 ! (.
Red Vat:
[rootYlocalhost]/# python fingerprint.py
redhat
Ubuntu:
rootYubuntu:/# python fingerprint.py
ubuntu
Solaris 10  SunOS:
bash z.00# python fingerprint.py
SunOS
]reeBS[:
# python fingerprint.py
FreeBSD
&         ' & %       
  ,     #    
 &  % #   
   . |     #  $    #   ! 
    ,  
,  ,  '    #
 #    (   (     ( '   
  &  & #      !  $  
 .  $     % &       
  #$ &      !      
&   ' #  ,  #$  &    &
         & ssh  %.    %  
  '   #   (  ! (   #     
%  $#  .
+   SSJ ; K  NGS
  !    Python
$  $ 
 $      & !    $ #  ,  
(     $ (   nix, $ % &  
 #$  ssh  %,     ,       
N]S,    !     
    &$ Python.
$ #         # " , %    &  :
} 1:  $  #   % ssh    ,     & #
&     .
   : & $(  !   
    '     
% #&.      & 
 #             % 
      ssh.  $  %    &  
  8.3.
 ;       !" Python  UNIX
283
 %   ' :   #      $ 
 % &  #$  & root,  &   % &  
   &  $      %"  $  # % 
$#  #$  &, &     #   sudo
 $ #    &.
% 8.F. ?#"  +  ssh
[ngiftYMacintosh 6][H:11026][`:0]% ssh keygen t rsa
enerating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
our identification has been saved in /root/.ssh/id_rsa.
our public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
6c:2f:6e:f6:b^:b8:qd:1^:05:99:6^:26:1c:b9:^q:11 rootYlocalhost.localdomain
[ngiftYMacintosh 6][H:11026][`:0]%
} 2:    #   %      "
 $  # !
authorized_keys
,   $
   8.4.
% 8.G. 3   +  ssh
[ngiftYMacintosh 6][H:11026][`:0]% scp id_leop_lap.pub rootY10.0.1.51:/
.ssh/
rootY10.0.1.51s password:
id_leop_lap.pub
100% q0z 0.qB/s 00:00
[ngiftYMacintosh 6][H:1102^][`:0]% ssh rootY10.0.1.51
rootY10.0.1.51s password:
ast login: Sun Mar 2 06:26:10 2008
[rootYlocalhost]# cd .ssh
[rootYlocalhost]/.ssh# ll
total 8
rw r r 1 root root q0z Mar 2 06:z2 id_leop_lap.pub
rw r r 1 root root 20qq Feb 1q 05:zz known_hosts
[rootYlocalhost]/.ssh# cat id_leop_lap.pub� authoried_keys
[rootYlocalhost]/.ssh# exit
Connection to 10.0.1.51 closed.
[ngiftYMacintosh 6][H:11028][`:0]% ssh rootY10.0.1.51
ast login: Sun Mar 2 06:z2:22 2008 from 10.0.1.z
[rootYlocalhost]#
} 3:     #     N]S,  '  , 
    & $  #       .     
    #&   $ % &   #$  !  autofs
      $   %    .  ' 
  '  $  #       &  &,   
 #   %  $ ssh  & #  #   $  SN
       ( "(.    (
 .  8 "  / 
        #$  #   '    
 . ; ,     $    Red Vat  ' 
   #,  ,    :
 ;       !" Python  UNIX
285
$ & #   , %    #   #  
 ,   $ ' :
cmd = "mkdir /src"
:
cmd = "python /src/fingerprint.py"
 ' :
subprocess.call("scp fingerprint.py rootY%s:/src/" % machine, shell=True)
H     ,  # $  "  
fingerprint.py
, 
%        :
#!/usr/bin/env python
import subprocess
 -     ssh
machines = ["10.0.1.q0",
"10.0.1.50",
"10.0.1.51",
"10.0.1.60",
"10.0.1.80"]
cmd = "python /src/fingerprint.py"
for machine in machines:
subprocess.call("ssh rootY%s %s" % (machine, cmd), shell=True)
K  #   , %  % #:
[ngiftYMacintosh 6][H:1110^][`:0]# python dispatch.py
redhat
ubuntu
redhat
SunOS
FreeBSD
J &  
fingerprint.py
 $#   & &   %
" . J $  ,   #    "  &     
  #       ,   %     % 
&  $   (      #  . ;   &  
     ,      $    .
     ! 
    $
 "    #$  %  ssh          
   & $ #    %  ,   % 
 ' "& #      #$  #.       #
  % #   , ( ( &
       ,  $ 
 .  8 "  / 
      ,  &(     .   :
    ( "  & & '  ,     
=  & &   '  $    =   &
$ #     $ $=   '    
 & &   ( "(,  "   $ '    = "
&   '  ,      %    '
  . @  &:   (       
  ,    % # IP     ,    
'   #, $ !   !=   (   
!          
, %   '     #
  "=   (      &, 
 $  #    #(  (   &, %  
   #   .
 ( ' , %   (    #       
!   !  $   & "   $   & 
 . $&    8.6.
% 8.;. 3 A+& & "   A 
[MACHINES]
CENTOS: 10.0.1.q0
UBUNTU: 10.0.1.50
REDHAT: 10.0.1.51
SUN: 10.0.1.60
FREEBSD: 10.0.1.80
[COMMANDS]
FINERPRINT : python /src/fingerprint.py
@  #   (   # ! , &  %  #  
' !   !   & # $  MAqVINES
 qOMMAN[S, %   '   & # (  ( $   
%  ,   $    8.7.
  $  #, %  
$ !   !
      #&  %   & .   #" 
%    ' $ #&     ,  $ ' , 
 %"    #  #  &$ Python,  
 #  # !   !.
% 8.7. ]'+& A &  
#!/usr/bin/env python
import subprocess
import ConfigParser
 -     ssh
def readConfig(file="config.ini"):
"""
  IP    -   Q 
 ;       !" Python  UNIX
287
 7  
"""
ips = []
cmds = []
Config = ConfigParser.ConfigParser()
Config.read(file)
machines = Config.items("MACHINES")
commands = Config.items("COMMANDS")
for ip in machines:
ips.append(ip[1])
for cmd in commands:
cmds.append(cmd[1])
 .  8 "  / 
def readConfig(file="config.ini"):
"""
  IP    -   Q 
 7  
"""
ips = []
cmds = []
Config = ConfigParser.ConfigParser()
Config.read(file)
machines = Config.items("MACHINES")
commands = Config.items("COMMANDS")
for ip in machines:
ips.append(ip[1])
for cmd in commands:
cmds.append(cmd[1])
 ;       !" Python  UNIX
289
 &,     # $       #
&     #  %   $#  :
[ngiftYMacintosh 6][H:11296][`:0]# python threaded_dispatch.py
Main Thread aiting
Thread 1: Running python /src/fingerprint.py to 10.0.1.51
Thread 2: Running python /src/fingerprint.py to 10.0.1.q0
Thread 0: Running python /src/fingerprint.py to 10.0.1.50
Thread q: Running python /src/fingerprint.py to 10.0.1.60
Thread z: Running python /src/fingerprint.py to 10.0.1.80
redhat
redhat
ubuntu
SunOS
FreeBSD
Dispatch Completed in 1 seconds
   &  # &     
   ,  &  $    ,   %  
 :
[ngiftYMacintosh 6][H:11z05][`:0]# python advanced_dispatch1.py
redhat
redhat
ubuntu
SunOS
FreeBSD
Dispatch Completed in z seconds
)( & $  (  $#  ,  '  $ #, % "    %&
 & $#     $
  . {    #$ 
     &    ,  ' , $ 500 ",   $ 5,
$   $  #      $ #&      
  .   $  "    !       
 &   &   %  " ,        
 "   $     !        .
  $  #, % &  $    &,  $ '
 ,    %  "      #$    $
%    IPython.      &  #    
:
http:44ipython.scipy.org4moin4Parallel_Computing
     !     ' 
H ' $ ,   & #    '    #  "
,   & #       ,     
   & &  , ,   ,  $  #  #
    #   '    EPM,     
 $  #  $     $     
    .  %     ?  #     F H
 .  8 "  / 
 '   #$  #     , %   $  #   ! 
       .
  &   (    #( "    #  
 $  #  # " & (      & 
( UNIX (   (  ,  (  [ebian�Ubuntu,
Red Va�tqentOS, ]reeBS[  Solaris. @  #,  $     , 
  (    #          
"  ,        '  $  #   %  (,
 $ ' '       ,   & $   &,
 $  #  $    $ '      .
     #F         %#    $  #
         $  N]S     #  
  %    &        .     ,  #
$&    ,  $   
 ,    #       
      N]S. H  '    EPM  $ &  $  #
   ,    ! ,    ,    &
 #
fingerprint
,      ' '  $ .   # 
 #   ,   # , %   #.
;'  $ ,   ' & #     :
#!/usr/bin/env python
from fingerprint import fingerprint
from subprocess import call
os = fingerprint()
#  3    @  EPM
epm_keyword = {"ubuntu":"dpkg", "redhat":"rpm", "SunOS":"pkg", "osx":"osx"}
try:
epm_keyword[os]
except Exception, err:
print err
subprocess.call("epm f %s helloEPM hello_epm.list" %
platform_cmd,shell=True)
@  #  '     # !  !
config.ini
,  
       $     &.
[MACHINES]
CENTOS: 10.0.1.q0
UBUNTU: 10.0.1.50
REDHAT: 10.0.1.51
SUN: 10.0.1.60
FREEBSD: 10.0.1.80
[COMMANDS]
FINERPRINT = python /src/create_package.py
@  #   # # $  #    %      
         #  $  #   & qentOS, Ubuntu,
PyInotify
291
Red Vat, ]reeBS[  Solaris $ %    . |   
 #$&   #  % #  %    
  ,           " ,    
    , %  $ &  
 # &$ Python     ,
  $   #   % .
PyInotify
{   %  #   #   ! � GNULinux,  
      $ '   PyInotify.     
 :  # Python & ' & $    !    
 . !#&     (  &    
http:44pyino�
tify.sourceforge.net
   8.9  $ ,    #      .
% 8.9. ?A &  # -+%  %/ %" Pyinotify
import os
import sys
from pyinotify import atchManager, Notifier, ProcessEvent, EventsCodes
class PClose(ProcessEvent):
"""
++  +   
"""
def __init__(self, path):
self.path = path
self.file = file
def process_IN_COSE(self, event):
"""
++  +  'IN_COSE_*'
- - 3 Q@ ++ 
"""
path = self.path
if event.name:
self.file = "%s" % os.path.join(event.path, event.name)
else:
self.file = "%s" % event.path
print "%s Closed" % self.file
print "Performing pretend action on %s...." % self.file
import time
time.sleep(2)
print "%s has been processed" % self.file
class Controller(object):
def __init__(self, path='/tmp'):
self.path = path
def run(self):
self.pclose = PClose(self.path)
 .  8 "  / 
PC = self.pclose
#   3 3  K - + -
mask = EventsCodes.IN_COSE_RITE EventsCodes.IN_COSE_NORITE
# K - -        + -
wm = atchManager()
notifier = Notifier(wm, PC)
print 'monitoring of %s started' % self.path
added_flag = False
#   3  ++  3 + 
while True:
try:
if not added_flag:
#     Q + 3      -:
# ++  - +    @  -.
wm.add_watch(self.path, mask)
added_flag = True
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except eyboardInterrupt:
# ...  +   -+Q Ctrl C
print 'stop monitoring...'
#    3     + -
notifier.stop()
break
except Exception, err:
#  3   
print err
def main():
monitor = Controller()
monitor.run()
if __name__ == '__main__':
main()
{ $  #   ,  %  & #    
 &      %        
4tmp
. |  
'   #        ,  ! %    
 # %  #   $ ,  
,  # !     
$  &   &   (  .  # '  '  
 #$  # % #   
 $  Y ,  ,
&   %         &     & (
 & ! ,  (        &   
   ! 
fnmatch()
.   ,        $
 # Python,    #  Linux.
OS X
293
OS X && &  #  $ %         ,  
 $ #  #" .      ,    ,  ',  %
"  #$  #   !   qocoa,    ,    Leo
pard,  && &    # POSIX         
  UNIX.   OS X   #  #&  , %     # 
   $     (   UNIX:    UNIX
   #       &. 
& OS X Leopard  %   
& Python 2.5.1, Twisted   
 $ % #  
     &$ Python.
$ %    OS X     #      ,
 &           ,   %    
. &,  $  , & Apple       ,
 $ ' ,    $ #&   (%   =  ' $ #
   '  #           
  .   &  &            
      
     &    
&,   ' &    , ( ( & Apple,  (   $
 '  # $$    ,  $ '  #         
  L[AP,         .
  "   FSHLK   " %' 
;$ [SqL  (  [irectory Services qommand Line + 
 &    '    -    &       
         !  '      OS X.
[SqL  $ & %  #,  $  #
  & # $, % &$ Python
 $ &  #     $ .    8.10   
& $    [SqL    % IPython & % &   
' Open [irectory  ( $% .
   , %       # %   $
% &   ,  %  ' ,  #$& '  ,
 '   $  #  ( $   .
% 8.5.  # /#    & - 
WPython  %/ DSC[
In [q0]: import subprocess
In [q1]: p = subprocess.Popen("dscl . read /Users/ngift",
shell=True,stdout=subprocess.PIPE)
In [q2]: out = p.stdout.readlines()
In [qz]: for line in out:
line.strip().split()
Out[q6]: ['NFSHomeDirectory:', '/Users/ngift']
 .  8 "  / 
Out[q6]: ['Password:', '********']
Out[q6]: ['Picture:']
Out[q6]: ['/ibrary/User', 'Pictures/Flowers/Sunflower.tif']
Out[q6]: ['PrimaryroupID:', '20']
Out[q6]: ['RealName:', 'ngift']
Out[q6]: ['RecordName:', 'ngift']
Out[q6]: ['RecordType:', 'dsRecTypeStandard:Users']
Out[q6]: ['Uni~ueID:', '501']
Out[q6]: ['UserShell:', '/bin/sh']
| $ % # , %  Apple $    $   
  # %  $&
 %  $& L[AP�Ac
tive [irectory    #  
. D  
dscl
  
 '   $ (          & L[AP,
'      #$  Python $   . D     %
  , %  & #&    
 . @     , $ , %
  # &$  Python    
dscl
 ' % #   $ 
 #     %  $&    #  
$ (,    $ ( L[AP,    Open [irectory,   
    '   $ # ,  %    % #.
  "       !"  OS X
     OS X   (  $ #,  $ 
 # $    ! %    !    #$  &.  OS X
Leopard & &$  Python  Ruby   & &    ($
 Scripting Bridge.    #  !       (
$  #    
http:44developer.apple.com4documentation4
Cocoa4Conceptual4\ubyPythonCocoa4Wntroduction4Wntroduction.html
  , &   OSA, 
 Open Scripting Architecture + 
 & (    -,  '  #$  #  #
app
script
         
OS X
295
{ $  #    $      ,  (%    
      . |   '  ,   ' Mac OS X= 
       .
K  #  $& 
 #$   &
appscript
&  
 '   API $     &$ Python,     
     ' ,    % IPython. ;'      
 &  &  ,  %    (   
     ( $
 (      !  
 & :
In [q]: from appscript import app
In [5]: sysevents = app('System Events')
In [6]: processnames = sysevents.application_processes.name.get()
In [^]: processnames.sort(lambda x, y: cmp(x.lower(), y.lower()))
In [8]: print '\n'.join(processnames)
Activity Monitor
AirPort Base Station Agent
AppleSpell
Camino
DashboardClient
DashboardClient
Dock
Finder
Folder Actions Dispatcher
rowlHelperApp
rowlMenu
iCal
iTunesHelper
`avaApplicationStub
loginwindow
mdworker
PandoraBoy
Python
~uicklookd
Safari
Spotlight
System Events
SystemUIServer
Terminal
TextEdit
TextMate
{   &  " # $ %   $      
 '  OS X,  #
appscript
' & &   %  ( ,
      #  &$ Python  '  $  #    
&,     $ ' #  &$ Applescript. ; 
! +Noah Gift-    #,        $ &
 .  8 "  / 
  :
http:44www.macdevcenter.com4pub4a4mac4=5574564584using�
python��andapplescript�to�get�t�hemost�out��ofyour�mac.html
 %        '  & #    # ]inal
qut Pro,  $ &    , $  (,  ,
Adobe After Effects.    ,  OS X    # Applescript Studio
 '    $  # !%    !   $ # $    
  &$ Python  
shell
script
. H  $   ,
% #&  & qarbon qo
py qloner    App
lescript Studio. {    #     &,     $ 
 #&       ' .
*      
ASR       ,   "  &   
     , $  & OS X. |    && 
& %      % #  &         qar
bon qopy qloner  ' &   $  (  . ; 
+Noah-  #$    
asr
   Netboot &   %  
    & ! %          $  
      $   ,    .  #$     %
     $$ #   "   ' # " N,
%        ' $$    ,    $#    
  ,  "  &   ' &.
 ' ,   $     ,   %  
(    , %      . ;' ,    8.12
  &   &  &  & &   %     
  &  ,   '  # $   $$   
     $  '    .  %  $ &   ,  
 
4|sers
,       '$  '   , ' 
 #  %    ,       $ ,  ' 
(  #&   , %  %" .     8.12.
% 8.=. ?A & %   #"  
"   VS X, "%  & 0" +  %/
" # --  ZXPython
#!/usr/bin/env pythonw
# -          
import subprocess
import os
import sys
import time
from wx import PySimpleApp, ProgressDialog, PD_APP_MODA, PD_EAPSED_TIME
#-        -[email protected]    asr
asr = '/usr/sbin/asr source '
#  -  ,  7   
os_path = '/olumes/main
OS X
297
ipath = '/net/server/image.dmg '
dpath = ' target /olumes/main erase noprompt noverify '
reimage_cmd = "%s%s%s" % (asr,ipath, dpath)
#-   
reboot = 'reboot'
bless = '/usr/sbin/bless folder /olumes/main/System/ibrary/CoreServices
 .  8 "  / 
|     &    $  # $        
  WXPython     (    &. {  #  $
    '  "
,  & &    $  $ 
 '        #  
asr
,       & 
    &    ,  $ (   &  
, $    $  $% & $'     # 

bless
,   %   & &   $$  ".
|      '    #       &
    &   
   &  & &,  
 #    %   $  #     $%( $ ,
 &#  (        ' % 
&     '    .      ' ,  ,
$  #              
% &    #    &    OS X     
#      &       radmind. ;  +Noah-
 $       ,    %    
%    ' $   $    OS X,  $  $ "
     #(      # radmind.
{   # $   # $ #&       
OS X,         '  $  #&  radmind.
Radmind       
  %     &, 
& ' $  &  !        %  $
 '  #     & "     ( $  . Y  
# !  radmind     
http:44
rsug.itd.umich.edu4software4radmind4
. ;  &  , %  
radmind    &$ Pyth
on,    '     
 #    &$ .
   !" Plist     $ Python
  3   & $   !   !  XML,
       
system_profiler
,  #$& &    
 ElementTree. ;  OS X  Python     '   
plistlib
, &  $ & $  #   $  # ! Plist.
  # ' $ &
plistlib
. D    $ '    
    #   #   (,      $  #&
   '   & # .
*       Red Jat Linux
 Red Vat &$ Python  #$
& % # "   ,
       . ;  $     (  (
     #$ & Python  #   Emerging Technolo
gies:
http:44et.redhat.com4page4Uain_Page
. ;'   & 
 (  ,  #$( &$ Python:
Libvert API  $   '   #( "
    Ubuntu
299
irtInst  '   &  # "  
$   libvirt
,   &$ Python PyGT\
J  Python,  & $   (  
#( "    libvirt
qobbler   ,  $ &  $  #    #   $
     $$  & ' PXE   $
irt]actory:  &    &  #  ' 
]UNq +]edora Unified Network qontroller-
*      Ubuntu
H '  $ #, % $  (  (     Linux Ubuntu &
& &  $ (  (  Python. %   , %
H }   +Mark Shuttleworth-,  $  #   , 
 &  % 90      &$  Python.  $ $ 
% #(  %    
&$ Python & Ubuntu && &
Launchpad:
http:44launchpad.net
*       Solaris
  90( % 2000( 
   &   Solaris $
  %           UNIX.  %
2000(   Linux       $&  Solaris,  &$  % 
 Sun " #   #    #  &   . 
          #"  (     , $
 %         %    # Solaris.
)$     (    ,       
Sun,  ' $ # 6 &%      (    ,
 ' ,    Ubuntu,  18 &%    (%    
' = $  $ & ?       [[ 
 #$     q[,   Ubuntu. ;  ,  $  
     $ Red Vat  ]edora   $    Solaris,
$        . $ #  $ $ # $$ %
q[  '    :
http:44www.opensolaris.com
  $% &       ,  #$ 
&$ PythonF )   Sun    ,     &  #"
%    #   ( (
 , %& Z]S  $ %
&     L[OM,        ' 
 #   # " M
ware. ) & ' &$#   
 . )    Python         
libvert  libvirt  $  
%.  .
300
 .  8 "  / 
  Solaris  ' "  #$ &  $  
 &   &  .
   $
14   2007     & #
   $    
 Mware,            
  $  $     &  $ 
!  ( (  .   $       
   ,  
%  ( &( "
    & 
      (,   , Mi
crosoft Red Vat  Oracle,   & &   $  #   #   $  
$. H '    $ #, %       $&  
  # $    
  (     (  
   .  $&         &
"  %   #$ & !$  & (  &.
 $&      ' &  (   
  ,   ,      ,  $ &      #  
   ' &,  ,      , % $%  %
 '  #    &. @ 
#    "    
  '   # $   #   (  , $ #  
(  #&  ' & &   $   & % # %
 #    .  !!  
# (  &   #,    % 
 !!    && &$  #        
  .
 $ ' , &  %, % &     ,       #: 
 "     &$  PythonF        .
  Racemi,      ;  +Noah-,  &$ Python
       '   &     
  (,      $ . Python  '
   # % #  $
    ($  
$, %&  &  # "  $ %
&        
 !$%  ( "   # , 
 #$& &   Python API.     $    Python
%   &     ' 
   '  #, %   
 #       #            
   (.
 '    # " , & Mware && &    
$ (    $. ;%      
   &   #  "       " &.
 % #,      # API   : Perl, XMLRPq, Py
thon  q.      & 
(      $ Py
thon      % &,     '    
*! * * /
$  #&.  ( ' , %  Mware     
XMLRPq API.
 & Mware     # $%(     $
% API. )$   ,     '     #&
$    #,  ' $ #
Mware Site Recovery Manager,
Mware ESX Server, Mware
Server  Mware ]usion.
D     %   , %  (  #  $  &
   (  &,   #     (   $  
  ,    &  , %    # $ ( $    $
,    #   # Python.
'$ ' 
@ #  #  ( "(    $,     $
 "  %   ( +cloud computing-. @ 
%&   (  $% (     & 
% #(       ,  $    % 
 %  $ .  !  $ & (   %   
(     (
  Amazon  Google. J 
# $   #  #   %    $   
& Google $   &  .  &   '  
  " !" , &    ' & # &$ 
Python.   #      &  &$  Python,   ,
%  %   "   % .     
   %  ,  &$  Python,     
American Express.
   $     &     & API,  
   &    #&    Amazon   Google App
Engine.  $ %       ,    '  #&
 (     .
' %' Amazon    Boto
%  $ '  # &    !    %  
  ( Amazon   
&  !  Boto.     
Boto   % &     ',  Simple Storage Ser
vice, Simple Queue Service, Elastic qompute qloud, Mechanical Turk,
Simple[B. |   "     % #   API,    
     $& #  "    
http:44code.
google.com4p4boto4
.  #   '  %  #   ' 
! , % %" , %   
   ,  ( 
    .
;'   &     $  &  '  Sim
ple[B.
    ' :
302
 .  8 "  / 
In [1]: import boto
In [2]: sdb = boto.connect_sdb()
 $      :
In [z]: domain = sdb.create_domain('my_domain')
Y         :
In [q]: item = domain.new_item('item')
   &  API   &  &,  , %   % #
      ,   (  $& #       
$  svn:
http:44code.google.com4p4boto4source4browse
.  ,
% $%       $ %"(      & #,  
   &  .
Yoogle App Engine
' Google App Engine      &      &
?& &  " $ 
 .   $ &   
$  #  ' &  !   Google.  ' & App
Engine   API   # & Python,          
'    ' $  #&.  $    "(     
App Engine $ % &  , %       '
 Google.
    $ '    &       #"  %  $  ,
% (  #         (,     ,  
      $   (     . D 
$    #  '  Google App Engine  ' $ #& 
     :     GOOGLE APP ENGINE
 !"" (Kevin Gibbs)
   (%       Goo
gle App Engine.    & Google
2004  . Y    Google App Engine
 %  &       $ 
!    ,  $&  
  &  ,    &
      '  Google.  
  ,   && &    Google Suggest,   
  ,   %     (   $
       . Y   & Google  
       (    (   
IBM,  $&  $       $ % .
*! * * /
%        &       ,   
 #  $& #&   .
H           $   $ 
%  App Engine    ( , %    %  #  '
  #&  
   .     
$ %:
1.$   #"( ?   (:
http:44code.google.com4a�p
pengine4articles4bulkload.html
      % (  &     #  
 ?  (,       $   " #    
      '  $ Google App Engine.
2.  &   :
http:44code.google.com4appengine4articles4log�
ging.html
3.) !       % : ! &
send_mail_to_admin()
http:44code.google.com4appengine4docs4mail4functions.html
q %  $ &             
!    ' $ #&   $ & $   .
 %  & & '(  %     &  
       %   & #     
 '    &       % .
4.     %  ( $ %    #    $ 
 cron.
|  && &        % # Google App Engine,  
    #$  #  
$  cron   (   
( &   % $      ' & %  $   
     . ; ,
 '   !  # $ 
 &   ,     '  %   
 #& $     
http:44yourapp.com4emailsummary
,   
$#             #&
        %     '(   ,  
$ " "(  %      %.
5.D   &:
http:44code.google.com4appengine4docs4conf�i
guringa napp.html\equired_Elements
 $ &$ #(   , $ & ( & "   ' 
&,   !    . '  $,   ' &
 '    '   !     ,  $  &  
   . )$ &&   !    ,   
%  $ '  #  #   #    ' &    
 #        #,  & $   '
  #  %    .
       %
$ $ Yoogle App Engine
 ' %    #  $   ' & & Google App En
gine,     & $$ #  S[\ & Google App Engine:
304
 .  8 "  / 
http:44code.google.com4appengine4downloads.html
.   '  '
$  #&  $ % # %        Google App
Engine:
http:44code.google.com4appengine4docs4gettingstarted4
   $        %      & Goo
gle App Engine,   $ % # %      '  
  . {        
http:44greedycoin.appspot.com4
,
 '    #      ' &,  
 & ' ,   '  $  #&         ( (
 .  '   ,    #$   ,  
(&  $ (  $   $       
       .  '    '  ' &
 $ '  #         API   !    $ '
  #  % & !    ( $ (. )(  
 ' &   &    8.13.
% 8.F. 2-&#x-6.8;÷.6;&#x. 2;&#x--5.;+  reedy Coin
#!/usr/bin/env python2.5
#Noah ift
import decimal
import wsgiref.handlers
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
class ChangeModel(db.Model):
user = db.UserProperty()
input = db.IntegerProperty()
*! * * /
class Recent(webapp.Re~uestHandler):
"""    -Q  10  X X"""
def get(self):
# Q
collection = []
# 3 10  X    X7 X
~uery = ChangeModel.all().order(' date')
records = ~uery.fetch(limit=10)
# -  3 +  
for change in records:
collection.append(decimal.Decimal(change.input)/100)
template_values = {
'inputs': collection,
'records': records,
}
path = os.path.join(os.path.dirname(__file__), '~uery.html')
self.response.out.write(template.render(path,template_values))
class Result(webapp.Re~uestHandler):
"""G7  Q   3  -"""
def __init__(self):
self.coins = [1,5,10,25]
self.coin_lookup = {25: "~uarters", 10: "dimes", 5: "nickels",
1: "pennies"}
def get(self):
#    3   
collection = {}
#+ 3     X7 X
change = db.~luery(
"SEECT * FROM ChangeModel ORDER B date DESC IMIT 1")
for c in change:
change_input = c.input
# -  -- - -
coin = self.coins.pop()
num, rem = divmod(change_input, coin)
if num:
collection[self.coin_lookup[coin]] = num
while rem� 0:
coin = self.coins.pop()
num, rem = divmod(rem, coin)
if num:
collection[self.coin_lookup[coin]] = num
template_values = {
'collection': collection,
'input': decimal.Decimal(change_input)/100,
}
306
 .  8 "  / 
#+  + 
path = os.path.join(os.path.dirname(__file__), 'result.html')
self.response.out.write(template.render(path, template_values))
class Change(webapp.Re~uestHandler):
def post(self):
"""-    3  """
model = ChangeModel()
try:
*! * * /
class MainPage(webapp.Re~uestHandler):
"""  Q"""
def get(self):
308
 .  8 "  / 
   #         '   $  #   #$  #
(  . ;'   & ,     #$ &
Python API &  % & ( $ (  ' & 10  
 (  $#  :
class Recent(webapp.Re~uestHandler):
"""    -Q  10  X X"""
def get(self):
# Q
collection = []
# 3 10  X    X7 X
~uery = ChangeModel.all().order(' date')
records = ~uery.fetch(limit=10)
# -  3 +  
for change in records:
collection.append(decimal.Decimal(change.input)/100)
template_values = {
'inputs': collection,
'records': records,
}
path = os.path.join(os.path.dirname(__file__), '~uery.html')
self.response.out.write(template.render(path,template_values))
 '    $ #:
~uery = ChangeModel.all().order(' date')
#$" Zenoss !   !     Windows " Linux
;    $ %  " 
 %       Google
App Engine,  '   #       
,   '    $  #        &
'       &.
{      $
 #&    (  ' ,  '  '  $ 
 #&  (     ' & Google App Engine, 
        +Guido van Rossum-:
http:44code.
 .  8 "  / 
 .     #$ &      &   
 $ :
wmic U username%password //SERER_IP_ADDRESS_OR_HOSTNAME "some MI ~uery"
       & &        ,  
IP  
192.168.1.z
,      #$  &
Administrator
,   $ 
 & $    %  $  $ '   :
wmic U Administrator%password //192.168.1.z "SEECT * FROM inz2_NTogEvent"
K '   & % #  $#  ,  % (  (   &
   :
CASS: inz2_NTogEvent
CategoryCategoryStringComputerNameDataEventCodeEventIdentifier
EventTypeInsertionStringsogfileMessageRecordNumberSourceName
TimeeneratedTimerittenTypeUser
zDCOM20080z200zqzq1.00000000020080z200zqzq1.000000000Information(null)
0(null)MACHINENAMENU600521q^q8965zz(,,,,1q,0,0 )SystemThe Event log
service was started.
2Eventog20080z200zqzq1.00000000020080z200zqzq1.000000000Information
(null)0(null)MACHINENAMENU600921q^q8965^z(5.02.,z^90,Service Pack
2,Uniprocessor Free)SystemMicrosoft (R) indows (R) 5.02. z^90 Service Pack 2
Uniprocessor Free.
1Eventog20080z200zqzq1.00000000020080z200zqzq1.000000000Information
(null)
   #  % $  $  &  &$ Python,
%  (     # 
'  . Y&   ,  (
' ,   #$    Zenoss 2.1.3 Mware.    
  % #     Zenoss   &  "  
   #$  &
enoss
.   ' $ % &  , % 
 #  #   
,  (  &  #
wmiclient.py
,    
  ' &
PTHONPATH
. H   #     %
'         
PTHONPATH
,   $ ' :
export PTHONPATH=/Products/Zenin:$PTHONPATH
  %  $ '  #    (   ,  '
    # $  #  , (       
& ' :
#!/usr/bin/env python
from wmiclient import MI
if __name__ == '__main__':
w = MI('winserver', '192.168.1.z', 'Administrator', passwd='foo')
w.connect()
~ = w.~uery('SEECT * FROM inz2_NTogEvent')
for l in ~:
#$" Zenoss !   !     Windows " Linux
311
print "l.timewritten::", l.timewritten
print "l.message::", l.message
   %    # $% &
 (   ,      
      
wmic
,      #  &  
  & $ '. Y    & &     
192.168.1.z
  &  #$  &
Administrator
    
foo
    & $  WMI
'SEECT
FROM
inz2_NTogEvent'
.  
   $  & (  % (  $#       
     & & '  $. @    # % 
    , %    .
;'   & % #  ,  %      &:
l.timewritten:: 20080z200zqz59.000000000
l.message:: hile validating that \Device\Serial1 was really a serial port,
 .  8 "  / 
   $#   
   
  
D    && &   $   '(   &
(  "    &      % &. D 
    $  %
 $     
&(, $(&       ,  (  Amazon. {
    ,  &
(   ,     
   Amazon     $ '. @ %  ' , 
    ,  %   !  #     &
  &        &$ ,  $   
    % &     #&     
% &.
     &   
,  $ ' ,   , % 
   ,   (
.rpm
  
yum
  (
.deb
 
apt
,   ( (  (  &  
  &      . H       
 ,    "       $    
       &$ Py
thon   ' & &$  Py
thon.   #$  Python
    #  $ '  #   
% #        &$ Python &    .
   ,    & #   #  ,    #
" %"   #,         $ &     
&  &$ Python,  &      &.
 =. '     
Y     $  & &$   $     $(
     %  (  #
  %(  #$   .   
( %&(     "   $(  ( , ( &  (
 &  %   .          #   
  &     EPM,       $  # 
 &  !  AIX, [ebian�Ubuntu, ]reeBS[, VPUX, IRIX, Mac
OS X, NetBS[, OpenBS[, Red Vat, Slackware, Solaris  Tru64 Unix.
    & 
  (   # $
 %       %
&. |   "   ( 
     . ;
       
   && &  %   ,     $ & $ %
 &  .     "(     & 
 & &$  Python  & $%(   (   &
& &  $       #      #    .
 #   & #&, % &    '    .  
 ,   !   ,   $    $ #,  '
      
http:44wiki.python.org4moin4buildout4pycon=558_
tutorial
Setuptools  Python Eggs
#$" easy_install
DevCenter4setuptools

http:44peak.telecommunity.com4DevCenter4Easy�
,      .
 '    ,     #   #  , %
  '  & #. )  
setuptools
 '  & # % 
 , %     
 #  .    #  
$ ,   '   #       ,
   $%         %  $ '  #
 =. '     
#$" easy_install
Package Index      Python-,  qheesshop:
http:44py�
pi.python.org4pypi
    # IPython,   % , &  #$ & & 
        &'    ,  '   $
  #    :
sudo easy_install ipython
   , % &   &      
easy_install
     %     #$  &,
      &
  # & Python   
site�packages
.   '         ,   %
 $%         &   , 
% && &    ,  (  &  &  !
python
Y&          #
easy_install
 (    #
   $#    
site�packages
    ,      
  Python. {    $ $   &,   # $ 
 ,  '  &  #$  virtualenv  setuptools. 
 ,  '      #     # Python   
      :  ,    "   .
 ' %       $%    #(  $ '  
   
easy_install
,          
 #$ &
easy_install
1.$ #   %#     
     : EASY INSTALL
# $. %" (Phillip J. Eby)
* Y'. |  % $   Python En
hancement Proposals +      ' 
  %"  Python-,  '     
WSGI +Web Server Gateway Interface  ! 
$  &      -, setuptools   
  .    $ #   [ream
ing in qode +Three Rivers Press-.   '   
 #   ,  &    :
http:44dirtsim�
ple.org4programming4
 =. '     
   '  easy_install
Y&  #"  (,  #$ &   
easy_install
,  
  % $ #              
,  $   #(   .
+    $ #,   #$ 

easy_install
           , 
    $$    
  ,   $   
      IPython.- @     ,     %, 
    (    #  $ '   &   &  
#(  ,   $$    $ Python Package Index.
 % #,
easy_install
  $   # #(  " 
      %     #, %     #  
     #(  $ '  .
    '   
   $  ,
easy_install
 '   #     
#    $     %     # (. ;  
     $ '  #   #    
  ,  #  '      #. ;'   &
   ,    #   
        
 #    #          :
$ easy_install f http://code.google.com/p/liten/ liten
Searching for liten
Reading http://code.google.com/p/liten/
Best match: liten 0.1.z
Downloading http://liten.googlecode.com/files/liten 0.1.z py2.q.egg
[+ ]
       
http:44code.google.com4p4liten4
 
& 
.egg
& Python 2.4  Python 2.5. %
 &
easy_in
stall
 &     ,    &   #  .  
            & Python 2.4,  
     . Y   % %   , %  % #  &
    #,  
easy_install
 #       ,
  '    ( &  .
   '   
    URL
@  #        %      #     ( 
    $       URL:
 $ *  easy_install
319
 =. '     
....
Best match: CherryPy 2.2.1
Downloading http://download.cherrypy.org/cherrypy/2.2.1/CherryPy 2.2.1.tar.g
....
Processing dependencies for cherrypy==2.2.1
Finished processing dependencies for cherrypy==2.2.1
@  #   , %  $  ,    ' #  
easy_in
stall
   #&    #  ,  '     :
$ easy_install cherrypy
Searching for cherrypy
Best match: CherryPy 2.2.1
Processing CherryPy 2.2.1 py2.5.egg
CherryPy 2.2.1 is already the active version in easy install.pth
Using /Users/jmjones/python/cherrypy/lib/python2.5/site packages/CherryPy
2.2.1 py2.5.egg
Processing dependencies for cherrypy
Finished processing dependencies for cherrypy
              '   #   
  '   , &  $,     ' $$ #  
  #:
$ easy_install cherrypy==2.z.0 Searching for
cherrypy==2.z.0
Reading http://pypi.python.org/simple/cherrypy/
....
Best match: CherryPy 2.z.0
Downloading http://download.cherrypy.org/cherrypy/2.z.0/CherryPy 2.z.0.ip
....
Processing dependencies for cherrypy==2.z.0
Finished processing dependencies for cherrypy==2.z.0
   :         #$  %
upgrade
.    #    %  ( , #   
'      &  &     (    # 
       .
Y   &     qherryPy 3.0.0,  #$& %
upgrade
.    %  #$  # %
upgrade
   
"   &$ # :
$ easy_install upgrade cherrypy==z.0.0
Searching for cherrypy==z.0.0
Reading http://pypi.python.org/simple/cherrypy/
....
Best match: CherryPy z.0.0
Downloading http://download.cherrypy.org/cherrypy/z.0.0/CherryPy z.0.0.ip
....
Processing dependencies for cherrypy==z.0.0
Finished processing dependencies for cherrypy==z.0.0
 $ *  easy_install
321
{  #$  # %
upgrade
,   $&     ,   
              .   
 :        % % &  & 

easy_install
cherrypy
.   
easy_install
cherrypy
' , %
 '       &  &        
(     #   .        
$       qherry
Py        :
$ easy_install upgrade cherrypy
Searching for cherrypy
Reading http://pypi.python.org/simple/cherrypy/
....
 =. '     
  &       -,  %   
$ #, % (        .    %
easy_install
# "#   ! $ 
  . {     &
   #  ,  '  $  #  
easy_install
 $.
+   "  
        &, %   '     
liten
  0.1.3           & &  &
liten
.    ,    &, %    && &   
&  &. ;'  $ ,   '    #  :
easy_install liten=0.1.z
|       %   (   #$     
   ,    %  $          .
'     !" .py   .egg
;'  $ ,   $  # %  Python  
.egg
+     %
easy_install f "http://svn.colorstudy.com/virtualenv/
trunk/virtualenv.py#egg=virtualenv 1.0" virtualenv
|     &,   
(    #   
!
.py
 
.egg
. )      ' $ #& %"  
  ,    (    % #      
#  ! $   %  !    .   ,
 '    #  #     !      
' &
PTHONPATH
.        %  $      
   
virtualenv.py
,       $  "
          .    URL    
#egg=vir
tualenv
1.0
   & &        , 
 &    &. K  ,    $    URL,
 & &  $     .      '  # 
 #$  #  ,      %    URL,  
%    
easy_install
   #    '   ,
%   $ . Y'  , %   '  #  $ #
    %  ,  
' %   #  & &$
 (& # $         $   &. ;
 :
easy_install f "http://svn.colorstudy.com/virtualenv/
trunk/virtualenv.py#egg=foofoo 1.0" foofoo
|      %   '  , %      ,
#    %  $  &      foofoo,   virtualenv.
 &    &  
     # "  .
 $ *  easy_install
* !  $  "K     
: : 
    '  $  #  &,       &  
  # 
.egg
   ,    
&      ! ,
 ' %   $ "  $' #       !.  
 %  '  $ # &  #$  &   # &   
URL,   $ ' :
easy_install f http://uid:passwdYexample.com/packages
  ' $ #&          ,  
 (  # , %  "   $  . +$   $
 &  F-  $        #       $
  $ % &  , %   $  #    !
.htaccess
 $
  & #      !    
easy_install
+   !    !"
Y&  (  #$      
easy_install
 &  
 . % &      %  ' $  #    #
!   !,   !  ini! . Y&
        
   %&  $ '  #, 
  $ &  & #       ,  #$(  
easy_install
.   !     #&  
 
easy_install
  ( !(       & :
&_ -&_ 4setup.cfg
~4.pydistutils.cfg
  !
dist�u
tils.cfg
,       distutils.
 '  #   !  !F % $ #
 & &   :  +
-   #   ,    '
$' #  ,      
        . ;'
 $ ,   ' & # ! ! &
easy_install
[easy_install]
#  3  
find_links = http://code.example.com/downloads
# 3 -   K - - -
allow_hosts = *.example.com
#   3  . +  - : K     
#X 3  PTHONPATH
install_dir = /src/lib/python
   !   ! ,      $ #, 
 ,
~4.pydistutils.cfg
,  & &    URL &     
, $ " &   #   #   
example.com
+   
 (- ,   ,
 $ &,   '
    #&  
    .
 =. '     
#      ' $ easy_install
| $    ' ' # $    ?   !# 
       &
easy_install
,   #   &
"#  , %   $% #         , 
    #$  #& 
  #$  &.  
easy_install
 '   $  #&,      
" %  #&   
http:44peak.telecommunity.com4
DevCenter4EasyWnstall
$   &    .    ,
    % &  ,  
$ & distutilssig + sig  
(  special interest group       -, 
'  &    , &$
       
  .  " #       
http:44mail.python.org4
mailman4listinfo4distuti�lssig
,    '   #     &
 ' ( " (   % #   #, &  #
$ &
easy_install
;  ,    
easy_install
help
,  ' 
 #" %   , (  '    $ #.
 #   &  , %  &     #, &   ( 
, '  $  
easy_install
   
  '  , %    "  
.egg
  
    &$ Python,   
   &   %
" , %   . ;'   &      egg, $&   
    setuptools:
   ! 
.egg
   %  #  % !  
    & EasyInstall,   % && &   ! 
  + &     &  % #  &$ Python-,
      #&         '   
 ,  %&    !  $  &(  .
     $' #&  & #&  $%    
sys.path     #&    ,
 '  &  sys.path,
  %     %     ' #&   
 &     &   &.
H    %,        
    # $      $   . { " & #
  # % &  $    $ (   ,   $&
 ' &       $. ;    %  & #
 "   $ %,  ' , %       $
 ' #  (  &   . {   $     #"  
   ,  $% ( &  " &   %   
%(& $ %,   ' !  #    . K  
   ,   #
    &    
)"  
  ,   %      (        #
( "(.
 $    Python   &    % $%   
  ,   & $ %  (   :
 =. '     
copying Helloorld.egg info/P INFO � build/bdist.macosx 10.5 iz86/egg/
E INFO
copying Helloorld.egg info/SOURCES.txt � build/bdist.macosx 10.5 iz86/egg/
E INFO
copying Helloorld.egg info/dependency_links.txt � build/bdist.macosx 10.5
iz86/egg/E INFO
copying Helloorld.egg info/top_level.txt � build/bdist.macosx 10.5 iz86/
egg/E INFO
)"  
 =. '     
creating build/bdist.linux x86_6q
creating build/bdist.linux x86_6q/egg
creating build/bdist.linux x86_6q/egg/E INFO
copying symlinkator.egg info/P INF�O build/bdist.linux x86_6q/egg/E
INFO
copying symlinkator.egg info/SOURCES.t�xt build/bdist.linux x86_6q/egg/
E INFO
copying symlinkator.egg info/dependency_links.tx�t build/bdist.linux
x86_6q/egg/E INFO
copying symlinkator.egg info/top_level.tx�t build/bdist.linux x86_6q/egg/
E INFO
+ /     
329
     
 =. '     
 %  (  &$   #   %  '(  , 
  (      % $
 #, % %  (   #$ &
&     "(   , (  #     
     ,    ,   &  #$  &. Y&  
  (    #   
,   " ,   
 # ! , & ' $ #& "     
     .
=   $   Python Package Index
{  "   #   $  #,      
 , %  $(    #&     #. |  $ 
( & (     $        % 
&.  % #, $ #  
Python Package Index +    
 Python-      ' .
|    "#    % &     $ &  .
       # 
   :  $ #  % #
  !  ReST +reStructuredText-   
long_description
    # $% 
download_url
. !  ReST  '  
   4.
;  &  , % !  ReST ' ' &  ,  '
$ #  %   #, %    !   ReST & !  & 
    (   , %    $   ! 
VTML   $     Python Package Index.   '  
 #$  #&     ReSTless,  $  K    
  +Aaron Villegass-, &   #     !   
   , %    #&, %  !    ' 
$ . &$ #      , %    #&  
   "  !   &
. {    '
$  !     !  ReST,   $   &
  ' #&  %  ,    VTML.
   9.2   &  ' !
setup.py
&   
         ,  $   ;  +Noah-.
-  !    Python Package Index
import os,sys
version = '0.1.q.2'
f = open(os.path.join(os.path.dirname(__file__), 'docs', 'index.txt'))
long_description = f.read().strip()
f.close()
 =. '     
K 
download_url
   ' $%  ,   %   
  
easy_install
,    # "  .    '  
% #     ,     
easy_install
  & #
      (       ! 
.egg
,   '  '  $ # &     .
  
long_description
$ &     , 
 ( &   $    !
index.txt
    
*
index.txt
 '   !  ReST,   
setup.py
         Python Package Index %    
!        
long_description
D  %    ; !  ;
;'   &   # '(   :
Easy install
http:44peak.telecommunity.com4DevCenter4EasyWnstall
 + Python   % .egg
http:44peak.telecommunity.com4DevCenter4PythonEggs
"/ setuptools
http:44peak.telecommunity.com4DevCenter4setuptools
"/ pkg_resources
http:44peak.telecommunity.com4DevCenter4Pkg\esources
-#  0  + %" pkg_resources   % Python egg  -�
0  0
-#  0  + %" pkg_resources   % Python egg
-0  0
)  $ #   %     &$  Python
http:44mail.py�
thon.org4pipermail4distutilssig4
Fistutils
     &  (   
  setuptools % &  
 %  #      $ &     &     ( 
Distutils
  #      ,  # !
setup.py
         !
setup.py
   #     (   
 $   %(  ,  ,  !  rpm & Red Vat,
pkgtool & Solaris  swinstall & VPUX
/%"         #,     distutils,
   #       #&.
} 1:  $  #     .   #$ &  
   ,          ,  
$  #      :
#!/usr/bin/env python
#A simple python script we will package
#Distutils Example. ersion 0.1
class DistutilsClass(object):
"""     -Q@  --  + ."""
def __init__(self):
print "Hello, I am a distutils distributed script." \
"All I do is print this message."
if __name__ == '__main__':
DistutilsClass()
} 2:  $  # !
setup.py
       .
#Installer for distutils example script
from distutils.core import setup
 =. '     
python setup.py sdist
 '  % #    :
running sdist
warning: sdist: manifest template 'MANIFEST.in' does not exist
(using default file list)
writing manifest file 'MANIFEST'
creating distutils_example 0.1
making hard links in distutils_example 0.1...
hard linking README.txt distutils_example 0.1
hard linking setup.py distutils_example 0.1
creating dist
tar cf dist/distutils_example 0.1.tar distutils_example 0.1
gip f9 dist/distutils_example 0.1.tar
removing 'distutils_example 0.1' (and everything under it)
@  #  , %  (    # &        , 
  #     #  :
python setup.py install
;'  & &   #  
,   & &,   $
   (   #  $  # 
  %  !  .  
 , %       &$         
,       '   #   !  rpm,  ,
       OS X.  , % & $    
 $,   '  # &   #"     . Y 
 % ( #      #  #( ", 
 '     #$  #& &     .
   #  rpm:
python setup.py bdist_rpm
   #   !  pkgtool & Solaris:
python setup.py bdist_pkgtool
   #   !  swinstall & VPUX:
python setup.py bdist_sdux
;  ,     &
&  %    , 
 '    #   ,  '  (  #   . %
   &     
 & &     ,  
 '  # &        ,   $ ' :
python setup.py build build base=/mnt/python_src/ascript.py
    $   
install
,     , % (  &
   
- ,
   
 
.   %     
         
si�tepackages
        
   Python,        & & 
Buildout
,    '  $ #     
 
,  ,   
     N]S,     " .
Buildout
)   Buildout   $  Y'  *   +`im ]ulton- $
  Zope qorporation   $%  &     ( 
 ' . |   ' &    #    &$ Py
thon    ,  
 Apache.  $  (  
  Buildout     , %    % #  $ '  #    
 '   $(  ! (.  $  (     ,
         # Buildout,       $
     Plone 3.x.  (     &, %    
"#  "  .
Buildout   $     (  (    
 &  ,   '   ' # Python,   
 $ &  '  ' &   ' $  & $
   # (  &,        & !
bootstrap.py
 !     .   ( $ (    " 
'    % :  #$  Buildout  $     
  Buildout. H  '        %  #   
   Buildout    :
http:44pypi.python.org4pypi4zc.buildout
         '   ' ! 
Buildout. |    &  #  &,  #   $
 ' ,  &$ # '   %  # '   #$  #
Buildout.
+   Buildout
;  &  , %   ,     (  & Zope, $
    Buildout,    #   &  #  % 
 #$    Python. Buildout        ($ $
  & Plone. Y& (,  $   Plone:    
     : BUILDOUT
$& '* (Jim Fulton)
Y' *   $  #   $ %     Zope Object
[atabase. Y'  ' && &  $  $    Zope Object
Publishing Environment  (%      Zope qorpo
ration.
 =. '     
 &  ' &    &  & &, $    
      $ % .   Plone  % $%
 '     ,     &
&    Buildout. @  #
 & Buildout     Plon
e  & & #   .
H  '   $  , % Buildout  '  #$  # '
&  & '   Python. Buildout   #   
#     %  ,     &     :
  &&  &
bootstrap.py
. $ #     '    
http:44svn.zope.org4checkout4zc.buildout4trunk4bootstrap4bootst�
rap.py
*
buildout.cfg
     &    .
/%"         #  $ '   Buildout   
 , %     # %  #     #. ;  +Noah- 
          &   &    ! ,
  '      #    $  Python, PyPI. H
       # Buildout $  #   Python & $ 
     .
} 1: $ #   buildout.py:
mkdir p /src/buildout_demo
curl http://svn.ope.org/*checkout*/c.buildout/trunk/
bootstrap/bootstrap.py� /src/buildout_demo/bootstrap.py
} 2:  #    !
buildout.cfg
.  '    # " ,
Buildout   &     !
buildout.cfg
. {    #&
$  #  
buildout.py
 $ !
buildout.cfg
,   % 
     :
$ python bootstrap.py
hile:
Initialiing.
Error: Couldn't open /Users/ngift/src/buildout_demo/buildout.cfg
Y&    $   !  !,   $  
  9.3.
% 9.F. %  A & Buildout
[buildout]
parts = mypython
[mypython]
recipe = c.recipe.egg
interpreter = mypython
eggs = liten
{  ( #  !    
buildout.cfg
 $    $
 #  
buildout.py
,   %   ,   $  
  9.4.
#$" Buildout
% 9.G. ?#"   buildout
$ python bootstrap.py
Creating directory '/Users/ngift/src/buildout_demo/bin'.
Creating directory '/Users/ngift/src/buildout_demo/parts'.
Creating directory '/Users/ngift/src/buildout_demo/eggs'.
Creating directory '/Users/ngift/src/buildout_demo/develop eggs'.
enerated script '/Users/ngift/src/buildout_demo/bin/buildout'.
{ $& #     #  $    ,     & 
  ,  %& #     Python    
$ ls l bin
total 2q
rwxr xr x 1 ngift staff z62 Mar q 22:1^ buildout
rwxr xr x 1 ngift staff 651 Mar q 22:2z mypython
@  #,               Buildout,  '
 $  #    ,      ,   
 #,   $    9.5.
% 9.6. 1 Buildout     
$ bin/buildout
 =. '     
A command line tool for detecting duplicates using md5 checksums.
Options:
version show program's version number and exit
h, help show this help message and exit
c, config Path to read in config file
s SIZE, sie=SIZE File Sie Example: 10bytes, 10B, 10MB,10B,10TB, or
plain number defaults to MB (1 = 1MB)
~, ~uiet Suppresses all STDOUT.
r REPORT, report=REPORT
Path to store duplication report. Default CD
t, test Runs doctest.
$ pwd
/Users/ngift/src/buildout_demo
| % #     &   ,
  ,   ' 
 #$  # Buildout &  $ & $         % 
  $   #   (  $         
. @     , %       #    # Build
out,   (    #         .
Buildout       
     ,    
 & &,   '  $  %  !
buildout.cfg
  
 (   . | $% , %    #  egg $ 
 ,                 
 ,   $    9.6.
% 9.;. ]" #& #  A & Buildout
[buildout]
parts =
;'   &  $#      $  Buildout     
&        $
 .    , %
Buildout  &  '              
  %   $ %
,    "#  !
$   !. % ,  '    $ Buildout   
     #    .
$ bin/buildout N
Uninstalling mypython.
{  # $& #    
,  '    #&, % 
             % $. {    ,
%   #   ,            Buildout:
$ ls l bin/
total 8
rwxr xr x 1 ngift staff z62 Mar q 22:1^ buildout
 ,  $& #    
eggs
,  '  #, %   
  ,     . H   ' 
$  #  ,     
     :
-" *  $" Buildout
$ ls l eggs
total 6q0
drwxr xr x ^ ngift staff 2z8 Mar q 22:5q liten 0.1.z py2.5.egg
340
 =. '     
 $  #  #  , $        Py
thon. )   virtualenv   & %      
  #      ,    && &,     $ &
 $  #    , % %     # $    
#    
site�packages
)   virtualenv  '  ' $   #  #
 ,  $ && $ %   & # #    
.       % #   Buildout,   
%       #$
  ! 
!.   $  #, %     , Buildout  virtualenv,
% # "  #$   setuptools,    '   
    &  & $ & * Y'. | +Phillip `. Eby-.
@  '  #$  #&     virtualenvF    
      #     #
easy_install
sudo easy_install virtualenv
{    #$  # virtualenv #      
Python,    (      &. {      
   #   Python,  , Python 2.4, Python 2.5, Python
2.6 ,  $ ' , Python 3000,  
         
'   
,   
4usr4bin
,   %" 
 #$  #
   ( ,   #     '     '    #
#    virtualenv.
 $      % #   #    virtualenv,  
(  $  & Python,     , %    $
$ #      virtualenv   $  #    & ' 
  Python. ;'  &,     #:
1.curl
http:44svn.colorstudy.com4virtualenv4trunk4virtualenv.py virtu�
alenv.py
2.sudo cp
virtualenv.py 4usr4local4bin4virtualenv.py
     : VIRTUALENV
+ , (Ian Bicking)
^ J   % $  %    
Python, %  %   '   # $
 . )    Webob, &&&
% # Google App Engine, Paste, virtualenv, SQL
Object    
 .   '   
 #       :
http:44blog.ianbicking.org4
virtualenv
3. $  #           % Bash  zsh:
alias virtualenv py2q="/usr/bin/python2.q /usr/local/bin/virtualenv.py"
alias virtualenv py25="/usr/bin/python2.5 /usr/local/bin/virtualenv.py"
alias virtualenv py26="/usr/bin/python2.6 /usr/local/bin/virtualenv.py"
 $       #   &,  '  #& #"
 $  #   #     vi
rtualenv,    & ' 
  Python,      &. ;'  $ ,   
 &.
 $   #    Python 2.4:
$ virtualenv py2q /tmp/sandbox/py2qEN
New python executable in /tmp/sandbox/py2qEN/bin/python
342
 =. '     
)  '  #$  #  
activate
, ( &&    
     #   , %     #      $
      . |   #   ,    '
 #$  #,    && & &$ #,        
'       #      #   . Y 
 +[oug Vellmann-,  $   $     ,   
   ,      :
http:44www.doughellmann.com
4projects4virtualenvwrapper4
.   #$  
activate
  
 &$ Bash,   $ &  #,  &   '  #
$ .
   '     % "
 & virtualenv 1.0, &        &
  ,  %  '   $ &    $  &
   (  #( ' . Y  #&    '    
# ! 
virtualenv.create_bootstrap_script(text)
. |  ! &
 $    $  &,        
 virtualenv,    "   $ '  & 
$       # ! ,  & (  #$   ,
extend_parser()

adjust_options()
,   $ &  & #  &  
        # ! 
after_install()
Y   ,  #    $  #      
$  &,     virualenv  $     
     .  $#  & #  %      liten. H
 '     # virtualenv  $  #   "     #
      #    liten.    9.7  $ ,   $
 &  & $  &       #   , 
    liten.
% 9.7. % A , # +   /  "
import virtualenv, textwrap
output = virtualenv.create_bootstrap_script(textwrap.dedent("""
import os, subprocess
def after_install(options, home_dir):
virtualenv
"""))
f = open('liten bootstrap.py', 'w').write(output)
 (  (,        ! 
after_install()

  # $#    !    
lite�nbootstrap.py
,   ' 
     %     ,  $     #
easy_install
 
  #  # liten. '   #, %  !    
  $  !
bootstrap.py
,  $    #$  #&
 $ .   $     &   % !
bootstrap.py
,     '    # $ %    %
   #$  .
{ $  #  
liten
bootstrap.py
 $   ,   
 %     :
$ python liten bootstrap.py
ou must provide a DEST_DIR
Usage: liten bootstrap.py [OPTIONS] DEST_DIR
Options:
version show program's version number and exit
h, help show this help message and exit
v, verbose Increase verbosity
~, ~uiet Decrease verbosity
clear Clear out the non root install and start from scratch
no site packages Don't give access to the global site packages dir to the
virtual environment
{ $  #   ,  $     $% &, 
 %     :
$ python liten bootstrap.py no site packages /tmp/liten EN
New python executable in /tmp/liten EN/bin/python
344
 =. '     
version show program's version number and exit
h, help show this help message and exit
c, config Path to read in config file
s SIZE, sie=SIZE File Sie Example: 10bytes, 10B, 10MB,10B,10TB, or
plain number defaults to MB (1 = 1MB)
~, ~uiet Suppresses all STDOUT.
r REPORT, report=REPORT
Path to store duplication report. Default CD
t, test Runs doctest.
|      , %  $ #  ,     $ &  $ 
 #    # $   
$    #  .
H  &, %    $     #  $ #  $  
(     virutalenv       #$   $% 
. J #" , %  %    , virtualenv  %  & 
 \ISS +keep its syntax simple  (&      '
  -,      % '   % , %    #  
 #$        &  & $    
 $ . {     
&   #   , 
 &      , &$ #     %   
virtualenv    
http:44groups.google.com4group4pytho�nvirtualenv4
/ %  EPM
H  '    EPM  $  
   & '   
    ,     '      #     
 ,   $  &     . J &    &   
( (    $ $      #     
&         #     #   #  #(
". ^  $   #  
  #( " + 
#      & -,  $' &   ' ,  
      3  Red Vat, %     #    
  ,   & &     .
   $ '   EPM          , 
     && & 
 $ $ %  EPM. ^  
     ,   $     $  #    
    % &,  & $ ,  $   
      ,   $ EPM.    % &  
      
http:44www.epmhome.org4epm�book.html
& &    ,  #      $  $  $
&     $ &  .  
 $        
 $ &       
 % &,       
( $(  ! (: Ubuntu, OS X, Red Vat, Solaris  ]reeBS[.
|  "      #  
   ,  '
 EPM,    AIX  VPUX.
    EPM
 ' %      $% ,     %#  
& EPM.   !#    ,    '  
 $%#   
         
   % &   %  !  ,       ! 
!  . J &       $ %   ' ! 
       #$  #&
 (   (  (
 &  ( !  .
 ' $    %   EPM
Y&     EPM   & #  &   %  
Bourne shell, &  &$  q
   make  gzip.   
      % #  %      UNIX    
 ,   '     .
    (   
EPM   $' ,  (    #     
#  #  :
./configure
make
make install
    '  Jello [orld   
 "  
 ' %    #  $    &   UNIX  
 ,  (   # %  , %   &   #.  (
 '"(&    %  $         
         
hello_epm.py
,   $    9.8.
% 9.8. L % %"&    Kello EPU
#!/usr/bin/env python
import optparse
def main():
p = optparse.OptionParser()
p.add_option(' os', ' o', default="*NI")
options, arguments = p.parse_args()
print 'Hello EPM, I like to make packages on %s' % options.os
if __name__ == '__main__':
main()
{ $  #   ,   %     :
$ python hello_epm.py
Hello EPM, I like to make packages on *NI
$ python hello_epm.py os RedHat
Hello EPM, I like to make packages on RedHat
346
 =. '     
   !   
:; EPM
   #$ &  #   , %  ' $ #  
   ,  %  #"       #$ # EPM & 
    !         % &. EPM % 
!+-    % , 
 "      
 %  .          % % &   
, 
    
,       
,   ,   
  ! ,    ,    $   
%  (  % &  !    .
   # EPM  '  $  #   #   ! 
       ,    !  $  . H
  %&   $  
!  $( !   .
  "     $ 
 !  $    $
% &   $  !  ,    %&,   
.    9.9   & "  !  ,  #$ "&
 &  $ &    "          
hello_epm
.   ,  "  && &  #  #,
%   '  #$  #    $% # $  & &
 $ &  (    (    .
% 9.9. -   " EPU
#     EPM - 3 3     
#@+@   @7X  -
#epm f format foo bar.list ENTER
# -  format - + 3 -   @7X @ X :
#aix    --- +    -  AI.
#bsd    --- +    -  FreeBSD, NetBSD  OpenBSD.
#depot  swinstall    --- +    -  HP U.
#dpkg    --- +    -  Debian.
#inst  tardist    --- +    -  IRI.
#native " "  7   -   (RPM, INST, DEPOT, P, ...).
#osx    --- +    -  MacOS .
#pkg    --- +    -  Solaris.
#portable   -    --- +    - ( -@).
#rpm    --- +    -  Red Hat.
    EPM
#  -   Q   -    Q
$prefix=/usr
$exec_prefix=/usr
$bindir=${exec_prefix}/bin
$datadir=/usr/share
$docdir=${datadir}/doc/
$libdir=/usr/lib
$mandir=/usr/share/man
$srcdir=.
# G - 
%system all
f 0555 root sys ${bindir}/hello_epm hello_epm.py
# J-  Q
%subpackage documentation
f 0qqq root sys ${docdir}/README $srcdir/README
f 0qqq root sys ${docdir}/COPIN $srcdir/COPIN
f 0qqq root sys ${docdir}/hello_epm.html $srcdir/doc/hello_epm.html
#   Q    (man)
%subpackage man
%description Man pages for hello_epm
f 0qqq root sys ${mandir}/man1/hello_epm.1 $srcdir/doc/hello_epm.man
{ $& #  # !,   $
hello_epm.list
 ' $  #, %       
$srcdir
, $%  
      
   %    .   $  # 
&   $  $ '(  ! ,   (   $  #  
   %       !    :
\EQDUE
CVPW`
doc4hello_epm.html

doc4hello_epm.man
.    '   
 '  (  #&  "  
hello_epm.py
 '    '   # EPM,        
!    ,     &   #,    
  :
$ pwd
/tmp/release/hello_epm
$ touch README
$ touch COPIN
$ mkdir doc
$ touch doc/hello_epm.html
$ touch doc/hello_epm.man
{  # $& #  "   ,  '  #   
 ' :
$ ls lR
total 16
rw r r 1 ngift wheel 0 Mar 10 0q:q5 COPIN
348
 =. '     
rw r r 1 ngift wheel 0 Mar 10 0q:q5 README
drwxr xr x q ngift wheel 1z6 Mar 10 0q:q5 doc
rw r r 1 ngift wheel 1q95 Mar 10 0q:qq hello_epm.list
rw r r Y 1 ngift wheel 2^8 Mar 10 0q:10 hello_epm.py
./doc:
total 0
rw r r 1 ngift wheel 0 Mar 10 0q:q5 hello_epm.html
rw r r 1 ngift wheel 0 Mar 10 0q:q5 hello_epm.man
   
@  #    &     !    %&,  '  
,     #        !  ,   
&  '  EPM. @  #  , %   #   #,  $  # 
 
epm
,    $  !   & !   %&.
   9.10  $ ,   &   OS X.
% 9.5. ?#" " " VS X    %/ EPU
$ epm f osx hello_epm hello_epm.list
epm: Product names should only contain letters and numbers!
$ epm f osx helloEPM hello_epm.list
$ ll
total 16
rw r r 1 ngift wheel 0 Mar 10 0q:q5 COPIN
rw r r 1 ngift wheel 0 Mar 10 0q:q5 README
drwxr xr x q ngift wheel 1z6 Mar 10 0q:q5 doc
rw r r 1 ngift wheel 1q95 Mar 10 0q:qq hello_epm.list
rw r r Y 1 ngift wheel 2^8 Mar 10 0q:10 hello_epm.py
drwxrwxrwx 6 ngift staff 20q Mar 10 0q:52 macosx 10.5 intel
      '  ,    %  
   #$  #    %
 &     .   
%      $     $  
.   $#    $    
maco�sx5.-7.;.9.;D6intel
  
 ':
$ ls la macosx 10.5 intel
total 56
drwxrwxrwx q ngift staff 1z6 Mar 10 0q:5q .
drwxr xr x 8 ngift wheel 2^2 Mar 10 0q:5q ..
rw r r Y 1 ngift staff 2zz29 Mar 10 0q:5q helloEPM 0.1 macosx 10.5
intel.dmg
drwxr xr x z ngift wheel 102 Mar 10 0q:5q helloEPM.mpkg
| % #   ,     $  ! (
,  &&
&   !   & OS X,  ' "  & 
 & ,    & OS X.
{  # $  #    ,  ' $  #, % OS X   
  !      %          
    EPM
     '   !   $   " 
 .   %    "  
       %  ,
    $ ,      $   &:
$ which hello_epm
/usr/bin/hello_epm
$ hello_epm
Hello EPM, I like to make packages on *NI
$ hello_epm h
Usage: hello_epm [options]
Options:
h, help show this help message and exit
o OS, os=OS
 V EPM "       
{    #  
scp
   #   
/tmp/release/hel
lo_epm
 Red Vat, Ubuntu  Solaris,   '    #   
'    $ &  , $  %   $&  ! ,
       #.   8  $,   $  # ! 
 &   , %        #  $  #   
!    .   
 , %      
(       &    $   ,   &
$$ . @  #    #   (  $&, %  $   #
 ,    $   ,
% #  $  #      
   !    .
H  '    EPM    &   ' #    &  
 #(     ,   ( &  $     .
{     $ # ,   $  #    %  $
  ,  $  #         %     
 ,      #&       !#  
   EPM,   &    %     .
    
  
      &        UNIX&#x-10;.8;&#x-9.5;&#x0.8;&#x-5.; -2;&#x.1-;.6;&#x-4.7;&#x -;.1;&#x -6;&#x.6-; .5;&#x -14;&#x.1;&#x-1;�-4;&#x.7 ;&#x-13.;&-1;�.6 ;&#x-4;&#x.7 ;&#x-6.2;&#x -14;&#x.12;&#x-6.;d.8;&#x-7.; -;.3;.7;&#x-10;.4;&#x-18.;7.;-1;.1 ;.9;&#x-9.5;&#x12.; -1;.24;&#x.8;&#x-11.; U-;.3N;&#x-7.4;&#xI-14;&#x.8X-;.40;Linux
   '$.  ' $ #  &( $   (
',  &( $ ,  (, $ &(    cron,
 '(   (,   $ %     (  
 .  % #, &$ Python 
        #
    . ;%&    Python 2.4,  &&  #
  # subprocess,  $ &   '  #     
   #& !     %  $         
 ,                    "
(.   !        "#  $   
   =    '   #,  $   #  & #
  ,    ' #  &.
/  subprocess
   Python 2.4  &&    # subprocess, $&"  
   # (  (   :
os.system
os.spawn
os.popen

popen2
H # subprocess       $  &  '$#  
(       $ % ,  (  &  #
        &   #     % . @ 
 #  &  #  # &      , 
,   %  % ,  '  #$  #& &  & 
    .
H # subprocess  ' %  #  ' &     
     ,   %    % ! 
  !    . H # subprocess  %  &$ Python
$     (  :   '   (    ,
$ subprocess
         
  ,       ,
           " (   %    $
   (    .
   # "   ,     #  \ISS +\eep
Its Syntax Simple  (&      '   -     
#  & subprocess  
  " $      
 ,   $    10.1.
% 5.. &'&  % /# %" subprocess
In [q]: subprocess.call('df k', shell=True)
Filesystem 102q blocks Used Available Capacity Mounted on
/dev/disk0s2 9^zq98^2 800qz82q 1^0500q8 8z% /
devfs 106 106 0 100% /dev
fdesc 1 1 0 100% /dev
 �1.     "$
    % . * &
subprocess.call()
    
  &  % &  ,   &  ! &
subpro
cess.Popen()
 .
+       :;
 $subprocess
)   $  #, %   #$ 
subprocess.call()
 '
 % #   $ , %    #,  #  " 
    . {    #
   &  &$
q  Bash,  '  # $ $     $ . 
$ $ &  !$ (    $   #$
 & &  $% &    &&      .
'      $  $   ( ,  $%  
  $   '  #$  #&, %    #,    &
'  & #  .   ,     $
$%  , % &,   #   " .  % 
  & $ %   #$    $    #,
   &  & #,       $%  , %
 &,  #   " . ;     '  
    (, ( &    ( %  (      #$ &
  $ .     
# $% &   $ ,
  #  , %
  ?   , %
!  && &  &          $
 "    "
CtrlC
.    $      #
$  #      $    (  &$ Python.
      & &       
 $   ( $%  :
D " $ " 
& " 
; #  #$    (    % 
=;
$ &     '  #   
=7
     
=8
;      
exit
=8n
* #& "    n
F5
   $ "  '    "
CtrlC
=66
D $ $ " & $ 
    $ 
;   %  ,     &     & #
&,   #$   0  1,
    #  
 "     %  $ "  # %     
.     #   (     #$ & ,
 $ ( !  
subprocess.call()
. $&    10.4.
$ subprocess
% 5.G. 3", # %+&  A& subprocess.call()   "
In [16]: subprocess.call("ls /foo", shell=True)
ls: /foo: No such file or directory
Out[16]: 1
  #         ,
  %  $  1, 
#   " . H  '  $ #  $    
    $   #$  #    (   &(,   
$    10.5.
% 5.6. ]+   A,    " # ,
%+&   A subprocess.call()
In [25]: ret = subprocess.call("ls /foo", shell=True)
ls: /foo: No such file or directory
 �1.     "$
 $%   ( .    , '  $  $ ,
   %   Solaris 10      '  ,
% #"  &#  Red Vat Enterprise Linux 5:
ash z.00# python
Python 2.q.q (#1, `an 9 200^, 2z:z1:zz) [C] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
��� import subprocess
��� subprocess.call("rsync", shell=True)
/bin/sh: rsync: not found
1
H   '   '   #$  #      $ ,
  #         .    
 &     '      # %    
 . {      #     ,  
&       "  $  #&  '    
platform.       
    $ #   8,
     '  #&   $   #  !  .
$&    10.7,     # platform  #$ &
     '    % IPython, %    #, 
      # ! 
subprocess.call()
% 5.7. L/# %"& platform  subprocess, -+ -"/,
 %" +  Solaris 5
In [1]: import platform
In [2]: import subprocess
In [z]: platform|
Namespace: Interactive
File: /usr/lib/python2.q/platform.py
Docstring:
This module tries to retrieve as much platform identifying data as
possible. It makes this information available via function APIs.
(  -3     3 --3 - +W -  -Q,
   Q@7   Q@  -,  +      K 
 -Q    Q API.)
If called from the command line, it prints the platform
information concatenated as single string to stdout. The output
format is useable as part of a filename.
(    -        stdout  -Q@
  -     .   -  - ,   -
3 3  - .)
In [q]: if platform.system() == 'SunOS':
....: print "yes"
....:
In [5]: if platform.release() == '5.10':
....: print "yes"
$ subprocess
....:
In [6]: if platform.system() == 'SunOS':
 �1.     "$
p = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
out = p.stdout.read()
print out
;'   &    
   !    :
In [28]: multi("df h", "ls l /tmp", "tail /var/log/system.log")
Filesystem Sie Used Avail Capacity Mounted on
/dev/disk0s2 9zi 80i 1zi 8^% /
devfs 10^i 10^i 0Bi 100% /dev
fdesc 1.0i 1.0i 0Bi 100% /dev
map hosts 0Bi 0Bi 0Bi 100% /net
map auto_home 0Bi 0Bi 0Bi 100% /home
lrwxr xr xY 1 root admin 11 Nov 2q 2z:z^ /tmp� private/tmp
Feb 21 0^:18:50 dhcp126 /usr/sbin/ocspd[651q5]: starting
Feb 21 0^:19:09 dhcp126 login[65151]: USER_PROCESS: 65151 ttys000
Feb 21 0^:q1:05 dhcp126 login[6519^]: USER_PROCESS: 6519^ ttys001
Feb 21 0^:qq:2q dhcp126 login[65229]: USER_PROCESS: 65229 ttys002
J &   &$  Python    %     
*args
  '  $  #    #   $  $ #  % 
 ,  #$& " !   %   ! . ' &  
$  & $ %    
args.pop(0)
{   
 #$  $     $   
args.pop()
,   $ 
#       & .   #       $ % & 
  '   #   ,
    ! ,  $ 
        
def multi(*args):
for cmd in args:
p = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
out = p.stdout.read()
print out
H
pop()
        #$ &,    ,
args

 ',    '    
pop()
.   &  , #" ,  %    
 ,      $  % ,   $    '
       . @ & ! &    & # 
   :
def multi(*args):
cmd = list(args)
while len(cmd)� 0:
p = subprocess.Popen(cmd.pop(0), shell=True,
stdout = subprocess.PIPE)
out = p.stdout.read()
print out
%.  .
|      #   &    .    1.
%. �
.
$ subprocess
      % (  & $  #   
#    ,          $  #  #,
        $ '  #. Y   ,   '
    $  #    #       ($ 
 &. )(    
&   &    10.10.
% 5.5. "/.65;&#x. -5;&#x.47;&#x.6";&#x8.2;&#x/-8.;н-     %" subprocess
#!/usr/bin/env python
from subprocess import call
import time
import sys
subtube K  -3, 7@7   - @7      
-   subprocess
class BaseArgs(object):
""" , @7 + - X -  """
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
if self.kwargs.has_key("delay"):
self.delay = self.kwargs["delay"]
else:
self.delay = 0
if self.kwargs.has_key("verbose"):
self.verbose = self.kwargs["verbose"]
else:
self.verbose = False
def run (self):
"""G    3 -  run"""
raise NotImplementedError
class Runner(BaseArgs):
"""
&7  subprocess.call     3 3 -.
    Runner - N QX -  
  @7  + 3 -  :
[ + 3 -  -  ]
delay=1,     X
verbose=True, +     -X   X
 3:
cmd = Runner("ls l", "df h", verbose=True, delay=z)
cmd.run()
"""
def run(self):
for cmd in self.args:
 �1.     "$
if self.verbose:
print "Running %s with delay=%s" % (cmd, self.delay)
time.sleep(self.delay)
call(cmd, shell=True)
K  #   ,   #
$  #& "     :
In [8]: from subtube import Runner
In [9]: r = Runner("df h", "du h /tmp")
In [10]: r.run()
Filesystem Sie Used Avail Capacity Mounted on
/dev/disk0s2 9zi 80i 1zi 8^% /
devfs 10^i 10^i 0Bi 100% /dev
fdesc 1.0i 1.0i 0Bi 100% /dev
map hosts 0Bi 0Bi 0Bi 100% /net
map auto_home 0Bi 0Bi 0Bi 100% /home
q.0 /tmp
In [11]: r = Runner("df h", "du h /tmp", verbose=True)
In [12]: r.run()
Running df h with delay=0
Filesystem Sie Used Avail Capacity Mounted on
/dev/disk0s2 9zi 80i 1zi 8^% /
devfs 10^i 10^i 0Bi 100% /dev
fdesc 1.0i 1.0i 0Bi 100% /dev
map hosts 0Bi 0Bi 0Bi 100% /net
map auto_home 0Bi 0Bi 0Bi 100% /home
Running du h /tmp with delay=0
q.0 /tmp
{    #, %        %  $ ssh   "
",         #,  ,    :
machines = ['homer', 'marge','lisa', 'bart']
for machine in machines:
r = Runner("ssh " machine "df h", "ssh " machine "du h /tmp")
r.run()
|     $        " ,  
 &      # 
&,   %   Red
Vat Emerging Technology $  &  ,  
     #   $     &$
Python.   ! , &   &    ]unc,
;'   &   , ( &         
 &   $$   (  ,  $    httpd. )  
 , ,   $ 
 #    &  ,  & ]unc.
]unc +]UNq-   #   8,   #    
&    &,   &   #    UNIX 
    .
results = fc.Client("*").service.status("httpd")
$ subprocess
if returns == 0:
fc.Client(host).reboot.reboot()
H # subprocess   % !   !  $
  &    ,     #   %   $  #
$# (         .    10.11  $
      %  %  ,  &   %  # %  
   ,  $              
  .
% 5..  #A #   % "  "
 # %"/ subprocess
In [z5]: p = subprocess.Popen("wc c", shell=True, stdin=subprocess.PIPE)
In [z6]: p.communicate("charactersinword")
16
|   &    &$ Bash &  ,   $ ' :
� echo charactersinword wc c
      $    #
   Bash     #
!         . Y& %   (  $
 # %  #  !=       #$        
 Python 2.6.   , % 
  #$  Python 2.5  ( 
  #$  #        (  $ '  :
In [5]: from __future__ import with_statement
In [6]: with open('temp.txt', 'w') as file:
...: file.write('charactersinword')
@  #  '     # ! %       %
 #   '     
,    %  $%   
In [^]: file = open('temp.txt')
In [8]: f = file.read()
     '    #
!  ( '    
 :
In [9]: p = subprocess.Popen("wc c", shell=True, stdin=subprocess.PIPE)
In [10]: p.communicate(f)
In [11]: p.communicate(f)
      % Bash    &    #  # 
 &  ,   $ ' :
% echo charactersinword � temp.txt
% wc c temp.txt
 �1.     "$
@  #   ,   $  #        
     # (  , & %  #$ &   &(
 &$      % .    %,  &   
  #  #  , ?  (    ,  &$ Bash,
$   $   '     #  #  &$ Python.
;    % # % (  &  #   ! '
 .    10.12   & ,  &  &   %  
 #$ &   #$    root     Macintosh.
% 5.=. -" %"  A   %/ %" subprocess
; &$ Bash     & &        
 %   :
[ngiftYMacintosh 6][H:1001�q] cat /etc/passwd grep 0:0 cut d ':' f ^
/bin/sh
K %&    #
 #  &$ Python:
In [^]: p1 = subprocess.Popen("cat /etc/passwd", shell=True,
stdout=subprocess.PIPE)
In [8]: p2 = subprocess.Popen("grep 0:0", shell=True, stdin=p1.stdout,
stdout=subprocess.PIPE)
In [9]: pz = subprocess.Popen("cut d ': ' f ^", shell=True,
stdin=p2.stdout,
stdout=subprocess.PIPE)
In [10]: print pz.stdout.read()
/bin/sh
@     , ( &   '   $  #        
#  & subprocess, $  ,     $% , %
#        #.          %
 &      %   #$  & root, ?     
   #  #  . ; &   &  (  
&$ Python  &     #,    % # ' $ #,
   ' $ ' #  #$ &  & subprocess &$ Python
 '  ' #     #,        #  
(    . H  $  , %  '   #    
  % ,  ,  $  # (  !  tar  zip,  '  
$  #   &$ Python  $  #$ &   .   ,
   ' , % (  &  $  # % #  '
       #$    & subprocess,  
       &$ Python. $&    10.13.
% 5.F. L/# %" pwd " -+  -#& "+0
 & % subprocess
In [1]: import pwd
#$"     Supervisor !  !    
361
In [z]: shell = pwd.getpwnam('root')[ 1]
In [q]: shell
Out[q]: '/bin/sh'
H # subprocess  $ &  
     #
  
         # 
$         
   ,   '  % #  $         
    " (.    ,     .
   , %   #$   
upper.py
&  
 %     % &     im $       %
 IPython,     ( 
 # !    
,   '   & #     ,  %  
     10.14.
% 5.G.  " "+0   "  "   % "+0
#   "  +"  #   " 
+" -& - '- 0
import subprocess
p = subprocess.Popen("tr a A Z", shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
 �1.     "$
 , Supervisor  '  & #   $ ""(&  
  , %  ' $ #& % #  .      Su
pervisor,  H   +qhris Mc[onough-,   , %   
'  '  #$  #& &  &  (   ,
 #   ,   &,
 , "    & 
        . Supervisor   %  $ '  #
     &      XMLRPq Interface Extensions
Event Notification System.
      &  #"       UNIX (
      & #  
supervisord
 , 
$     %    , 
supervisorctl

  &  ,  $ &&    # ! ' 
& #   .    ,       ! ,  ,
  #     UNIX (  (,  & #" .
     &  (         &  
Supervisor 3.0.x.              
 '  % #    
http:44supervisord.org4manual4current4
. D
     Supervisor  $   (  '  
 '    #    #   
easy_install
.    ',
%     # virtualenv  $  #    & $  
    Python,    %    #   Supervisor
 '    #     :
bin/easy_install supervisor
    Supervisor    
. {   #$  #&  
easy_install
     Python,       
     ,  ,
4usr4local4bin
       %
&   .
   ,      #   $   
  Supervisor, $ % &   $      &,
,        ,    , '  3  
  $ "    . @   ,  % ,  #$& $ #
 '    ,      #      
 $ ( #(      Supervisor     #
  %     $
  #  ,  & (   
    . @  #  ' $  # !
supervisord.conf
, 
 #$& &    #  
echo_supervisord_conf
.   
     $ &  !
#$"     Supervisor !  !    
     ,    #$ &  $ '  #   Su
pervisor   $  #   
,   $    10.15.
% 5.6. &  %  #   A  %/   %%+
Supervisor
#!/usr/bin/env python
import time
print "Daemon runs for z seconds, then dies"
time.sleep(z)
print "Daemons dies"
 '   #  , %    % # $ % (  
      
supervisord
,   (      #
!  !   #    "  '  . Y
 & #"    !
 �1.     "$
supervisor� tail f daemon
== Press Ctrl C to exit ==
for z seconds, then die
Daemon died
Daemon runs for z seconds, then dies
+      screen
$  $   
K#    (      $ % &  
 #$    GNU screen.        
   (      #     screen, '  
   # & #   $     &$ Python.
 $  (        screen $ % &  ,
%   $ &  & #&  '      #
 $ #&  . |  #   $&  $ '  #, % 
" $&      
   '   #  
$  (         UNIX.
  %  ,
         #&  
 #&  '    ' &,    trac.  
    #         trac,        
 , %    #& #     trac    #
  screen.
 , %  (  & $          
 screen,      #   screen     $ 
 '    ,  $  ' #  "
CtrlA
CtrlD
, %    #&  .   #  % #&
    ,    %         
screen
' # "
CtrlA
 $.
   10.16  $  & $   tracd    
screen.  #    $  &,   '      #
&  , '  "
CtrlA

CtrlD
, ,  % ,
   &, %  $    #    % #&  .
% 5.;. 1   %%  #+  Python "  %
  %%+ screen
screen python2.q /usr/bin/tracd hostname=trac.example.com port 8888
r single env auth=*,/home/noahgift/trac instance/conf/
password,tracadminaccount /home/example/trac instance/
 & #  % #&    ,  '     :
[rootYcent ]# screen r
There are several suitable screens on:
q^9^.pts 0.cent (Detached)
  !  Python
 $ ' ,    %"  ( &  #$ &   % 
 ,  & ' $   %   #$ &   
     .
  $  Python
    &     &   (  $ .
;  &  , %      & &,     ,   
$ &  " # $ %,   (
 &      # 
$    #   .     &     ,
  %   & &   (     '   
     #$ & #   . |  $ (  #"(
           #"      .
    $ % &  , %  '  $  #  & 
   (,            &
 $  #$ &  ($   '  ( $   +IPq-.
;        &      .  
#&  ,   && $   # ( &     
  ,         &  '   # % $
%  ' . H   %    ' ' #  $
 #$ &  ?   
 ,      %  
   & % #  '     ,   %   
 %  !   ' $ #& "  ?   $ 
.  $     $     &      
(    #   SNMP,   $  #     
 '      & $ # % #    .
      
  ,    $ 
   %(  ' ,   $&  '    
    $  (   .       $ #&
% #         "   '( $ %.
     &    %(  '   '
$ #&   $ &       .    #
  ,       &     #&     
        
 :    # 
     %    ' , $ %    # (   
    , $ %            
(  .
 (&&    #  \ISS,
   $ (  
 (     #$ &   # (     &.  
 $  #, % &  #$ &  & threading  (   
 ?          &. {  
   %  ?          &
+-      ,       ' $ #&   
&  & .    %          #   
 �1.     "$
   H  /  +Mark Lutz- Learning Python +OReilly-
  
$  #&      ,   '   #&
 1            #&   (
 (,    & &.   %  % , ?   
         , %  $% #  .
  #      &   %      &$ 
Python,        
        % 
 ' &,   #$ &          % 
   &.          %    
 #$ &  # threading.      & $% 
 #      ,  $
    & & 
run()
 
  &. ;  , $  & & #     &, '
 $ (       .
  (  " &(    % $        
(  $,   %    $   #    #$ 
   '  #    .         %
"  #$  # %  ,      & #   & 
 '  # $        #$  .
)(    &   &    10.17.
% 5.7. &'& %+& A &
#  - 3     -   3 -- -
import threading
import time
count = 1
class issThread(threading.Thread):
def run(self):
global count
print "Thread # %s: Pretending to do stuff" % count
count = 1
time.sleep(2)
print "done with stuff"
for t in range(5):
issThread().start()
[ngiftYMacintosh 6][H:10q6q][`:�0] python thread1.py
Thread # 1: Pretending to do stuff
Thread # 2: Pretending to do stuff
Thread # z: Pretending to do stuff
Thread # q: Pretending to do stuff
Thread # 5: Pretending to do stuff
done with stuff
done with stuff
done with stuff
H / . )$%  Python  .  . .:  , 2009.
%.  .
  !  Python
done with stuff
done with stuff
#common.py
import subprocess
import time
IP_IST = [ 'google.com',
'yahoo.com',
'yelp.com',
'amaon.com',
'freebase.com',
'clearink.com',
'ironport.com' ]
cmd_stub = 'ping c 5 %s'
def do_ping(addr):
print time.asctime(), "DOIN PIN FOR", addr
cmd = cmd_stub % (addr,)
 �1.     "$
Sat Apr 19 06:q5:5^ 2008 AITIN FOR clearink.com
  !  Python
369

~.task_done()
for i in range(num_threads):
 �1.     "$
@  #   & "           
       $.   ,  %     # 
 ,       ,  %   ,  #"   
&    &   threading  Queue.  '  % #
" , $     %(  '   $  #$ & % 
     ' ,    $ &   . & 
$,      &   #  #$   , ' 
#  #$  #  # Queue.  % F |  # '  
   #  &   $ $  (    # #  ,
  %     ($ ( %     %  
(  $  (.
  # , %  !  �% , '     ,  
$ , %   , ( % $  +  
  $ #,  % ,  #    -,    "  
&  $    &  20      .
| % #     (   $ '  #,  & , 
   '   #  % , %    # '  3   ,
 %   #    '   # 50   .   #  (
  ,  '     #&   # (  ,  $    '
    '  '  #         . 
% , $    ,    , %       
$ ".  ' "#  # %    $    #
  , %          #  $ %   
 #    .
{   #     , 30   , &  $ %,
   $   # & 50      %  $ 10   . |  
  #$ &    %     &(  &$ Python. 
     &   &    ,
   %  #  , $   ' %  #   .
%     %     
% $     
  $  $ .  $ ( '(     " 
      $   
join()
.   
~ueue.join()
   :
Namespace: Interactive
File: /System/ibrary/Frameworks/Python.framework/ersions/2.5/lib/
python2.5/
ueue.py
Definition: ueue.ueue.join(self)
Docstring:
Blocks until all items in the ueue have been gotten and processed.
(   @7  --,   + ++ 
 K -     )
The count of unfinished tasks goes up whenever an item is added to the
~ueue. The count goes down whenever a consumer thread calls task_done()
  !  Python
(G ,     3 +   K -  ,     
  X . G ,  3 3    - 
task_done(),  +  3,   W      K -  ++ ,
  - 3 .)
hen the count of unfinished tasks drops to ero, join() unblocks.
(    - 3   , -  join() 7
  @7  -- .)
H
join()
  &             # $ 
"    &        ,   #
    &  % "
$ " #      
%  .  $&#  !   !   ,    '
 #  !   ,    %    (  ,  
     &  ,  &#   # . {  
"    $     # $   
~ueue.join()
, 
#    &    $
&  $ #&.     $ 
    # $ 
~ueue.join()
print "Main Thread aiting"
#V --   3  -  join,  --   
# ,     - 3  3 @ + 
#~ueue.join()
print "Done"
@  #   , %   " $ % #  . $&
    10.19.
% 5.9. % , " +&  +   %%+
# ' - /' " 0  
[ngiftYMacintosh 6][H:10189][`:0]# python ping_thread_basic.py
Main Thread aiting
Done
Unhandled exception in thread started by
Error in sys.excepthook:
Original exception was:
@  #, $ "#      &   &(   
  &  %  ,   &      " $ " .
   %  '      # $% , 
   #(  ( %    &    
      .    &
num_threads
 ' %  
%(  ,    &
~ueue
  $ & %   ,   ,
ips
  IP   ,   '     #  %  #:
num_threads = z
~ueue = ueue()
ips = ["10.0.1.1", "10.0.1.z", "10.0.1.11", "10.0.1.51"]
 & ! &  &        .  
$ & '     $  %    IP   $ %  .
 �1.     "$
 % # , %      
 & $ %     '  & 
,     ( & &  
. @ &  $&  $ & $
  #    ,   %  #   .    
while

$ & 
~.task_done()
  ' $%  ,   %
    
join()
, %    %       ,
$ %  $ %  . ),   &    &$ ,   
, % $     .   , %    &  
 
ueue.ueue.task_done()
File: /System/ibrary/Frameworks/Python.framework/ersions/2.5/lib/
python2.5/
ueue.py
Definition: ueue.ueue.task_done(self)
Docstring:
Indicate that a formerly en~ueued task is complete.
( 3   -,           +  .)
Used by ueue consumer threads. For each get() used to fetch a task,
a subse~uent call to task_done() tells the ~ueue that the processing
  !  Python
print "%s: did not respond" % ip

~.task_done()
;'   #$      
for
,  &  $  
     &.  % # , %     
   ' ,   %  #   & &  %  .   
%    (  ,   
       $
.
 "     &  
 $ & (   #, &  
(&     &
  " .    
$   
 �1.     "$
 %"  & #  
 #$ &    %  ,
 '   #   "     #  "   
       %  #.        
"    #    ping  IP   ,  $ 
 $ %  .      
 $      
    # IP  , (   %   ,   
%  #.
     &     $  # IP   $  
  %  ,  $  #      #    arping   $
 # IP      MAq 
. )(     
  &    10.20.
% 5.=5.  /   "&   /     
#!/usr/bin/env python
# +  Python2.5  
from threading import Thread
import subprocess
from ueue import ueue
import re
num_ping_threads = z
num_arp_threads = z
in_~ueue = ueue()
out_~ueue = ueue()
ips = ["10.0.1.1", "10.0.1.z", "10.0.1.11", "10.0.1.51"]
def pinger(i, i~, o~):
"""  """
while True:
  !  Python
#  3   3 MAC         
result = out.split()
pattern = re.compile(":")
macaddr = None
for item in result:
if re.search(pattern, item):
macaddr = item
print "IP Address: %s Mac Address: %s " % (ip, macaddr)
o~.task_done()
# -   3 IP      3
for ip in ips:
in_~ueue.put(ip)
#  3   , @7X    ping
for i in range(num_ping_threads):
 �1.     "$
       $   . H ' '  $ #, % 
    & $& 
&$ #(   .
@  %  $  :;
threading.Timer
 &$ Python  &       #,  &  " 
 , &  ' $ #&      "  $ % 
     &.        $ ! 
  $ '     ,   $    10.21.
% 5.=. H&%    
#!/usr/bin/env python
from threading import Timer
import sys
import time
import copy
#  ++  +
if len(sys.argv) != 2:
print "Must enter an interval"
sys.exit(1)
# Q,   +  3      - 
def hello():
print "Hello, I just got called after a %s sec delay" % call_time
# ,         - 
delay = sys.argv[1]
call_time = copy.copy(delay) #    3 
t = Timer(int(delay), hello)
t.start()
# 3,   --  +    +  3
print "waiting %s seconds to run function" % delay
for x in range(int(delay)):
print "Main program is still running for %s more sec" % delay
delay = int(delay) 1
time.sleep(1)
{ $  #  !  ,  '  #, %    
  '        (   '  $ 
! :
[ngiftYMacintosh 6][H:10q68][`:0]# python thread_timer.py 5
waiting 5 seconds to run function
Main program is still running for 5 more sec
Main program is still running for q more sec
Main program is still running for z more sec
Main program is still running for 2 more sec
Main program is still running for 1 more sec
Hello, I just got called after a 5 sec delay
  !  Python
' ' ' "  
|    $%  &  (     ,   
    "    &  " &  
 %  $ %.     
  $#    '   
  '  $   ?       ' &   ,
       & # % ( '    ( !   
'  &   . H       #"    & #  &
    $  & ! ,  ,
 &   ( &  
#       ,    ,        
 & & '        ,  %   & &, $ 
&   .
|  #    '  $  #     #  
  ,       10.22 '       , 
   ( $  #&  $ '     #  
rsync
delete
,   '     '  $%&.
% 5.==. L % 0 #A 
#!/usr/bin/env python
from threading import Timer
import sys
import time
import copy
import os
from subprocess import call
class EventoopDelaySpawn(object):
""" ++  + ,    -      """
def __init__(self, poll=10,
wait=1,
verbose=True,
dir1="/tmp/dir1",
dir2="/tmp/dir2"):
self.poll = int(poll)
self.wait = int(wait)
self.verbose = verbose
self.dir1 = dir1
self.dir2 = dir2
def poller(self):
"""  """
time.sleep(self.poll)
if self.verbose:
print "Polling at %s sec interval" % self.poll
def action(self):
if self.verbose:
print "waiting %s seconds to run Action" % self.wait
 �1.     "$
ret = call("rsync av delete %s/ %s" % (self.dir1, self.dir2),
shell=True)
def eventHandler(self):
#V   X - @    - - -
if os.listdir(self.dir1) != os.listdir(self.dir2):
print os.listdir(self.dir1)
t = Timer((self.wait), self.action)
t.start()
if self.verbose:
print "Event Registered"
else:
if self.verbose:
print "No Event Registered"
def run(self):
"""   +     - - ++ """
try:
while True:
self.eventHandler()
self.poller()
except Exception, err:
print "Error: %s " % err
finally:
sys.exit(0)
E = EventoopDelaySpawn()
E.run()
 # %     $
 #, %      &, $ ' 
$ #  && &     (  ,     #  . ;
    , $ '   '  #   #    
 . {  # $ ' ,  ' ,  5   ,  '    
 #       %
  &     &, 
 ,  %  '    
&      .  '
,  $ &    ,   &    $ % #
 ($  $ &     '     , 
 '   #.
 
           #$ &   $ %  
 &$ Python.    #         
       , . . ,  %    &$
Python,    & #&  
$(    (. ;    ,
$$ %&  #          +Global Inter
$ processing
%"   .   ( %&(   %"  $  #
$(   (.
     %"   ,  &  " & $ %   
& $    #   #     .    ,   
 '    ,   
     #   
380
 �1.     "$
 % #(       & processing $ % &  , %
                 ! 
 & threading. | $% , %    & $% #  
API, %    '  #         .     
 processing  '  %  #    :
http:44pypi.python.org4py�
pi4processing
@  #,     %    &   processing,
    10.23.
% 5.=F. 2"  %"/ processing
#!/usr/bin/env python
from processing import Process, ueue
import time
def f(~):
x = ~.get()
print "Process number %s, sleeps for %s seconds" % (x,x)
time.sleep(x)
print "Process number %s finished" % x
~ = ueue()
for i in range(10):
~.put(i)
$ processing
381
Process number ^ finished
Process number 8 finished
Process number 9 finished
Main Program finished
 , %     ,
   '    
    #&  %     ,      &  
      .    ,  !   &     & .
@  #,      &       Vello World, 
  &  #$   & processing,  '  $  # % 
 #      . {    ,  $      
  &   $        %  , 
 &     .   #       !   &
processing % #    !   & threading,   ' 
 $  #  %     %  ,  #$&   
     &,   $    10.24.
% 5.=G. ] ping    A
#!/usr/bin/env python
from processing import Process, ueue, Pool
import time
import subprocess
from IPy import IP
import sys
~ = ueue()
ips = IP("10.0.1.0/2q")
def f(i,~):
while True:
if ~.empty():
sys.exit()
print "Process Number: %s" % i
ip = ~.get()
ret = subprocess.call("ping c 1 %s" % ip,
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
382
 �1.     "$
p.join()
print "Main Program finished"
|     #  ( '     %  , &
 #  . { $  #   ,   
    :
[+ ]
10.0.1.255: is alive
Process Number: q8 didn't find a response for 10.0.1.216
Process Number: q^ didn't find a response for 10.0.1.21^
Process Number: q9 didn't find a response for 10.0.1.218
Process Number: q6 didn't find a response for 10.0.1.219
Main Program finished
[+ ]
[ngiftYMacintosh ^][H:11205][`:0]#
|       #(  & . &   
 !     % #  ( ',  '        #  
 %&.    , % '  $     $  
&      %   ,   & & $ %     
$ %  .    #    , %  '  $ " #
 ,       , &   & , 
   %  #. '  $ 50 % (     %  
 & ,     %  #,    %       ,  
     &, $& ! 
sys.exit()
{  %      &    ,      % $
  %       ,    % IP  ,   
     $ &, 
#  &   $   IP
      #    ping. &    #$ 
join()
, %  ' ,    & 
&,  $ &   
 ,  '  ,   %  #   .       
%    $ " &,  % 
#  ,  & '  
 &
print
  $ "   .
J &  ( '        !   # processing 
 #$  #  '   ,    
# threading.   7  '
  %    $     & processing  
&,  #$    Ne
tSNMP, &    
 && & (  "   & &$  Python.
        Python
@  #,       $ $        
   &$ Python,        #   (  
&   &  (    .
Y& $   , 
(  &$ Python,    (      
cron.
  "    Python
383
 $  ( $ % #(         cron,  
  &   #"  POSIX   (  , $ % &   
      &. |   # , $$ %    #$ 
cron,     %      #    &$ Python
  $ %  (       %:
384
 �1.     "$
server = smtplib.SMTP('localhost')
server.sendmail(FROM, TO, msg)
server.~uit()
| #     $ &   $   %   
 #$          $ cron,      
 &  " &  '   $ 
%. @  #     ,
%     #"  !       &$ Py
thon.    %  #,    #
subprocess.Popen()
 & &
%             df.    $  &  
   & $  &   
From

Subject
.   ?  
  (    $  &    . | &  '& % #  
&.  $ %    $  &
localhost
 %      
  ( &   %           ,  $   ,
! 
server.sendmail()
Y&  %   #$  #    ,  %   
!
4etc4cron.daily4nightly_disk_report.py
{   # % $  #&  &$  Python,  '
 #$  #     "  &     $ 
&  (   .   4        ' 
     $ &         % ,    $  
 #  !     '  #&    .
@  
        # &   ,      
    UNIX  #"   , %   (  &   
$  . Y    &  %      
  $       !     + ,
lpd
  $   VTTP    
% !  + ,  
httpd
 
   Apache-.
@ % '   F         &
&  !     '   ,    &  
. {  $    ($   & $ &  UNIX,
   '  ' #&   , %    
  
   $   . ) '  
CtrlZ
  $ 
         
 $   .   ( %&(
  % !     ,    $  (      
         %    "  & 
 + $ ' ,   '          %
-. )  ,   ( $ 
 :     !     
' ,    &$     , $ "  ,    
&  .   , $   !     '
     ($  &
$ &,  % #  
    .
@  
385
;'   & !     ,     &
& ! &
daemonie()
.    $   
      ,       #      
! . |  ! &  $&  $     ]orking a [aemon Process on
Unix,    &  
  $   Y  K" 
+[avid Asher- Python qookbook +OReilly-   ( 388389.
|     % $      &, 
   %    +Richard Stevens-    
UNIX Network Programming: The Sockets Networking API +OReilly-
 %   #      $ &  . Y& (, 
$       , $ 
, %  %   &
  %       ,   '    
    $      UNIX
. )(   !   
 &    10.26.
% 5.=;.  A daemonize
import sys, os
def daemonie (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
# G 3      Q .
try:
pid = os.fork()
if pid � 0:
sys.exit(0) #   3 Q    + .
except OSError, e:
sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
sys.exit(1)
# @ 3   3  .
os.chdir("/")
os.umask(0)
386
 �1.     "$
  ,    &   &  %    ,  
    #    .    $ &    #
      ' $ " #    . Y&     & &
  !     
pid
    &. {   !  
      ' # % 
,  $% , %  & &
  #    . {  
        
        # ! 
fork()
,   '  $ #& 
 .    $  $ ! 
os.fork()
    && &
      '      .     &
,  $  !  
fork()
,   %      
 # $%  0,     #          #  
!     . /    $%   $ & #
  #    ,  '  $ " #  . {
$ #  $   %  ,   
   $ " &. { 
  $ & $          %  +  
 Bash-,        
#     " &  ,
  %   ,  
$ , # % $ "
 . ; %      '    .
     $ &  %    
os.chdir("/"
-,  
    $% 
os.umask(0)
-   $      +
@  
387
     '     & .     
  && & &$ #  
     & &  #" $
   '  . J $      &          
& ,   #      $
!
O_NOCTT
   , %  ! &,  & %  !    $
  (  $.    & ! &     (
 (          " ( +
sys.stdout

sys.
stderr
-. @     &  ! , &  
  . * &
daemonie()
 $ & $   
  & # !, 
   #  #  
stdin
stdout
stderr
.   %  %    (  ( !   #$ &  
  
/dev/null
.      ! &    $
 #$    !,  $% &
  %   
     ,              
  " (        !.
  '  #$  # ! 
daemonie()
F    ', %
  &  
     &
daemonie.py
  10.27   &    &,  #$   
! .
% 5.=7. L/#  A daemonize()
from daemonie import daemonie
import time
import sys
def mod_5_watcher():
start_time = time.time()
end_time = start_time 20
while time.time() end_time:
now = time.time()
if int(now) % 5 == 0:
sys.stderr.write('Mod 5 at %s\n' % now)
else:
sys.stdout.write('No mod 5 at %s\n' % now)
time.sleep(1)
if __name__ == '__main__':
daemonie(stdout='/tmp/stdout.log', stderr='/tmp/stderr.log')
mod_5_watcher()
|   %   (    '  ,  && 
 , %  %       
    #$  #& !
4tmp4stdout.log
,   %              "
(   #$  #& !
4tmp4stderr.log
.    %  20  
 ,     1     '     ,   '
  &. {  &, '     (,  &  & #
 $   ,  $  & $#   &        
      " (. {  &   &  & #,  $ 
388
 �1.     "$
 & $#   &         . @    
 #$ !
4tmp4stdout.log

4tmp4stderr.log
 %    
                 " (,  
    ,     $ '  #   #     &  
$     ...
$ '   $   &  (   $     
" &  :
jmjonesYdinkgutsy:code$ python use_daemonie.py
jmjonesYdinkgutsy:code$
) '   &  $#     :
jmjonesYdinkgutsy:code$ cat /tmp/stdout.log
No mod 5 at 120^2^2q5z.18
No mod 5 at 120^2^2q5q.18
No mod 5 at 120^2^2q56.18
No mod 5 at 120^2^2q5^.19
No mod 5 at 120^2^2q58.19
No mod 5 at 120^2^2q59.19
No mod 5 at 120^2^2q61.2
No mod 5 at 120^2^2q62.2
No mod 5 at 120^2^2q6z.2
No mod 5 at 120^2^2q6q.2
No mod 5 at 120^2^2q66.2
No mod 5 at 120^2^2q6^.2
No mod 5 at 120^2^2q68.2
No mod 5 at 120^2^2q69.2
No mod 5 at 120^2^2q^1.2
No mod 5 at 120^2^2q^2.2
jmjonesYdinkgutsy:code$ cat /tmp/stderr.log
Mod 5 at 120^2^2q55.18
Mod 5 at 120^2^2q60.2
Mod 5 at 120^2^2q65.2
Mod 5 at 120^2^2q^0.2
|   # % #    
 &  ,   
&, %  &       $   & &.
  '  #$  # ! 
daemonie()
&  $ &  ,
   $   &    ,  &     ,
 (        , %   ,     ' #
+      ' # -  &.
 ; 
 #   & #&, %        ,  #
"      $ '  &   &$ Python & 
     .  &$ Python  $   # $&
 '      !  &        
&,          $   #     GIL. {
 "& 
389
 &$   
,   $%         &&
&    ,      & $$ #     #
    , %"   #
$  #   #    . ; 
 %  , %     
%  # , %   , ' 
        GIL.
& %  & &  
 &     , %      %     
 '    #&  ".
;  ,      "  '  $  #&    
subprocess,       $ . Subprocess   
#  #,          ,  $
%  &    .  #  ,     .
    !    !" 
   !       %& &$     
   , $     !%    !  
 #$  & +)- %  ( 
 ( % . @     , 
    ,        
-0"%
 $  #  
'   !%    !     $     ' &
 '      % #  '$#.  #    
  !%    !   "   ,  $ & 
    ' &  !%    !    $ 
(  ,  GT\  Qt,    ' &    !  .
     "     %    #$ 
 PyGT\, curses    !  [jango. Y& % 
     $ & !%    ! , $    
   % #     ' &,  #$  
  PyGT\,    "  '   '    #$ 
  curses  [jango. ;  , $  ,     # [jango
  #"  ?       '  #  ' 
&    $  (,     #  ! .
 $   $  !
   !" 
    $  &  #&   ,    &, %   
 & #   (   &  $  " #   #$  &.
@   '      ,     $  &    
#  (    $ , 
cron

. ;    $  &
    !%    !  ,    &, %  #$ 
# '   %    #, %           #
   .         !%    ' 
&,      $ ,
        %   
     . 
# 
 '       .
+  ! "!      
391
 '   &    &  $,  $
 ' , $'    #
!  !     
  &         & . ;      ' 
   ' ,    #$  #   %  #.   % , 
      ' ,
 &(    &
  & # ,  ,  , ]irefox   %     & 
%     $ &    &   &  #$  &,
  ' &  &.
 '   '  F   $ , %  #,    #$ 
 #    
  F  ' 
'  ,  
 $ 
-+
.     , %  (    ( 
 ' &   $ $#(      &,   
'        !' . )  '  $ , %  #,
   ( &     &,   %   &$
     &   
 !     
. *     
, &$    
  &, $
- - % -+&
.  $  $% 
  ,  $ (  $  & !%    ! , $
% &  , %  $ # 
#  %   &, 
   (       . {  #   %,  
 !%    !   $     ,   (
   & &        &  (   , ,  
  &  ( & ,  
(        .
    ' & & &   &.     "
 '   !%    !  ,    " ,  
 '  '    #     &  #$  &.
  $   %    ,    $ #&  
 !%    !  
  $'      #$ 
 .
|       ' &,   !   #  
! F @  #   $  #   ,    &  ,  
!'    ' F       $  #$ 
     &. !%    !   '  $  #    
#  #       & !%    ! ,
( &          .     # !% 
   !   $ & $   #  !      ' 
& $% $#    ,      ,  ,
!'    . ; ,           
 Mac OS X    %       qocoa, & $
  & !%  (      '   #$  #&  
  Interface Builder. ),    PyGT\  Linux,  '
  #$  #&    Glade. ),    PyQt,  '
   #      Qt [esigner.
     !%    !      #$ , 
      '  & #& '   #       #
 11. )"      
 !%    !  , %   '   ' #   
   #.   ( %&(  
    '  $  # !%  
 !  %,        .   
PyGT\ '   !%  (          
  &$ Python. ; ,   ? 
gtk.indow
    ? 
gtk.Button
.   $  #    
'   !%    !  ,       , 
 $   $ &  
gtk.indow

gtk.Button
 &
     . {  (  , %    %      
&#    &, 
'   #  %  
&  %     .
       % $ PyYT\
H  $       ,  #$ '  " &

gtk.indow

gtk.Button
. ;'   & (    
   ' &  !%   
!  ,    
%    $  ,    
      $
&    !%    !  .
 ' %   '     #      # 
     '   $   PyGT\,   ( 
   # .     ( 
 ( Linux      
& &   %   .   & &   ' & Windows.
{   #$ #     Ubuntu,     '
 # '    . { & "   !       %
    ,      ' $ #&   %  '
 . )(    ' &   &    11.1.
% ..    PyT  "%  %   "&  &
#!/usr/bin/env python
import pygtk
import gtk
import time
class SimpleButtonApp(object):
"""      PyT  - -    .
 7        +  7  -.
"""
def __init__(self):
#   
self.window = gtk.indow(gtk.INDO_TOPEE)
# "   " ++  + .  
#  - Q gtk  3 self.~uit(),
#  " "  "destroy".
self.window.connect("destroy", self.~uit)
)"     ! PyGTK
#3   "Click Me"
self.button = gtk.Button("Click Me")
#  Q  ++  + .  K  , 
# " "  "clicked", +  3 - 
#'update_button_label'.
self.button.connect("clicked", self.update_button_label, None)
# K    .   "add"     .
self.window.add(self.button)
#      -,      -,
#    --  7   .
self.button.show()
#  3    --
self.window.show()
 11. )"      
@. .    %  $  #       , $ ' %
    , %  (      +
__init__()
-. * % 
 ,  %   , %    '  ,   %     
 . |    '      ,     
    #   & & $ #,      '
   .      $  &  ?  !%    
! :
gtk.indow

gtk.Button
.         &   , 
      ? . H  '  $   % 
  
destroy

clicked
,   '  (          
  .   $   ' &     && &    
,     # qlick Me +   $ #-. '  $,  
 $  &  %    ,  #     & &  
'   &. ; . 11.1  11.2   &  " 
 ' &     %     .
PyYT\ $    
!" %  '    Apache
@  #,          $ & !%    
!        #$   PyGT\,      , 
    # PyGT\  $  %     $  
 $   ' & &     '  ! '
    Apache. |  '     #  
!  #  $ '  &:
 $   #   #    ! '
J ' #      , &     (  ,   &
&  %     (  
 $      #     (   ,      (
(  ,    &&  %     (  
.11.1.
   PyT "     
.11.2.
   PyT      
)"   ! PyGTK !        Apache
|         ,  &  $ !
 ' Apache,      3. )(  
 ' &   &    11.2.
% .=.  PyT "  %  &  
-�   Qpache
#!/usr/bin/env python
import gtk
from apache_log_parser_regex import dictify_logline
class Apacheogiewer(object):
""" -- -     +    Apache,  
   3  -Q@  - - X"""
def __init__(self):
#   
self.window = gtk.indow(gtk.INDO_TOPEE)
self.window.set_sie_re~uest(6q0, q80)
self.window.maximie()
#  3 Q +     
self.window.connect("destroy", self.~uit)
#Box K    , @7 + 3    3
#-  . 3    @   3  +   
#       -  
self.outer_vbox = gtk.Box()
#  3  -    -    
#     
self.toolbar = gtk.Toolbar()
# 3           
#  -- + 3    3  -  
# 3      @7- ++ - + 
open_icon = gtk.Image()
~uit_icon = gtk.Image()
 11. )"      
# 3     -...
self.loglines_tree = gtk.Treeiew(model=self.loglines_store)
#... + 3    
self.add_column(self.loglines_tree, 'ine Number', 0)
self.add_column(self.loglines_tree, 'Remote Host', 1)
self.add_column(self.loglines_tree, 'Status', 2)
self.add_column(self.loglines_tree, 'Bytes Sent', z)
self.add_column(self.loglines_tree, 'ogline', q)
#   3  -@ + 3   +   
self.loglines_window = gtk.Scrolledindow()
#+W  3  - 
self.window.add(self.outer_vbox)
self.outer_vbox.pack_start(self.toolbar, False, False)
self.outer_vbox.pack_start(self.file_chooser)
self.outer_vbox.pack_start(self.loglines_window)
self.loglines_window.add(self.loglines_tree)
#  3 K -   --
self.window.show_all()
# K - K -  +      3  --
self.file_chooser.hide()
def add_column(self, tree_view, title, columnId, sortable=True):
column = gtk.TreeiewColumn(title, gtk.CellRendererText() ,
text=columnId)
column.set_resiable(True)
column.set_sort_column_id(columnId)
tree_view.append_column(column)
)"   ! PyGTK !        Apache
gtk.main()
if __name__ == "__main__":
l = Apacheogiewer()
l.main()
    ' &   
! '     Apache
   ' & $ &
Apacheogiewer
  

object
.  "    ?  %      ,   
 ? &     %  !%    ! .
Y  
__init__()
 $  & ? .      &
 & % &  %        ,  
 ,   , % $ #  $
 $  . H %  
$ , %  '  # $  640
480,  $   
  $  #  . @ &  &     $    
       . 640
480   # $ %#
$ ,     % #   (
 $% &   %. &
$  640
480   % (  ",  %    #" ,  %" ,
     $   .
$ &, %   %#&
    $   640
480 + ( ( $  - %  &
(  "    .      PyGT\   '  
 '   ' # $ 
maximie()
.    ,  #$  
 '    #&    #" # $       % 
&,     #  $ 
# (  $  .
   $ &     &  $     $     
Box
. |  #,  & ,     # $   ,  
 &&       ? .   GT\  #$
&  &  #$ &       # +
Box
-   
$  # +
HBox
- $    $#(     + ' -
  .    $%   (       , % 
    & # (  ' ,   & (  % + (
&
Box
   &
HBox
-      .     
'  $  & %     !%    ! ,
          &.   #$   ( 
   '   ' #  '     %     
      .   #    && &   ,
     #   ,        '  
& #      .
   &  
Box
   &   #  
      .      #       
$    #    ,  
  &   &  
&      . Y   $     &   ,
      %      %    . ; 
 ,  &       #    . Y&  &
 '    #    
Toolbar
 #$ & 
insert()
  '  #, %  
pack_start()
 
Box
 11. )"      
Y   $    '   ! ,   $   
 # ! '  &   
,  &$     % 
  &.    %   %   '  ,        
&  .
   $ &  '    !    $      
 ,    ' #    $ ! '. |  
     $ ( % : ? ( & ( +   
ist
Store
-  $#    +
Treeiew
-,    #$  # 
$    #.     ( & (  $  &  
,     &   
( & '    .   
 $   $#     &$       ( 
 $        $  &        
% &  # ,   %    '  ? & &  
 . H       $    #
Box
 #   
,  '   !    %   #.  ,  
'    $ ! ',  &    % 
 #,  & %    #"  %       ' 
 % # (.
 $ %       '   ,     
.    &      #  
show_all()
|        '     . D% 
&, %   $    '   !%    !  ,   
(  , %   '   !   &   ,  
 #$  #        open +  #-.    
 '     $ &      .
    '  ,   '   #&, %     
"   %#   &. H  '   #  
 # '  ! '. '         ,
& (  ,   &&  %     (     
   &         ,        ' 
  !  #  ,   $&    .    , 
 '   & #       
   ,      
     $   .
    % $ $     !"
%  '    Apache :; curses
curses   ,  %&  $    (  
'      !  .  %  !%  
  !  curses   '  #     
! &    $ .    % $  %   
 #$  &  $   ,     GT\ $ %  % &
   #$  &   &  ' ,    
)"   ! ! Apache  $" curses
399
$ !   %    $      . { 
 $%  '  curses     $ & !%   
!  $ % &  , %   #$   !
%    !   &  '       
 $ &    $ #& '      
   .   #$    curses  % 
 & $ #&       .
   11.3   &    &      !
 '     Apache,  $ &   #$    
& curses, ( &       
     &$  Python.
% .F.  curses "  %  &  
-�   Qpache
#!/usr/bin/env python
-- -     +    Apache,    
++  curses
 3:
curses_log_viewer.py logfile
 - + 7     ,  -   
  -   .       3 X 
  -  -X - Q:
u/d    X/
t       
~   3 + 
b/h/s   3     + /-  X /  
r   3  3   
import curses
from apache_log_parser_regex import dictify_logline
import sys
import operator
class Cursesogiewer(object):
def __init__(self, logfile=None):
self.screen = curses.initscr()
self.curr_topline = 0
self.logfile = logfile
self.loglines = []
def page_up(self):
self.curr_topline = self.curr_topline (2 * curses.INES)
if self.curr_topline 0:
self.curr_topline = 0
self.draw_loglines()
400
 11. )"      
def page_down(self):
self.draw_loglines()
def top(self):
self.curr_topline = 0
self.draw_loglines()
def sortby(self, field):
)"   ! ! Apache  $" curses
while True:
402
 11. )"      
   (  $ $ % $   
page_up()

page_down()
,  
    . H
page_down()
  $ 
draw_loglines()
       , %&      
 (   $    . 
 '      
   &  &   . H
draw_loglines()
   #
  ,  #     &    ,      $  
 # %  %           (   $ 
  .        $ 
draw_loglines()
 $  $#
 !!    $  
'  ! '. H
page_up()
% $%   
 ,   '   
  " ,  $   $     $    
draw_loglines()
. |  $  $# !!     ( 
 '  ! '. %,     
page_up()
  $% &   ,   ' &     " ,
    , %            &   , 
  ' & $  . @   &   &  ' 
&    $.
   "    $     . H  
           (  ,    &&  %  
 ,  (    $ . /&        
  $   
sortby()
sortby()
   
  ? 
Cursesogiewer
  $   ,   %  $

top()
top()
$%         
 $    %       + &    
  -.
    %   &  "   '   & $
 "     ' &.    %    (   
       , %  $ &  
main_loop()
  #   ! 
wrapper()
, &    %  #  $
        '   .
;  &  , %  %          
 ' &      , 
   , &  $  ' 
&  $   curses " #  ' #  #" .
 $ ' ,      ( 
  #  $  #      
       . ),  '  #, $$  (   
 $  #     !%  (    . ),  $ ' ,
$$  , % " #   #          
,    ' #   , % " #   #
 #"  .     ,    $  ,   $  #
 ' &  $ curses,  ' $ #&   $.
; . 11.3  $  "   ' &    ! '
,          
  %    (
 .
 $ %" ,   '         '  ,
  $  #        & ,     .   #
 *;  !
403
   %   ,      $    $ '  
%  &.    %"   '   $  #
     !    %     '. | ' 
% #  ' ,   $    $ '     '   $
%  &  %   ' &.
 $ #, %  #  , $%   #" #   $ 
.  # $   ' &,     #$ ' 
  .  %         ' F   (,   
' & % & "     . | $% , %   $
  &   ' &  ,       ,
 '    $ #    URL     $    #$  #& .
 #$  &    & %  $' #    #, $
#   &  $  +      '    -,
   ]lash. |      # 
    # &  #$ 
  .   (,   ' &      #&  $
        & , %  $ &  (  #$   .
| $% , %     +    ' &-  '  
 #  $  ' &  $    % &    
  + #$  &-. &    #      , #
    #  !
  #  $ '  , 
      #   #$  &. ; ,  "  $
   '   &    "   ]lash,   
'     #  #$   
   #     " 
.11.3.
?" % &   -�   Qpache
404
 11. )"      
&,   "        #  . { '  
    &,  $ '  #  $   '    
 &   #  &  (   , ( &  #$  ,  
  ,  $    & .   #(,  $    &   
 $% #      #
  ! .   % ,   &
         % 
        '   $ 
,    #"  % ,      #$  #  
# " &,   '  ,       
$           
,  %    &  
  #     $            . |   
   #  ' && &   #  &  (   .  
    $ %   &  ' #     #" 
, %    % #      #  ' &  $%(
 $ (. K  #$   &  #$  #&  ' &,  
& $    .
; #  ' & ,  &       F
 %,   #   #$  $ &  ' 
!%    !  ,   
    & &    
' &.  $       '  &  (  
        , %   ' &     ! 
            " ,     
 & &. |      #   '   (  
 "   &    & 
   ,  ' 
 #$   ,   ' %  ($     & % 
. K   $ % (  &     &     
  .
 #   & #&, %   '   #$  #&    
  , ( &        ' &,    $  &
 &  & "(  #$   ,    #   !! . )  ,
        '  #$  # &  $ &   
' F   #     &$ Python, ,  % ' ,  
     #$  #  " &,    &$ Python. ; %
$ (  #F  $        , %     #
'  !  & $    '   &$ Python,  #
    .   &  &    '  $
 %  $ ( TurboGears, [jango, Pylons  Zope. D '  $
 ( %  (  !    &  
  ,   " $& ,
 !  [jango %" (        .
Fjango
[jango    !  #&  !  & $   
 ' .   '    & " ,  ($
   &  $ (      ?   &  
  ,  % ' ,  &$ Python &  $    
 ' . J %   !  #   !  , [jango  '
Django
405
 #$  ( MT +Modeliew
Template  #    
" -.  (  #    "   ( ',    
% ,      (  Mq +Modeliewqontroller  #
        -.   
  $ & $  #  
 ' &  , %    " # %   ' .  
 $  &  $  (   ( %&(   &
   #  #, & $ &  #. J$  
   & &   #, & $ &     
MT        Mq. K  "  !   & &
  #, & $ & "    MT     
 Mq.
%  $     !" % 
      ,   &  $   # ( !    
  ,   $      '  &   
! '     Apache,  % , %   
$   $   PyGT\. @     &  #
! ' , %   $  #  #$  &    #   
  # (,      &  #& $ ( "
   "   (
    % & $ 
(.  ' %    # '   ,   ' 
,   $  #    '   [jango.
$ # [jango  '    :
http:44www.djangoproject.com4
    &  (         & 0.96. 
        #   $   $ .  
$$   !    & %   
406
 11. )"      
dj_apache
__init__.py
manage.py
Django
407
views.py
manage.py
408
 11. )"      
log_dir = '/var/log/apache2'
Django
$  # '       ',  !  :
  
 _X
  _+ 
      '.   ! &
view_log()
     ' ,    %  $ URL,  % 
 $        .  $ %  ! &
view_log()
  
  %   " 
view_logfile.html
& ' &.
{    , %   #   #,   $  # " ,  
 #$ & ! &    & & ' & ! 
. }    !  [jango     #  " 
,  & %   " &   #       #$ 
&     % &  $  "     .  
   $   " ,  && &   #  & (
( "  . | "    & #   " 
& ( ( "     ' . )       %
     . | " 
base.html
, (      &
  11.9.
% .9. #+& '- Django (base.html)
html�
hea�d
tit�le
{% block title %}Apache ogviewer File isting{% endblock %}
/title�
/head�
bod�y
div�a href="/"�og Directory/a�/d�iv
{% block content %}Empty Content Block{% endblock %}
/body�
/htm�l
| % #    $  " .  $ ' ,  &   &  
 VTML,  #  '  % #. {      
,    & $ #   ,   $  block:
title  content.       #  "   & & $
 block, %  "   %  $ '  # $  #   
      '. |  $ & $  #  ' 
 %,   '  # $    %   "  . J
title  $ & %     & # $%  , 
 ' #&  
tit�le
. J content  % 
   &   $     $   & $  
  # % #  .
   11.10   & " ,    #     &
 !    $     .
% .5. - Django " +"   & (list_files.html)
{% extends "base.html" %}
{% block title %}Apache ogviewer File isting{% endblock %}
410
 11. )"      
{% block content %}
ul�
{% for f in file_list %}
li�a href="/viewlog/linesort/{{ f }}/" �{{ f }}�/a/�li
{% endfor %}
/u�l
{% endblock %}
; .11.4  $ ,  &       ! .
   "    $ , % "&  "  base.html.
|  $ &  #$  #  ,
%     $   "  ,
 % #      ,     ,    
 & # (    . )          title
content.   content     & & (  ' 
     
file_list
, &     " . Y& ' 
      
file_list
 $  &  ,   $#   % 
         ! '.
}     11.11  % $  $   ,  
 $   $ "         11.10.  
'  '   ! '.
% .. - Django " +" " % &
(view_logfile.html)
{% extends "base.html" %}
{% block title %}Apache ogviewer File iewer{% endblock %}
{% block content %}
table border="1"�
�tr
t�da href="/viewlog/status/{{ filename }}/�"Status/�a/t�d
t�da href="/viewlog/remote_host/{{ filename }}/"�
Remote Host/a�/td�
.11.4.
? &   -�   Qpache
Django
411
t�da href="/viewlog/bytes_sent/{{ filename }}/"�Bytes Sent/�a/�td
t�da href="/viewlog/linesort/{{ filename }}/"�ine/�a/t�d
/tr�
{% for l in loglines %}
�tr
t�d{{ l.status }}/t�d
t�d{{ l.remote_host }}/t�d
t�d{{ l.bytes_sent }}/td�
t�dpr�e{{ l.logline }}/pr�e/t�d
/tr�
{% endfor %}
/tab�le
{% endblock %}
}     11.11  
$  " ,  "&
" ,   $      content.     
  ' '   :   &&,    (  ,
%    (         $ ! '.
  &  '  , $         #$  
  $ '  #  & #            .
; ,   #$  #  
  $     Bytes
Sent +    - +  && & %   -,  
    $'    
       &
         Bytes Sent. %  $   
   , $  %   Line,    #   
            &  $ &. %  $ 
  Line   $    %#   &   
&   .
; . 11.5  $ ,  &     ' &  
#  &   &  
,   . 11.6  & 
      &         Bytes Sent.
|  % #     '  ,      $  ! 
 [jango.    #        %  '  .
J #"   '  [jango  &     
$ (. Y  '   '     "   
 #,                 & ,
!#      $% 
    &&     
(  , !#     
&  & %   
 (      % ,  $ '  #   # $
% !#         # (  $ '  & ( 
  A`AX. ;      & #      "   &
   ( %    %     & #  ' &.
412
 11. )"      
.11.5.
% " % &   -�   Qpache
     % %  
.11.6.
% " % &   -�   Qpache
       +0 -&
Django
413
   %  ' 
"  '   , %     '    ! 
[jango && &     %     #$ &, 
    #$
$ (.      #"  
   %   #$  [jango,      
    %    #    .   #$ 
[jango &  $ &  ' &,    % #& $
(, %  $  & "  & ' & (, (&
(&  $ (,   ' ! ,  &      
  (,  (  #$   .        
$ ,   $  &  # $ (   #$   ?  
 & (    !  [jango,   '   $  &
"     & ' & (,   ( 
 #&          !   ! 
[jango. ~ #    (      , %   $ # , 
      '  $  #  !  &    $  (,
  $    #      #  .
 '  ,    $  ,   &     ' 
  $ # (  .  %   ,   ' 
  $ & #   #  $ ( #   (  ,
   IP  , 
  %   ',  
 & &  (,   % # 
     % &,   & 
  ,     .
         ,    '   &,
%   $  #    '  [jango. ;'  & & 
  &          
django
admin
,  $ 
    '  :
jmjonesYdinkbuntu:/code$ django admin startproject sysmanage
jmjonesYdinkbuntu:/code$ cd sysmanage
jmjonesYdinkbuntu:/code/sysmanage$ django admin startapp inventory
jmjonesYdinkbuntu:/code/sysmanage$
|     $   %      ,      
     ' & &  
  ! '    
Apache. ;'   &        ! ,  
 $ :
jmjonesYdinkbuntu:/code/sysmanage$ cd ../
jmjonesYdinkbuntu:/code$ tree sysmanage/
sysmanage/
__init__.py
inventory
__init__.py
models.py
views.py
manage.py
414
 11. )"      
Django
415
Y   (     # '  URL,  %  
  %      ! . ;'   &  
  &    $ !     URL:
# --    @7@    @  -     
(r'admin/', include('django.contrib.admin.urls')),
)   ,  $ " !
urls.py
,          , &
 %      ! ,         &
     #.    , %   % #    
  ! ,      
,  &"  %   .
@  #,       $ (,   ' &  
     !     $     
  !   !  !
urls.py
,  '  
 #    (  $ (.   #$   ! 
 [jango & '   ' &  & &  &    &
( .     '   ' &,    % inventory,
   !    
models.py
,  '   & 
    ,     #$  #&  '  .  [jango,
   (  ! ( $    ' , (&
  #$  ?   & (   +ObjectRelation
Mapping, ORM-,    $ '  $  #   #$  # $ 
(,      SQL' &. H ($ ORM  ! 
 [jango     ,         
  ( . ; ,   !     
&& &          $ ( + !
  && & % #      &,     
  -:
class HardwareComponent(models.Model):
manufacturer = models.CharField(max_length=50)
#   X   ,    ...
type = models.CharField(max_length=50)
model = models.CharField(max_length=50, blank=True, null=True)
vendor_part_number = models.CharField(max_length=50,
blank=True, null=True)
description = models.TextField(blank=True, null=True)
   , % 
HardwareComponent
  
Model
 !  [jango. | $% , % 
HardwareComponent
  
& 
Model
          . '  
            #   :
manufacturer
+ $  #-,
type
+ -,
model
+ #-,
vendor_part_number
+ 
   - 
description
+  -.  $&  (    ( 
 &     !  [jango. ; ,  !     & 
   % #  $   ,    $ 
CharField
@       ' 
inventory
 $  
inventory_hardwarecomponent
 "  #  :
manufacturer
type
model
vendor_part_number

description
.  %    %    
416
 11. )"      
       & ORM. * %    ?&
 
/
        & ORM.   
 & &   ,  !  [jango  $     
     ,   & $    ' & +  
 '     -, $       %  & 
&  +    '  '     -.    , 
     ,  !   $   "     #
   
,    #  #  %  %. ;'
  &  &$ SQL, 
$  , &   
 #      
HardwareComponent
CREATE TABE "inventory_hardwarecomponent" (
"id" integer NOT NU PRIMAR E,
"manufacturer" varchar(50) NOT NU,
"type" varchar(50) NOT NU,
"model" varchar(50) NU,
"vendor_part_number" varchar(50) NU,
"description" text NU
{    #    &  #  &$ SQL, 
  !   #$ &  $ & $ (,   $
        
python manage.py s~l myapp
,  
 
myapp
       ' &.
@  #,     $ #  ORM  !  [jango,   
 %  $  $    $ ( & "   ' &
  $.    11.12   &  ' !
model.py
&  ' & inventory.
% .=. ?0% -#+ "+0 (models.py)
from django.db import models
#   3  - .
class OperatingSystem(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
class Admin:
pass
class Service(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
class Admin:
pass
Django
417
class HardwareComponent(models.Model):
manufacturer = models.CharField(max_length=50)
#   X   ,    ...
type = models.CharField(max_length=50)
model = models.CharField(max_length=50, blank=True, null=True)
vendor_part_number = models.CharField(max_length=50,
blank=True, null=True)
description = models.TextField(blank=True, null=True)
def __str__(self):
return self.manufacturer
class Admin:
pass
class Server(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
os = models.Foreigney(OperatingSystem)
services = models.ManyToManyField(Service)
hardware_component = models.ManyToManyField(HardwareComponent)
def __str__(self):
return self.name
class Admin:
pass
class IPAddress(models.Model):
address = models.TextField(blank=True, null=True)
server = models.Foreigney(Server)
def __str__(self):
return self.address
class Admin:
pass
Y& "       & #  :
OperatingSystem
vice
HardwareComponent
Server

IPAddress
. 
OperatingSystem
 $ &
  & # $%      &    , 
   %  #&  '     $.    
      :
name

description
,    #
   (  . H '    $  # 
OperatingSystem
endor
   #       
OperatingSystem
,    
 (  ( &      &        
 $        . '       
    #   &   
&  . H  '   
 "   '             ,     
  # 

Service
 $ &   % #  ',    
 & #&     .  %       ( '  ' 
$ #     Apache,         %  Postfix,   
418
 11. )"      
[NS Bind     OpenSSV.   
OperatingSystem
,  
    :
name

description
. '      '  #
 '   '. H  '   " &  '    ,
      # 
Server

HerdwareComponent
  &   (  (  
  ,     ' #&     . |    
 & #   , #    &    
           % ,        $
#(    .  
HardwareComponent
   & #
  :
manufacturer
type
vendor_part_number

description
. 
  %  $         ,  '    $
 # #  & &  $        
    % &,  $  &$ # (  " &. ; & # ' ,  
 ( &       %   $  #    " &.

Server
       $. '   $ 
& 
Server
 #   , !    
  .  Server    ,  ( & &  &$   
 &  " &   &    .  '   ,
  '       
name

description
.    %
       ( (.     #  " 
&   ,   (   $ #  
Server
, 
       " &. '       # # 
     ,      $    "    
OperatingSystem
  "  % +foreign key-.   #   
$&    &        &  ,  " 
         &   ,      
   & "     &. ;     '  & #&
 '   ',  '     '   '  & #&
  (   (,     '  
Server

Service
  $ 
  "      . @ %  ' '    
 '  ' #  '    (    ,    '
         '  #       '  
   .    
Server

HardwareComponent
  ' &$
 "       .
;  , 
IPAddress
   ( IP     (    ,
 '  # % . H      #    ,
%   %   #  " &  '  IP      . 
IPAddress
       "  . K 
address
 
' IP    ! 
XXX.XXX.XXX.XXX
. H '  
IPAdd
ress

Server
    "    "  %,  
%  IP    '   ' # #     . Y, 
&  "     ,      &  &   
    &  "   '      ( [jango.
@  #     $  ! $ ( slite. { $  #
 
python manage.py syncdb
     ,   $   
Django
419
    &  ' ,  % (  !
420
 11. )"      
  $  ,   &   '  $  #     # [jango.
),   ,    % #  ' .
; ,        #  % # #  
& '        ,       ,
'    ,       $  #. {     
  #  #  $ '  #    #    $  (    
 % #     ,  (   (   , 
 '     $  #  . )        #  #
 $ '  #    #    $       % #   
!   ,      $  #   . Y  # 
  . Y        
  %#   &.
.11.7.
? A  A   0"  "% +&
 & Django
.11.8.
  A "%   & Django
Django
421
Y& %    11.13   &    !
urls.py
% .F. -  "  |\[ (urls.py)
from django.conf.urls.defaults import *
urlpatterns = patterns('',
# - :
# (r'sysmanage/', include('sysmanage.foo.urls')),
# --    @  -     
(r'admin/', include('django.contrib.admin.urls')),
(r'$', 'sysmanage.inventory.views.main'),
(r'categoried/(|Pcategor�y.*|)/(|Pcategory_i�d.*|)/$',
'sysmanage.inventory.views.categoried'),
(r'server_detail/(|Pserver_i�d.*|)/$',
'sysmanage.inventory.views.server_detail'),
H        & ' &  (     URL 
! .  #  %   %       '  
   ! '     Apache. H $   
URL,      & ' &,  ! , 
    #$    &( ' &(    
  .
.11.9.
 % "-   %
 "% %  & Django
422
 11. )"      
  , %    ,     #
views
! , 
  ?&   ! ' &     URL.   
 11.14   &  '  &
views
% .G.  A  "    #A
(views.py)
#   3     .
from django.shortcuts import render_to_response
import models
def main(re~uest):
os_list = models.OperatingSystem.objects.all()
svc_list = models.Service.objects.all()
hardware_list = models.HardwareComponent.objects.all()
Django
423
% .6. +& '- (main.html)
{% extends "base.html" %}
{% block title %}Server Inventory Category iew{% endblock %}
{% block content %}
di�v
�h2Operating Systems/h2�
�ul
{% for o in os_list %}
l�ia href="/categoried/os/{{ o.id }}/" �{{ o.name }}�/a/li�
{% endfor %}
/ul�
/div�
di�v
�h2Services/h�2
�ul
{% for s in svc_list %}
l�ia href="/categoried/svc/{{ s.id }}/"� {{ s.name }}/a�/l�i
{% endfor %}
/ul�
/div�
di�v
�h2Hardware Components/h2�
�ul
{% for h in hardware_list %}
l�i
a href="/categoried/hw/{{ h.id }}/" �{{ h.manufacturer }}/a�
/li�
{% endfor %}
/u�l
/div�
{% endblock %}
| "    ' %   '  .      
% ,    & '    , & ' ' #&.
 '       &        ,  
&  (,  '  % #   (    ,   
'  $    .
    #$  #       $  (  , $ &
 & ! &    &
categoried()
 "     !     &
categoried()
 
  +
 %      ,
 %   
    
svc
 % '- 
   +  #   
    ,         % ,  , 3qom
905b Network qard-. * &
categoried()
    
  $  $ $ (   (    ,  '( 
    .   $    % & !  $ $
( ! &
categoried()
    %   & " 
424
 11. )"      
 categorized.html.    11.16   &  ' "
  categorized.html.
% .;. -   (categorized.html)
{% extends "base.html" %}
{% block title %}Server ist{% endblock %}
{% block content %}
h1�{{ category }}::{{ category_name }}/h1�
di�v
�ul
{% for s in server_list %}
l�ia href="/server_detail/{{ s.id }}/"� {{ s.name }}/�a/l�i
{% endfor %}
/ul�
/div�
{% endblock %}
}  categorized.html '   (    ,  
%  ! 
categoried()
     #$  #  '  
 #       , %
 $  !     &
server_detail()
. * &
   &
Django
425
�ul
{% for service in server.services.all %}
l�i{{ service.name }}/li�
{% endfor %}
/ul�
/div�
di�v
div�Hardware:/di�v
�ul
{% for hw in server.hardware_component.all %}
l�i{{ hw.manufacturer }} {{ hw.type }} {{ hw.model }}/�li
{% endfor %}
/ul�
/div�
di�v
div�IP Addresses:/di�v
�ul
{% for ip in server.ipaddress_set.all %}
l�i{{ ip.address }}/l�i
{% endfor %}
/ul�
/div�
{% endblock %}
|    $ ,   $  #  #    ' 
$ (,  #$&  !  [jango. K    
!    %  $ '  #   & $ (,  
            ,     $  #  
      &,  $ &
    #      
 #&  ,   $  . 11.10, 11.11  11.12.
.11.10.
  A     %%
426
 11. )"      
 ; 
;  &  , %  $   '   !%    ! 
 ,  ' &  ,  
      &$ 
 &       ,     ,    ' 
$ #&   . )     ' '
 -/
 $  #
  #    '  &   $ "(  #$  
 . )     '
 -/
 $  #  '  &  
  &. )     '   & #& , %   
 -0�
"%
,     ' &     %#   #   
$ %    .  #   %  , %  $   
'   !%    !    $   $   , 
    ,  %  % (  $  #.
.11.11.
   %%   CentVS
.11.12.
   %%  %A    
   
 (  # (    ,  #     ( 
 ( &      #
$ &. |   $  &,
%  ,  (  &  
   #$ &,   
 ,    ,  (" (, $ "    . %  
(  # (   &  
 $ & (   
!   $#   . ;  !  ,    XML 
AML,   %    & % &. ;  !  ,  
 ! $ ( Berkeley [B +bdb-  SQLite,   
&         #$ &  #.
    '     #&  (& # &     
 #$ &F  $ ' ,    &  ,    $
      $  & ! 
    ,    (   
 %   $  #  , %  $ #,   ! $ #
        $ . )! & !(   
 ,   (& & &      #$ &,
 # &    $   &.      (& #  
     ! .   #     %,  
  & #    $      ,  $ 
    #,    " $  #   '  15 
 , %   #,  #     '   #  
#    .      (& #  &    ! (
&      #$ &.    % &    
 #$ &     &   ,     " $
& #&     ( (,     ,    
,  &&   (,  & .
H $ #  " '   $ (     
:      & .
428
 12. )/ $ /
 $    $
     #      (
 & (   &   
   #$ &.     ( & (    $  
( &  "   '  % & (  $      
$ . $%&  '       &    $ 
    $  ,    &   $.
Pickle
  ,  ',      ($     $
  &$ Python       
pickle
, ( &    
       &$ . {   #   
    ,  &   % &  (       
&     , %  $    # (   &   
   #$ &. &  &      
&  $  &  &
pickle
.    #    &   '
$ # ?   , $ " #    ,   #&
 $  ,   $  #  ,  %  # ?      
' # $    #  .
   $ '  &    #
pickle
F ;'   &
 , $&  $ &  & pickle        
   &$  Python,    %   ? , 
    (& #&     #:
None, True  ]alse
~  %,    , %    % , 
  %
%         
  ',  ,  '     
,  ' # ?
,     (& #&    #  & pickle
* ,    
 (      
   ! ,   
  (      
,    
 (      
| $ &  ,  (   
__dict__

Pickle    #,   #,   #, $ " #.
%.  .
 !  "!
429
In [q]: pickle.dump(some_dict, pickle_file)
In [5]: pickle_file.close()
K   &  !   (     :
jmjonesYdinkgutsy:$ ls l some_dict.pkl
rw r r 1 jmjones jmjones z0 2008 01 20 0^:1z some_dict.pkl
jmjonesYdinkgutsy:$ cat some_dict.pkl
(dp0
S'a'
sS'b'
  '    #&
$% # !  ! ,  $  (   
pickle,   $  # ( %, 
        #  .
;'    &,    
  #  (    :
In [1]: import pickle
In [2]: pickle_file = open('some_dict.pkl', 'r')
In [z]: another_name_for_some_dict = pickle.load(pickle_file)
In [q]: another_name_for_some_dict
Out[q]: {'a': 1, 'b': 2}
   , % &   
  & (   #$ 
? , &   % &   ? ,   (
&&  ! . ; $ , % &    "#      #
&  ? .
)     #, %   "   &$ # , %   ' 
!   (&  ?       "  
 .   '  (& #      ' !  # ?
,  #    (   '      !    
 . ;'   &    ( &   # (     
  ! :
In [1]: list_of_dicts = [{str(i): i} for i in range(5)]
In [2]: list_of_dicts
Out[2]: [{'0': 0}, {'1': 1}, {'2': 2}, {'z': z}, {'q': q}]
In [z]: import pickle
In [q]: pickle_file = open('list_of_dicts.pkl', 'w')
In [5]: for d in list_of_dicts:
...: pickle.dump(d, pickle_file)
...:
...:
In [6]: pickle_file.close()
430
 12. )/ $ /
H  $     , ? !,     ' &
$, $    (        $  
'  $ (    ' !.    ,  ' 
   ( &,   #$ & " &  ( &
  ?   !, # 
   &     
$ 
dump()
  # $.
;'   &       & ?  $ !,  
'    # ? ,  (  :
In [1]: import pickle
In [2]: pickle_file = open('list_of_dicts.pkl', 'r')
In [z]: while 1:
...: try:
...: print pickle.load(pickle_file)
...: except EOFError:
...: print "EOF Error"
...: break
...:
...:
{'0': 0}
{'1': 1}
{'2': 2}
{'z': z}
{'q': q}
EOF Error
 #   $  ? !,  $          ,
    ' & % &,    &    $' # ?
 $ !,      $'   % 
EOFError
.  
 ,  ,  %  $ !, $#  ' 
+    '  & -, %   ,   $
!.
;   , %   '   (& # ?    (   (
 ,   '   '  (& # ?   $ (   .
;'   &  '  &,      #$ 
 #  (  (  (. |  #  '   
"       ,  $ &         
( #,        #:
#!/usr/bin/env python
class MyClass(object):
def __init__(self):
self.data = []
def __str__(self):
return "Custom Class MyClass Data:: %s" % str(self.data)
def add_item(self, item):
self.data.append(item)
 !  "!
   #     #  "     (&
 $ &     !    #  &
pickle
#!/usr/bin/env python
import pickle
import custom_class
my_obj = custom_class.MyClass()
my_obj.add_item(1)
my_obj.add_item(2)
my_obj.add_item(z)
pickle_file = open('custom_class.pkl', 'w')
pickle.dump(my_obj, pickle_file)
pickle_file.close()
           #  "  ,  $ 
 $ &   ,   ?   #    , $
  $   .           # %  
  .
Y   &  #,      #  "
   $  $'  $ &    $ !:
#!/usr/bin/env python
import pickle
import custom_class
pickle_file = open('custom_class.pkl', 'r')
my_obj = pickle.load(pickle_file)
print my_obj
pickle_file.close()
;'   &  ,  % 
  (     & (
$ !:
jmjonesYdinkgutsy:/code$ python custom_class_unpickle.py
Custom Class MyClass Data:: [1, 2, z]
Y&    ,  &       (,  
 "   &$ # &     # " . 
'   #  $ '  #   #  #,     & &
" . ;'   &  #,       #
     :
#!/usr/bin/env python
import pickle
##import custom_class ## Q -   --  
pickle_file = open('custom_class.pkl', 'r')
my_obj = pickle.load(pickle_file)
print my_obj
pickle_file.close()
432
 12. )/ $ /
;'   &  ,  % 
   $#  $   &,
     :
jmjonesYdinkgutsy:/code$ python custom_class_unpickle_noimport.py
Custom Class MyClass Data:: [1, 2, z]
K  %   %   '    &,     
!            ,    
$ :
jmjonesYdinkgutsy:/code/cantfind$ python custom_class_unpickle_noimport.py
Traceback (most recent call last):
File "custom_class_unpickle_noimport.py", line ^, in module�
my_obj = pickle.load(pickle_file)
File "/usr/lib/python2.5/pickle.py", line 1z^0, in load
 !  "!
In [^]: default_pickle_file.close()
In [8]: binary_pickle_file.close()
  !  ,  $   +   
default.pkl
-, 
 ' #   !    %,  %     
%    &  & &.    ! +   
binary.pkl
-   
' #    %  !  .    , %  
 !
default.pkl
 %   ' & $ +
'w'
-,  !
binary.pkl
  ' $  %( ( +
'wb'
-. {   
$%  '  & $   
dump()
$ % &  , %
  (    %  !       &   
#   : %
, $% , %   #$  #&
"  ,    &  & && &  %
 .
;'   & "    %   %  !  
jmjonesYdinkgutsy:/code$ hexcat binary.pkl
00000000 80 02 ^d ^1 00 55 01 61 ^1 01 qb 01 ^z 2e ..}~.U.a~..s.
K  &  "    %  !  ,  (
    #$      %:
jmjonesYdinkgutsy:/code$ hexcat default.pkl
00000000 28 6q ^0 z0 0a 5z 2^ 61 2^ 0a ^0 z1 0a q9 z1 0a (dp0.S'a'.p1.I1.
00000010 ^z 2e s.
            (   ,   % 
 '    #$  #&      
, %   %  #  
' !  ,  (    #$   
   %:
jmjonesYdinkgutsy:/code$ cat default.pkl
(dp0
S'a'
cPickle
       &$  Python       
$&   Pickle, &    , %      
 .  $ &
cPickle
.  &  $  ,  
cPickle
 $   &$ q.   '    & #
 % !   %&(,    % $ % #, %   (
  ?    &      &.    ' %  '
    #  #$  #  #
cPickle
. ) !   &
cPickle
 %        !  %   &
pickle
434
 12. )/ $ /
shelve
{   $ '  #  ( & (   &  #
shelve
. H #
shelve
        ! ,  
  $ '  #  ( &  '   ? .     $
  &  $ '  #  ( &  '   ?      
' ? (     (     & $ (.
 (  ?   (
shelve
   #$ 
 &  &$ Python. ;' 
 &  ,    
 & ( ,    $
 &  , $  (  
   &  $   $  &  (   :
In [1]: import shelve
In [2]: d = shelve.open('example.s')
In [z]: d
Out[z]: {}
In [q]: d['key'] = 'some value'
In [5]: d.close()
In [6]: d2 = shelve.open('example.s')
In [^]: d2
Out[^]: {'key': 'some value'}
{    %  '   #$  
shelve
     
&     , % ?
shelve
 $  &    #  
shelve.open()
,      $ &  $ & 
dict
    
# !(   +
-. {  %     , % 
 #$ 
shelve
 $ "       ( 
$ # 
close()
? 
shelve
D ? 
shelve
 &      .
   $ (  '
 :  $ "       (  $ #

close()
. {      #,  $  &,  
    ?
shelve
,     ( . ;'   &
    ( $$  , % ?
shelve
 $  &.
Y& %  '  $  # ?
shelve
,  ( #    
   $   %  IPython:
In [1]: import shelve
In [2]: d = shelve.open('lossy.s')
In [z]: d['key'] = 'this is a key that will persist'
In [q]: d
Out[q]: {'key': 'this is a key that will persist'}
In [5]: d.close()
In [6]:
Do you really want to exit ([y]/n)|
 !  "!
@  #   $  IPython,   ' ! (,  $
            ,  $  ?
shelve
In [1]: import shelve
In [2]: d = shelve.open('lossy.s')
In [z]: d
Out[z]: {'key': 'this is a key that will persist'}
In [q]: d['another_key'] = 'this is an entry that will not persist'
In [5]:
Do you really want to exit ([y]/n)|
@  #   $    %  IPython,    ' ! (
    , %     &:
In [1]: import shelve
In [2]: d = shelve.open('lossy.s')
In [z]: d
Out[z]: {'key': 'this is a key that will persist'}
)  ,  (  $ # 
close()
&  ( ? 
shelve
,  
' (   & ,    (  #   ( #.
Y&     #  & $ & ( ? .   , %
$ &  ?  $ &   ? , $%  
(  ' $ & #  $     &   $% &  
   . ;'   $   ?
shelve
, &        ,
   &    $ &
 ? +   %
 -,  !  $ &  ? ,  $  $   ?

shelve
In [1]: import shelve
In [2]: d = shelve.open('mutable_lossy.s')
In [z]: d['key'] = []
In [q]: d['key'].append(1)
In [5]: d.close()
In [6]:
Do you really want to exit ([y]/n)|
  #     % $ & 
close()
? 
shelve
 '   '  #, % $%   %
'key'
 
[1]
;    . ;'   &  $#      # ! (
,  $   " ,   %  # $    :
In [1]: import shelve
In [2]: d = shelve.open('mutable_lossy.s')
In [z]: d
Out[z]: {'key': []}
436
 12. )/ $ /
       %       '   .   
#         #
shelve
    .   
    , %  ! &  (& ( $ & ( ? 
   &   %.         ,
 $ &(        .   $ (  $ 
  $  ,    "    ? .
 ,  $ ,  ( $ % &  , %   
   #      %  ?
shelve
, 
 $ ' :
In [1]: import shelve
In [2]: d = shelve.open('mutable_nonlossy.s')
In [z]: d['key'] = []
In [q]: temp_list = d['key']
In [5]: temp_list.append(1)
In [6]: d['key'] = temp_list
In [^]: d.close()
In [8]:
Do you really want to exit ([y]/n)|
       #  (   ?   %
  :
In [1]: import shelve
In [2]: d = shelve.open('mutable_nonlossy.s')
In [z]: d
Out[z]: {'key': [1]}
 ,         ,  (&.
  , "    ?   ( $ % &  $  
!
writeback
? 
shelve
. Y (        $ 
 
shelve.open()
          ! (
. ;    '  #     , 
 $ ( && & !
writeback
. {  !
writeback
  
 $% 
True
,  $  ?
shelve
,   &
 #   , " &  &   $   (& &  $ 
  
close()
. |    ' $ #&    
$ &  ? ,  $  (  &   #.   # 
 ? ,   $  #   , " &  $
  (& &  $   ?  + $  , $ &
#    -, ?   #$   &    &  $#
!        # % ?   ( ,
  $ &  .   ,     &  #"
% ?   ( ,  (  &  #&,
%"    # !
writeback
 $% 
True
 !  "!
           !
writeback
$% 
True
  !   '  ,   &&    
 %  ?
shelve
In [1]: import shelve
In [2]: d = shelve.open('mutable_nonlossy.s', writeback=True)
In [z]: d['key'] = []
In [q]: d['key'].append(1)
In [5]: d.close()
In [6]:
Do you really want to exit ([y]/n)|
K  #   ,  (#  " $  &:
In [1]: import shelve
In [2]: d = shelve.open('mutable_nonlossy.s')
In [z]: d
Out[z]: {'key': [1]}
    &#, $  &   ( .
H #
shelve
         ( & (.   
 &     ,       % #   $  #.
]AML
 $    ,  $  &   ,   ' " # $
  &    AML,  : AML aint markup
language +AML   &$ $ -  yet another markup
language +   &$ $ -.    %  ! 
(,  %  #$ & &  ( &,     &
   & (     
 . |   %  
 (%     .    ,  ',     
 #   AML  &$ Pyth
on     , %     #
   #   
easy_install

PyAM
. ; $%    #$ 
 # AML,     &   #,      
&     #
pickle
F       %, 
 AML $ &   %  # , % 
pickle
%      A
ML %"   (  &(,
    (  & # (       $%
  #.   (, !  AML   &  & & %   .
{         ! ( ! . {
    $   ,  
 (     #  $ '
  #    & ! ( ! , AML  %
   .   (,   %   $  &$  AML
 $    ( ( &$ (. {    &   % #
    '   '    &$ Python   '  ,
438
 12. )/ $ /
     &$  
 &, AML  '   #
  (  "     .
     
PyAM
  %  $ '
 #  (& #    
 #   !  AML. ;'   &    (
 &     &:
In [1]: import yaml
In [2]: yaml_file = open('test.yaml', 'w')
In [z]: d = {'foo': 'a', 'bar': 'b', 'bam': [1, 2,z]}
In [q]: yaml.dump(d, yaml_file, default_flow_style=False)
In [5]: yaml_file.close()
|     %   , %     $  #&    
  & # , ,     ,     .   , % $ #
 &,  & &      & AML +   
yaml
-.    & !   ' & $,   
 #$  #& &  ( & (
. Y  $  &  # +  
 
-,  '  ,    &  ( #.    
   (&   # +   
-    # ! 
dump()
$
 &
yaml
.  %      ! 
dump()
   &:  
#,    &  ( #, (   !   ,  
  AML, % $# '  $  #&   %
    ,      , $     %,  %  
   $   (&   ?  (    .
;'  $ ,  &   ' !    ! 
AML:
jmjonesYdinkgutsy:/code$ cat test.yaml
bam:
bar: b
foo: a
    (      #  ,   &   , 
  , %  &#         ! 
dump()
. ;'  $ ,   % #  $ ! AML:
In [1]: import yaml
In [2]: yaml_file = open('test.yaml', 'r')
In [z]: yaml.load(yaml_file)
Out[z]: {'bam': [1, 2, z], 'bar': 'b', 'foo': 'a'}
      !  
dump()
,  %      #
 '  &$  AML +
yaml
-.    $   ? !. ; 
$    !     ' & % &. ;   $
 !  "!
 & ! &
load()
$  &
yaml
. * &
load()
 $  
#,     (    .
  &     &  , %   #$   &
yaml
  $    $ & (,  ( & (   , $
     &       .
 $ ' ,   &$ #  (& #     !  , 
  &  & & %   ,         ( #  
# $          %   ' . ;'  $ ,
  ( # '   #    %   ' :
In [1]: import yaml
In [2]: yaml_file = open('nonblock.yaml', 'w')
In [z]: d = {'foo': 'a', 'bar': 'b', 'bam': [1, 2,z]}
In [q]: yaml.dump(d, yaml_file)
In [5]: yaml_file.close()
  &   ' !    !  AML:
jmjonesYdinkgutsy:/code$ cat nonblock.yaml
bam: [1, 2, z]
bar: b
foo: a
% #  ( '   ' !, $    %   ' ,
$  %     $%      
. $%&  ' 
   ' %  && #&   &     #
(     '        (,  ( 
,  (      .      , % 
 # $%&. ;  ' $ , %   #   
  ,  $ #&    AML!     #  
cat
. K   !   ! 
dump()
$  &
yaml
&& &
 &$ #. +* %       PyAML ? 
file $ & stream + -,     #    #"   
    .- { ! &
dump()
  %    ! 
+  -,    $  ?    
    .             
   ?  
file
    $#    ! .
;'  &      (,   
$ &   %      %   '(.   (,    
  
default_flow_style
,  #$ &  %  ' ! 
 &,    (,   
default_flow_style
   ,
 #$ &   %  ' !   &:
In [1]: import yaml
In [2]: d = {'first': {'second': {'third': {'fourth': 'a'}}}}
In [z]: print yaml.dump(d, default_flow_style=False)
440
 12. )/ $ /
first:
second:
third:
fourth: a
In [q]: print yaml.dump(d)
first:
second:
third: {fourth: a}
In [5]: d2 = [{'a': 'a'}, {'b': 'b'}, {'c': 'c'}]
In [6]: print yaml.dump(d2, default_flow_style=False)
a: a
b: b
c: c
In [^]: print yaml.dump(d2)
{a: a}
{b: b}
{c: c}
In [8]: dz = [{'a': 'a'}, {'b': 'b'}, {'c': [1, 2, z, q, 5]}]
In [9]: print yaml.dump(dz, default_flow_style=False)
a: a
b: b
c:
1
2
z
q
5
In [10]: print yaml.dump(dz)
{a: a}
{b: b}
c: [1, 2, z, q, 5]
K      &  $ 
 # "     F   
%  #
yaml
  &  %   %  ' ,    #
pickle
.        #$ & '   #
custom_class
,   #$ &        pickle.
;'   &  ' 
&,      #
custom_class
,  $   $ & 
MyClass
, &   #
     ?  $   $  :
#!/usr/bin/env python
import yaml
import custom_class
my_obj = custom_class.MyClass()
my_obj.add_item(1)
my_obj.add_item(2)
 !  "!
my_obj.add_item(z)
yaml_file = open('custom_class.yaml', 'w')
yaml.dump(my_obj, yaml_file)
yaml_file.close()
    $    #,  %    :
jmjonesYdinkgutsy:/code$ python custom_class_yaml.py
jmjonesYdinkgutsy:/code$
@  # %  . | $% , %    ,   .
;'   &  #,      :
#!/usr/bin/env python
import yaml
import custom_class
yaml_file = open('custom_class.yaml', 'r')
my_obj = yaml.load(yaml_file)
print my_obj
yaml_file.close()
|       
yaml

custom_class
,  $  ?
! & % & ( $ !,  $       
, $' ? $ !     .
    $    ,  %   :
jmjonesYdinkgutsy:/code$ python custom_class_unyaml.py
Custom Class MyClass Data:: [1, 2, z]
@ %   '  $#    %
    ,  #$   
#
pickle
,    " &      ,     ,
%  #
yaml
 &&       ,     
   #.
{      $ (        
& ZO[B. ZO[B $% Zope Object [atabase + ? & $ 
( Zope-.    "( %&(  #$  ZO[B  
 $    #  &
pickle

yaml
,  ZO[B  
 $ '  #      
"     &. ; ,
ZO[B   &  ($ 
$   %,    
  &   % #    #  (  . K     
 &   "    "  ,   '  #$  # ZEO,
      ( & ? .
J$ ( ZO[B    "
   #   $ , 
     $,   $ ,   $ &  &
    $.   
? & $ (    
%     , %    $ #  & 
442
 12. )/ $ /
$ (, ( &   $    '   #  " &
 '  ? .    ,       "#  
$    (  $ ' 
 ZO[B,     "(  
(   #"    #
shelve
, %   &  $ 
(.       "   # ZO[B  $  ,  $
      $.
D    ZO[B  & &     % $  #  
easy_install ZODBz
. H # ZO[B  & $  ,    
easy_install
  % $ " (,  $$      ,
%  (  .
Y&     "   #$ & ZO[B  $   ? (
 ZO[B       #   . ;'   &
  ,  &  $  &   :
#!/usr/bin/env python
import ZODB
import ZODB.FileStorage
import transaction
filestorage = ZODB.FileStorage.FileStorage('odb_filestorage.db')
db = ZODB.DB(filestorage)
conn = db.open()
root = conn.root()
root['list'] = ['this', 'is', 'a', 'list']
root['dict'] = {'this': 'is', 'a': 'dictionary'}
transaction.commit()
conn.close()
    pickle  AML & $    ZO[B
  &  #          #" ,  
# (   $   $  ,   #$ 
& % #   ' ( #  . |     % % 
 ,     %  #, %  '     
  ( & (. ),     ,      &   .
  (,       
#    ZO[B,   
ZODB

. +H (   $ #   #   #"
$ % . )     &,        
  !    ! , &    #   .  $  &
 %   , %      #
'   #  
! 
. ;     , &  &  ,   #,  
    % $ #   . K  #  '  #& #" .-
   $  & ?
FileStorage
,    $ & & !,
   #$  #&  $ (.    $  & ?

  % & ? 
FileStorage
.   ? $ 
(  &    #  
open()
   &    
   $  ? .          '  & #   #
 !  "!
443
?       (, %    ,  #$&  
$     #.        '   $  
&    # ! 
transaction.commit()
 $  $    
   $  ( $    
conn.close()
 #   $     ( ( +  ?
! (      -  $# (    ' 
,    '  & #&     #     #    .
         '  $ (,  
 $  %    $ !,   $     :
#!/usr/bin/env python
import ZODB
import ZODB.FileStorage
filestorage = ZODB.FileStorage.FileStorage('odb_filestorage.db')
db = ZODB.DB(filestorage)
conn = db.open()
root = conn.root()
print root.items()
conn.close()
)  $  #       ,  $ (  
  ,      #   :
jmjonesYdinkgutsy:/code$ python odb_read.py
No handlers could be found for logger "ZODB.FileStorage"
[('list', ['this', 'is', 'a', 'list']), ('dict', {'this': 'is', 'a':
'dictionary'})]
  (  ($   ( & (   
    $  (    (  ,    
 ' ,  '   &    # ZO[B.   
$      #$  # '  
MyClass
+ $  ?
&,  % -.     #$  (  ($ , 
  ?&   ,  $    $ &     $ 
      ($  $ &  ( &   . ;
'   &    ,      #$  #
 $:
#!/usr/bin/env python
import persistent
class OutOfFunds(Exception):
pass
class Account(persistent.Persistent):
def __init__(self, name, starting_balance=0):
self.name = name
self.balance = starting_balance
def __str__(self):
444
 12. )/ $ /
return "Account %s, balance %s" % (self.name, self.balance)
def __repr__(self):
return "Account %s, balance %s" % (self.name, self.balance)
def deposit(self, amount):
self.balance = amount
return self.balance
def withdraw(self, amount):
if amount� self.balance:
raise OutOfFunds
self.balance = amount
return self.balance
| % #    ,      %   $
%  &  &  '   . H  '  
  % 
OutOfFunds
, $%    ?&  $' .
 Account   
persistent.Persistent
. +  &  
&
persistent
,  & #      #     
      $%   ! 
    &,    
 &  #$  #.      $       
    #, %   #$
ZODB
F ;  . ;    ( 
 #  .- ;   persistent.Persistent  $ &
$    #     ($   % & ZO[B  $
  ( (.        $       
$    $ &      ! 
__str__
__repr__
.  $     (   . H  '  $   

deposit()

withdraw()
.    $ &  
balance
? 
     % &   #" &,  $    ,  
 $ &. H
withdraw()
  & ,   %    
 +  
balance
-,  ' %   # $ "  .
{      % , 
withdraw()
 $'   % 
OutOfFunds
,  " & " .   ,
deposit()

withdraw()
 $       %     &  .
;'   &   ,   (& # %
 :
#!/usr/bin/env python
import ZODB
import ZODB.FileStorage
import transaction
import custom_class_odb
filestorage = ZODB.FileStorage.FileStorage('odb_filestorage.db')
db = ZODB.DB(filestorage)
conn = db.open()
root = conn.root()
noah = custom_class_odb.Account('noah', 1000)
print noah
root['noah'] = noah
jeremy = custom_class_odb.Account('jeremy', 1000)
 !  "!
445
print jeremy
root['jeremy'] = jeremy
transaction.commit()
conn.close()
|    %     %         #$ 
& ZO[B,    (&  #   . @ # $ #  
           #,  $     $ & " 
   (&     ?   $ ( ZO[B. |   ?
 %
noah
 %
jeremy
, '  $ (   
1000 +   ', 1000.00,      ! ,   
 %& &   % -.
;'   &  $# 
     :
jmjonesYdinkgutsy:/code$ python odb_custom_class.py
Account noah, balance 1000
Account jeremy, balance 1000
K  $  #  #, '  ' $ (
ZO[B,  , %   %:
jmjonesYdinkgutsy:/code$ python odb_read.py
No handlers could be found for logger "ZODB.FileStorage"
[('jeremy', Account jeremy, balance 1000), ('noah', Account noah, balance
1000)]
;"    #  $   ? ,  '  #,    (
 (   &      #$ &.
K    # $ (  $  #   % (F  
" &     ,   #    $ '  . ;'
  & !  , 
 $ (,  $   ,
 &    300 +   ,  -  % 
noah

%
jeremy
#!/usr/bin/env python
import ZODB
import ZODB.FileStorage
import transaction
import custom_class_odb
filestorage = ZODB.FileStorage.FileStorage('odb_filestorage.db')
db = ZODB.DB(filestorage)
conn = db.open()
root = conn.root()
noah = root['noah']
print "BEFORE ITHDRAA"
print "================="
print noah
jeremy = root['jeremy']
print jeremy
446
 12. )/ $ /
print " "
transaction.begin()
noah.withdraw(z00)
jeremy.deposit(z00)
transaction.commit()
print "AFTER ITHDRAA"
print "================"
print noah
print jeremy
print " "
conn.close()
;'  & &  $#        &:
jmjonesYdinkgutsy:/code$ python odb_withdraw_1.py
BEFORE ITHDRAA
=================
Account noah, balance 1000
Account jeremy, balance 1000

AFTER ITHDRAA
================
Account noah, balance ^00
Account jeremy, balance 1z00

K  $  # "  , '  ' $ 
( ZO[B,  , %   (#:
jmjonesYdinkgutsy:/code$ python odb_read.py
[('jeremy', Account jeremy, balance 1z00), ('noah', Account noah, balance
^00)]
  %
noah
 #"#  1000 700,    %
jeremy
 %#  1000 1300.
%,     $#  #$ & 
MyClass
    , %  (  #      #    $ 
&.  $ %  (       #      
 # (  #$        % . { 
  &    #   %          % 
     $     , $       
  ,       #  . ;'   & 
 ,   #$ & $       $ , % # 
      :
#!/usr/bin/env python
import ZODB
import ZODB.FileStorage
import transaction
import custom_class_odb
 !  "!
447
filestorage = ZODB.FileStorage.FileStorage('odb_filestorage.db')
db = ZODB.DB(filestorage)
conn = db.open()
root = conn.root()
noah = root['noah']
print "BEFORE TRANSFER"
print "==============="
print noah
jeremy = root['jeremy']
print jeremy
print " "
while True:
try:
transaction.begin()
jeremy.deposit(z00)
noah.withdraw(z00)
transaction.commit()
except custom_class_odb.OutOfFunds:
print "OutOfFunds Error"
print "Current account information:"
print noah
print jeremy
transaction.abort()
break
print "AFTER TRANSFER"
print "=============="
print noah
print jeremy
print " "
conn.close()
|  &  ! &        &,  
&       . @ #   $         
 &      300   % 
noah
 %
jeremy
,   
% 
noah
 ' &    %    &    .     ,
   %  $ &  
 %   ,    
   , %  $   %  ,  !   
  & % .  
  $ & 
abort()
$ 
       &.    ,     
!       $ .   $    " 
&,        ?      % (   &
2000,   #  $%#  '  %  #  1000.
;'   &  $# 
$     &:
jmjonesYdinkgutsy:/code$ python odb_withdraw_2.py
BEFORE TRANSFER
===============
Account noah, balance ^00
448
 12. )/ $ /
Account jeremy, balance 1z00

OutOfFunds Error
Current account information:
Account noah, balance 100
Account jeremy, balance 2200
AFTER TRANSFER
==============
Account noah, balance 100
Account jeremy, balance 1900

  %         %
noah
 #  700 
   %
1300 ,   2000.     $   
% 
OutOfFunds
,  %
  # 100    %
2200,   2300.   A]TER TRANS]ER +     - 
%
noah
  # 100    %
jeremy
1900,   2000.
)  ,    $   %  ,      $ 
transaction.abort()
,  # " 300 ,  &  (
  $ '   ?& #. ;   $    
      .
J$ ( ZO[B   &     "  , $   
' %   '   '    
   &     
.       #$ . ? ,  (&    ,  
   ?   &    ( &,        
 &. ;          &     #   
  ,  $ . J$ ( ZO[B    , %   
   ,   $%#   &   %   
 ($ ' & ? , "   $ '    
       #&  $' .
 $ %  $      $:     , % 
  &,     (& #     # ?  Python.
    ,      $ #,   &
 &    $ % . D '  $ (  #   #    
 .     $   &  (   #,   ' $& #& 
    & #,   $     %"  (  &
  "   .
=$ $    $
)       $     % . )    $ 
    #   #$     &   $.   &
    $   $  &   (  ? 
Python    !    (
 " &( 
 ? 
Python,   (   & ( ( + ,   &
  $ (-      ?    !   
.
- !!  "!
S^Lite
)     $  (& #    #        
    ,  %   "   '  .  #   
   #         ( & ! , 
$ &  &  $ (,  DJY + 
 &  &  $ (-. H   , % 
 ' (  #  #$  #    &  $ (,
 MySQL, PostgreSQL  Oracle. {   ,    '  $
  #     %    $ .
  ! , %   &    , SQLite  
       % 
&,  $&    %,
 $  ,    
    ($ $ ( SQL
 '  $ .  
$% F |  ($ $
(      #         ,    '
     , %  "   ,    '  #&
    . Y ( & &  ! ,     '  
   , $ (    #  !   . )  
  , %    # & (  ,      , &  #$  &,
 #    , & $
        
$       & ! $ (,  $  
   SQLite. |   '   ' $% , % SQLite
&& & $  (    % "   $ '  &.  
   &,    '   $   (    
SQLite:      #$      $ '  &, 
  & $ (. {        
      .  ' 
SQLite   % &  #"
   &$    &   #"   (   
(  .
@  #,    $ %,       #  #$ 
   $ (,   ,    #$  #&. H $&
    &  $  ,   #$ #  
!  [jango   11.    ', %    & !   
 
inventory.sql
,  '    :
BEIN;
CREATE TABE "inventory_ipaddress" (
"id" integer NOT NU PRIMAR E,
"address" text NU,
"server_id" integer NOT NU
CREATE TABE "inventory_hardwarecomponent" (
"id" integer NOT NU PRIMAR E,
"manufacturer" varchar(50) NOT NU,
"type" varchar(50) NOT NU,
"model" varchar(50) NU,
"vendor_part_number" varchar(50) NU,
450
 12. )/ $ /
"description" text NU
CREATE TABE "inventory_operatingsystem" (
"id" integer NOT NU PRIMAR E,
"name" varchar(50) NOT NU,
"description" text NU
CREATE TABE "inventory_service" (
"id" integer NOT NU PRIMAR E,
"name" varchar(50) NOT NU,
"description" text NU
CREATE TABE "inventory_server" (
"id" integer NOT NU PRIMAR E,
"name" varchar(50) NOT NU,
"description" text NU,
"os_id" integer NOT NU REFERENCES "inventory_operatingsystem" ("id")
CREATE TABE "inventory_server_services" (
"id" integer NOT NU PRIMAR E,
"server_id" integer NOT NU REFERENCES "inventory_server" ("id"),
"service_id" integer NOT NU REFERENCES "inventory_service" ("id"),
UNIUE ("server_id", "service_id")
CREATE TABE "inventory_server_hardware_component" (
"id" integer NOT NU PRIMAR E,
"server_id" integer NOT NU REFERENCES "inventory_server" ("id"),
"hardwarecomponent_id" integer
NOT NU REFERENCES "inventory_hardwarecomponent" ("id"),
UNIUE ("server_id", "hardwarecomponent_id")
COMMIT;
@        $  # $ ( SQLite     :
jmjonesYdinkgutsy:/code$ s~litez inventory.db inventory.s~l
  % , $ #     , %  '    SQLite.  
( Ubuntu  [ebian      & &     
apt
- !!  "!
   ', %   SQLite         $ 
(    %  $ . H  ' "     , 
%   % & $ (  $  &   
. ;'  $  , % 
(    # &  % &
$ ( SQLite:
In [1]: import s~litez
In [2]: conn = s~litez.connect('inventory.db')
 , %      #,      #   SQLite 
$  $ # ! 
connect()
  
s~litez
. * &
connect()
 $ ?   &  $  (,     
 &
conn
      #$  #   " & %  
 . Y    # ?    &   &  $ , 
&   $:
In [z]: cursor = conn.execute("insert into inventory_operatingsystem (name,
description) values ('inux', '2.0.zq kernel');")
H
execute()
 $ ?   $ (,    
 "  #  &
cursor
.    , %   $ $
% & # &   
name

description
   $%  &  
&
,  && &  % 
% .  $     
 , %     %  $%  .   #   $   
  (  $,   $ 
   ,   '  $
   $#     (=        
   #    $  #   $#  ,    
' ( #:
In [q]: cursor.fetchall()
Out[q]: []
;%  ,    ' .
In [5]: conn.commit()
In [6]:
   #     '    '  #   
 & (. |  $  &      "    ,
   $   $       $  (. ;    
  " & $ # 
commit()
,   $   , %   
'  # $.
@  #,     $   $  $ ( SQLite,    
 %  # $    . Y& % $    % 
IPython,      # slite3   $       ! 
$ (:
In [1]: import s~litez
In [2]: conn = s~litez.connect('inventory.db')
452
 12. )/ $ /
@  #    $ 
select
  %     $#  :
In [z]: cursor = conn.execute('select * from inventory_operatingsystem;')
),   , $ %   $  :
In [q]: cursor.fetchall()
Out[q]: [(1, u'inux', u'2.0.zq kernel')]
|   ,     " . %    
name

description
(& &   . K  
$     %
 . % ,    $  &    (  $     
 $ & $%   &  %  %, $ (  $
   ,   %    %
&    # $% 
&    &.
@  #,     $ #      $  
&  $  ( SQLite,  $&   & ,   
& (     '(    ,  $% #    ,
     . J$ ( SQLite   % %  $ '
  #  ( & (,        #$ & 
       #   #   #$  &  
   .   &   , SQLite    (  &
 " &   #"( $ %. 
 !   & slite3   &
"   '.
Storm ORM
;  &  , %    SQL !  $ (  
  % & $ % &, $  &,  &    & 
(  $ ,     , %     $ #&  
      &$  Python.       #     (
  $ (  & #     ?   
       (, (&(&  $ . | 
  $ & ?   &      +ObjectRelational
Mapping, ORM-.  ( ORM ?  &$   &
 '      #         $ (.
@, &$  " & 
"  %,    # 
        ? .
Storm     ORM,
        
 ,   &     (   , 
 qanonical, &  $     Linux Ubuntu.
Storm    #            $
( & &$  Python,    '  && &  #
     , %     $  (   
ORM  &$ Python.
@  #       #$  # Storm &     $ ,
&      $  SQLite.   , %   
  #,   $  # '  &   (  .  
- !!  "!
 #   ' # 
inventory_operatingsystem
 
    $#,   '       . ;
'  $ ,  &  
'    #$   
 Storm:
import storm.locals
class OperatingSystem(object):
__storm_table__ = 'inventory_operatingsystem'
id = storm.locals.Int(primary=True)
name = storm.locals.Unicode()
description = storm.locals.Unicode()
|  %    .  #  %   (?   
   .  #    &     ,      

object
.   &   #   . {    , % 
&       ,   
__storm_table__
.     #
  Storm  & , &       
 #$  #&  ? .    &    %     
 % , ,     ,           #  #  .
; ,  
name
' &   
name
 
inventory_
operatingsystem
,   
description
' &   
description
  '  .  F H&. /    ,     
   Storm,   %   ' &      
  , &    & &   
__storm_table__
K % ,    ' , %   
description
?  
'&   
description
F @         
storm.lo
cals.Type
&      &       
name
. ;
 , $       
description
  :
dsc = storm.
locals.Unicode(name='description')
,    &'  
? 
OperatingSystem
  '     +  #    
descrip
tion
-. ;     '   #&     
mapped_object.description
,     
mapped_object.dsc
@  #,      &       $ (,
     #     
 .     "   
     Linux  & 
2.0.34   Windows 3.1.1:
import storm.locals
import storm_model
import os
operating_system = storm_model.OperatingSystem()
operating_system.name = u'indows'
operating_system.description = u'z.1.1'
db = storm.locals.create_database('s~lite:///%s' % os.path.join(os.getcwd(),
'inventory.db'))
store = storm.locals.Store(db)
store.add(operating_system)
store.commit()
454
 12. )/ $ /
           
storm.locals
storm_model

    $   $ & 
OperatingSystem
   $% 
&    
name

description
. +   :  %  
$%   (      #$      .-  
  $  ? $ (, $ ! 
create_database()
        # ! "  $ ( SQLite,
inventory.db
.       #, % ? $ (  
 #$  #& &  & (
 $,     ,   
  ,  &
. %  '  $  # ?
Store
,   
? $ (   .       '   #
?
operating_system
 ?
store
.  $ %  $ &  
commit()
? 
store
, %      #   ? 
ope
rating_system
 $ (.
H  ' (     #&,
%       #
  $  $ (.   #   $ ( SQLite,
 '       #$  #&       
  
s~litez
. ;    #  , 
   %  #
  , $   $ $    # Storm.
)  , '   &   &   , & $    
  $ $ 
inventory_operatingsystem
+( &    #
    -:
import storm.locals
import storm_model
import os
db = storm.locals.create_database('s~lite:///%s' % os.path.join(os.getcwd(),
'inventory.db'))
store = storm.locals.Store(db)
for o in store.find(storm_model.OperatingSystem):
print o.id, o.name, o.description
    #         $ #  
    #        . %   (  
   , %         $ 
  !   .  % ,    .  & ' %
$ % &  , %   ( %&(  (    # 
 '    #  &,  ' %      
 #&  $  (.  #  #$ & '    
   &, %         . D   & ?
  $ ! &
create_database()
. D   & ?
store
,  $     
Store()
,       ?
. ;  #    & ?   ( + ?
store
 $  
find()
? 
store
. |    $   
+  #
store.find(storm_model.OperatingSystem)
-  $  
'    ( ? 
storm_model.OperatingSystem
.   #  
Ope
ratingSystem
&& &     
inventory_operatingsystem
- !!  "!
Storm    ( & $  
inventory_operating
system
  $  ?
OperatingSystem
& '  $ (. Y& ' 
 ? 
OperatingSystem
 & & $% &   
name

scription
. |     && & 
&      &
$   $ (.
 "  $ ( '  &  $#,  &   
    ,  " &  $  SQLite. Y   
, %  % &,  $  #   . H    '
 #, %     $#, ( &       $
 #$ &   Storm:
jmjonesYdinkgutsy:/code$ python storm_retrieve_os.py
1 inux 2.0.zq kernel
|  %       " ' &. @  # %  
   $  #  , &   $#,  $   
 $   , $   . ;  $  ' 
     $#,    +   $ & 
Linux 2.0.34-,  # %   $# +Windows 3.1.1-:
jmjonesYdinkgutsy:/code$ python storm_add_os.py
jmjonesYdinkgutsy:/code$ python storm_retrieve_os.py
1 inux 2.0.zq kernel
2 indows z.1.1
)     %   , %  '   % #.
; % ,      & !#   #  F    ', %
    &  # #
    , $
( % &     #      Lin. ;' 
  & !    
,      :
import storm.locals
import storm_model
import os
db = storm.locals.create_database('s~lite:///%s' % os.path.join(os.getcwd(),
'inventory.db'))
store = storm.locals.Store(db)
for o in store.find(storm_model.OperatingSystem,
storm_model.OperatingSystem.name.like(u'in%')):
print o.id, o.name, o.description
|     %    
  ,   #$ &

store.find()
, $  %    , %       
store.find()
   &     :     . $ 
Store.find(storm_model.OperatingSystem,storm_model.OperatingSystem.na
me.like(u'in%'))
   Storm, %   &   #
 ? 
OperatingSystem
,  ( $%    
name
%
 &      
in
. ' $%      $# 
   & %  ' ,          .
456
 12. )/ $ /
)    $   !  ,      :
jmjonesYdinkgutsy:/code$ python storm_retrieve_os_filter.py
1 inux 2.0.zq kernel
 $ (   '    
$#  $   
    Windows 3.1.1,    !#  ,  
%  % &     Lin.
S^LAlchemy ORM
  &    Storm # %   #   
  (  &     !  &    ,  
SQLAlchemy ' && &      ORM & &$ 
Python.    (   " 
      Storm.
  &  , %"    $ #, %   Storm    
(   "       SQLAlchemy,   # 
  SQLAlchemy  &#
#" . ; ,     ,
&    SQLAlchemy    #$ &   '  
inventory_operatingsystem
, &      # %  #$ 
   Storm.
;'   &      ?  & ' &

inventory_operatingsystem
#!/usr/bin/env python
import os
from s~lalchemy import create_engine
from s~lalchemy import Table, Column, Integer, Text, ARCHAR, MetaData
from s~lalchemy.orm import mapper
from s~lalchemy.orm import sessionmaker
- !!  "!
     $%  '     #$ & Storm
 SQLAlchemy $ % &     ,   #$
&   SQLAlchemy &
 $ &      
  .
@  #,      &    ,  '  #
  ,  & $   ( $  $ :
#!/usr/bin/env python
from s~lalchemy_inventory_definition import session, OperatingSystem
for os in session.~uery(OperatingSystem):
print os
{ $  #  !   #,     '   &  
  , $      (  (,  
   :
$ python s~lalchemy_inventory_~uery_all.py OperatingSystem('inux','2.0.zq
kernel')�
OperatingSystem('indows','z.1.1'�)
/OperatingSystem�/OperatingSyste�m
{       #  $  #   $#,      
  #  ,    $  ?
OperatingSystem
    ?
session
#!/usr/bin/env python
from s~lalchemy_inventory_definition import session, OperatingSystem
ubuntu_^10 = OperatingSystem(name='inux', description='2.6.22 1q kernel')
session.save(ubuntu_^10)
session.commit()
  $#       & $#     
   Linux    &  ,       .    
, $"  $,  $,   %:
$ python s~lalchemy_inventory_~uery_all.py
OperatingSystem('inux','2.0.zq kernel')�
OperatingSystem('indows','z.1.1'�)
OperatingSystem('inux','2.6.22 1q kernel'�)
*# &  $# 
  SQLAlchemy  & &  '   .
; ,        #  #  ? 
Operating
System
,  ( $%    
name
% &     #
      Lin,      #    :
#!/usr/bin/env python
from s~lalchemy_inventory_definition import session, OperatingSystem
for os in session.~uery(OperatingSystem).filter(
OperatingSystem.name.like('in%')):
print os
458
 12. )/ $ /
)      % #    $#  :
$ python s~lalchemy_inventory_~uery_filter.py
OperatingSystem('inux','2.0.zq kernel')�
OperatingSystem('inux','2.6.22 1q kernel'�)
|  "#   $   $ '     SQLAlchemy.
   #  !     #$  SQLAlchemy 
 #   
http:44www.sqlalchemy.org4
. )    
       +Rick qoupland- Essential SQLAlchemy +OReilly-.
 ; 
          # $%(    ,  
$ &(  (& #  &      #$ &. ) 
       #&  %        ,   #
pickle
. )        #&  %     !  #
 ,  SQLAlchemy ORM.  '   $ ,   #$ 
 &$  Python  "   &'   &  '    " 
, % #   (  (   '(.
     : SQLACLCHEMY
,  (Mike Bayer)
H  J   & %       
    % & $ ;#  ,   
&         &  
$ (  ( !   $  .    $ 
&  '      (    
   $ (   ( &$ (
  &,  q, `ava  Perl,     
 # (   %       ,   &
$   # (    ,   Oracle & "   
     SQLAlchemy,       
&  $ &  SQL  &    $ (. ~ # 
    , %       #  &      
    & &$  Python,        # Py
thon  "  &  !    &, 
      #.
# $  
  
  &       $%  &      
. ;               $% 
     ,   &   .       
             &  & & &  #
"   (    
. H      
   %      (,  #$  
 !%    !  ,  $ !%    !  
&.  $ ' ,        ,    &" &
          &  !       
  .
 %  % #     
  UNIX  '# !
  !, %  !    
   +qommand Line Inteface,
qLI-   (      $ '  &   !%    
! ,    $ &.     (   
 $  &  %   , % ' Microsoft  "   #&  
&. Y' !!    +`effrey Snover-, (  Windows Po
wershell, $&: |  "
  #, % !%   
!     '  '    #  !   
    .
Y'  $     Windows,     %  &  
 &  ( "  !        $  (    
(   (  , %   # $%  #  ! 
      , %    $ Windows Powershell.
         #&       Windows,
  % #    ! ,  %   '  #  &
         #  (   #  $ &  
        .
460
 13.  !  
    %   
 #      
UNIX          .    #  &  
!         ,  (  % #&  $  #  
          '  #      % , 
   $&      . |     $ % . 
% %  ,     
   $      
       &$ Python.
|       " 
     #  
 $                  . H ( 
 %      #  " %"     
  &  &$ Python,   $ %   $ # ,
  '  #$  #        $   &( " 
       .
   $ 
   
     #  $            
 &  $  ! , %  #
sys
 $ &   #
                
sys.argv
.   
 13.1    &  
          
,   #  $ ' :
% F.. sysargv.py
#!/usr/bin/env python
import sys
print sys.argv
|           $      
 , %   &       :
./sysargv.py
['./sysargv.py']
./sysargv.py foo
       
['./sysargv.py', 'test']
./sysargv.py foo bad for you
       
['./sysargv.py', 'foo', 'bad', 'for', 'you']
 $"!   
461
Y          
  $   
 , %    %  %           ,
  $    13.2.
% F.=. sysargv.py
#!/usr/bin/env python
import sys
#    Python @   , K -  @ 3
#   - - sys.argv[0]
num_arguments = len(sys.argv) 1
print sys.argv, "ou typed in ", num_arguments, "arguments"
      #:     ,  #    # "#  
% #          (   $  
sys.argv
  #      (  .     
,   #    $  #. Y     
    "   '       .    , %
      #,         "    
         " (  %   &  
      ,   $    13.3.
% F.F. sy&#x-6.2;ø.2;&#x.F8.;. s;&#xy15.;sar;&#xgv00;sargvstep=.py
#!/usr/bin/env python
import sys
num_arguments = len(sys.argv) 1
#G      -      +7 
#       +7  + +X.
if num_arguments == 0:
sys.stderr.write('Hey, type in an option silly\n')
else:
print sys.argv, "ou typed in ", num_arguments, "arguments"
) #$ 
sys.argv
  $           
$%  && &  # 
  ,   &     
 .        &$  Python  &  #
opt
parse
,      &  "    $ (   ( $ %
  $  %              . Y' &
(  " %( $ (     %"  #$  #
opt
parse
, % 
sys.argv
,    $ (      #    
      #&   #
  %    .   
  $   ?&,  %
 %"  #$  #  #
opt
parse
,   #   $ % &  , % % (  "   &
$      $  $ " #   %  .
462
 13.  !  
    optparse
   #      $  , '   #   
  '   #$  #&      &
optparse
 
   $          .  & $% 
  $ '  
optparse
,     % #   $ 
  Vello World,   &       
  .    13.4   & "   Vello World.
% F.G. Kello Zorld " %" optparse
#!/usr/bin/env python
import optparse
def main():
p = optparse.OptionParser()
p.add_option(' sysadmin', ' s', default="BOFH")
options, arguments = p.parse_args()
print 'Hello, %s' % options.sysadmin
if __name__ == '__main__':
main()
 &   ,   '   % # $%   
 :
$ python hello_world_optparse.py
Hello, BOFH
$ python hello_world_optparse.py sysadmin Noah
Hello, Noah
$ python hello_world_optparse.py s `eremy
Hello, `eremy
$ python hello_world_optparse.py infinity Noah
Usage: hello_world_optparse.py [options]
hello_world_optparse.py: error: no such option: infinity
 "   #      , %  '  #$  # 
 
,   
sysadmin
 ,   ' $%  
 %. ;  ,        $ '  #  
" ,    $        #    %  
  ,     (  &$  Perl.
  '  $ optparse
`'  $ ' ;"
     $    , %  #
optparse
 '  
 (   #$  #& '   # (  &(.    13.5
 $    "   #$ &  &
optparse
,   
  8* $"! optparse
463
    % % 
     , %   "
  #$  #    
optparse
% F.6. 3 %"+ ls
#!/usr/bin/env python
import optparse
import os
def main():
p = optparse.OptionParser(description="Python 'ls' command clone",
prog="pyls",
version="0.1a",
usage="%prog [directory]")
options, arguments = p.parse_args()
if len(arguments) == 1:
path = arguments[0]
for filename in os.listdir(path):
print filename
else:
p.print_help()
if __name__ == '__main__':
main()
       $   &$ Python     

, &        #   ,
 '     &   . H      
' %   #( % ,    '   '   #$ 
 #&  $ '  &  &
optparse
, &#  (   
    &  . %   $   $ & 

OptionParser
   &    !   $
  &      &  #$ & &  
#(  #$       .      &  %  
  ,   ( %  #"   #"   ,   
    &  #$ &        #  
p.print_help()
. ;'   &   #   #$ &
"     ,      & &     
$ python no_options.py .
.svn
hello_world_optparse.py
no_options.py
K  #   , %  $  ,  $  #    $ 
  :
$ python no_options.py
Usage: pyls [directory]
Python 'ls' command clone
Options:
464
 13.  !  
version show program's version number and exit
h, help show this help message and exit
)   , %    ,
&$  $    
p.print_help()
    & %& $   &,   % 
     %  ,  # $   &  
help
$ python no_options.py help
Usage: pyls [directory]
Python 'ls' command clone
Options:
version show program's version number and exit
h, help show this help message and exit
K       
version
,    #$ 
   %   :
$ python no_options.py version
0.1a
      #
optparse
$&   $  '   $ 
$    &,   '   % # # "  $
`' trueqfalse
J % #    #  $ '  #    #   
$  $%  true  false. %        " 
  ' # %:
  8* $"! optparse
465
for filename in os.listdir(path):
if options.verbose:
print "Filename: %s " % filename
elif options.~uiet:
pass
else:
print filename
else:
p.print_help()
if __name__ == '__main__':
main()
) #$& %
verbose
,     "    #   
   ! ,     
      .   
,  & ! &   &  '  $       
 . %  #   #:
$python true_false.py /tmp
.aksusb
alm.log
amt.log
authTokenData
466
 13.  !  
  &, &   ]ilename:   ! %     
!.    , %       $   
p.add_option()
    
default=False

action="sto
re_true"
,  $  , %   %    
 # $% 
false
,    $   &   $ %
verbose
,      $% 
true
.    $ % &
  #  #$ &  %  (       
optparse
`'       
{   #$  %           
      UNIX,  
tcpdump
,  $ #  
vvv
,   %         , %    #$ 
  

.   '  $  #  %   
 ,   #$ "#    $ '  #  &
optparse
, 
 % %    ( 
  . ; ,    
  &   #    
 %  &    
   ,       #  ,   $    13.7.
% F.7. -  "% %&  % 
#!/usr/bin/env python
import optparse
import os
def main():
p = optparse.OptionParser(description="Python 'ls' command clone",
prog="pyls",
version="0.1a",
usage="%prog [directory]")
p.add_option(" v", action="count", dest="verbose")
options, arguments = p.parse_args()
if len(arguments) == 1:
if options.verbose:
print "erbose Mode Enabled at evel: %s" % options.verbose
path = arguments[0]
for filename in os.listdir(path):
if options.verbose == 1:
print "Filename: %s " % filename
elif options.verbose ==2 :
fullpath = os.path.join(path,filename)
print "Filename: %s Byte Sie: %s" % (filename,
  8* $"! optparse
467
  #$  "    &    %    
%        '         
   $  #     .       
$ &  % 
,  
options.verbose
 % $%  1= 
    $ &  % 
,  
options.verbose
 
% $%  2. ;"   
$   $ %     
  ! ,  $   % 
     ]ilename:
  '     ! ,   ,     $ &
 % 
,     # & !,    $   
(. ;'  $  $#  $   &  % 
$ python verbosity_levels_count.py vv /tmp
erbose Mode Enabled at evel: 2
Filename: .aksusb Byte Sie: 0
Filename: alm.log Byte Sie: 1q0z
Filename: amt.log Byte Sie: z0z8
Filename: authTokenData Byte Sie: z2
468
 13.  !  
choices=["normal", "verbose", "~uiet"],
default="normal")
options, arguments = p.parse_args()
print options
if len(arguments) == 1:
if options.chatty == "verbose":
print "erbose Mode Enabled"
path = arguments[0]
for filename in os.listdir(path):
if options.chatty == "verbose":
print "Filename: %s " % filename
  8* $"! optparse
469
Filename: helloworld
Filename: hsperfdata_ngift
Filename: ics1000z
Filename: ics12158
Filename: ics1zzq2
Filename: ics1q18z
Filename: icssuis501
Filename: MobileSync.lock.f9e26qq0fe5adbb6bcq2d^bf8f8^c1e5fc61a^fe
Filename: summary.txt
{     ,          $  
chatty  %,    verbose  $%  .    "
    
print
&     
options
, %   
$ # ,   &   %  $ &  .  $ % 
'   &   $     $% 
~uiet
 
 
chatty
470
 13.  !  
{     # $  #         
  
dir
,   %        " :
[ngiftYMacintosh 8][H:102z8][`:0]# python multiple_option_args.py dir /tmp
Usage: pymultils [ dir dir1 dir2]
pymultils: error: dir option re~uires 2 arguments
D $    %     
dir
,   %  
 :
pymultils: error: dir option re~uires 2 arguments
[ngiftYMacintosh 8][H:102z9][`:0]# python multiple_option_args.py dir /tmp
/Users/ngift/Music
isting of /tmp:
.aksusb
     *        
     ,  "           
    &$ Python  $ &  $  #     
  ,      
 #  &$ q  Bash.
  ' %  "&  
    %  
,   #$ & %  ,
tcpdump
    &( 
'  & &$  Python   #$ &  $  
 
rsync
F     "   UNIX 2.0 % #  
     ,   
 Web 2.0.  " Python
   UNIX    &   (     " 
   $%   .    $       
 $  (   .
`'    $  V '  
    $
  $ Python
)    #$               %
    , %   &
.   '    # " 
 #"  %      &  &    
% &  ,     . ) #$& &$  
 & Python,  ' % #   $  #        $
  #  #   , %   (  . H $  "
     &  $. Y&
(,  $ ,  &, %
 $      # &   , $ $     
 ( }   $ ^ .  $ %       
 "! ,   "   &&   "  .    # &$  Py
thon   '  # '     UNIX.
          
snmpdf
    &$
Python, %     #  #$  . Y& %   ,
 &  % $  :
[ngiftYMacintosh 8][H:10285][`:0]# snmpdf c public v 2c example.com
Description sie (kB) Used Available Used%
Memory Buffers 206^6z6 2q9560 18180^6 12%
Real Memory 206^6z6 1990^0q ^69z2 96%
Swap Space 101208q 6q 1012020 0%
/ ^q59q112 1^q20^q0 5^1^zz^2 2z%
/sys 0 0 0 0%
/boot 101086 200q1 810q5 19%
Y& (,  $    
snmpdf
,  &, %   $
%  &       &   (,  (  '
 SNMP    ( &  % & !  $ $  MIB,
    "   .           
,  #$   SNMP,    #" %  
  , %  '& (  #$  .        
$  #, %  $   
'  $  #    ,
      #   & 1, 2  3   SNMP,  
  # $ " #     (
(   . K % ,   
472
 13.  !  
      & &   '    %  F 
 '  $  #      $    
snmpdf
, &
  %      # & ". J $ & (  
 ,   $ ' .    13.10  $ ,     
& #  &   .
 , %  $  #  
    UNIX    #
&$  Python, (  &  #  #"     
, %   &$ Bash. ; ,   &   ,     
 %  &$  Python,   %   $ &  #$  #
          & " &     
  ' .    ,   '     #   
 %  ' ,         
,    %   #   
#      %     .
% F.5. -   " %"+ snmpdf  #+  Python
#!/usr/bin/env python
import optparse
from subprocess import call
def main():
p = optparse.OptionParser(description="Python wrapped snmpdf command",
prog="pysnmpdf",
version="0.1a",
usage="%prog machine")
p.add_option(" c", " community", help="snmp community string")
p.add_option(" ", " ersion", help="snmp version to use")
p.set_defaults(community="public",ersion="2c")
options, arguments = p.parse_args()
SNMPDF = "snmpdf"
if len(arguments) == 1:
machine = arguments[0]
#-      - snmpdf
call([SNMPDF, " c", options.community, " v",options.ersion, machine])
else:
p.print_help()
if __name__ == '__main__':
main()
|     &      #      
,    " '$# 
   . ) #$   " 
(       &
optparse
      # $% & 
 % &  (   , %" $    
  "     &. ; ,   , % 
 %   #$  #& 
& 2   SNMP,  
 $ , %  "  % #      #$ & #
   &  .    , &  
community
 
  %   $% &   %   
"public"
,   %
     *          !" Python
   $%      "      
$ ,  .  $ %
# , %  #$   
&
optparse
 $    $ & # $% &   , 
$ &&   .
   , % $% &   %   &   
 #  
set_default()
,   $ &  $    
 # $  $% &   %       
     . H  %    ,   
  #  &
optparse
  (   $% &,  
  %
options.community
.  #   & #&, %  
    % &     ,     $  " 
  $ '   &$  Python  $ &   #     $
  #   , %      % "     &.
`'    $  '  V '  
    $
  $ Python
     $
             %  #$   
 
snmpdf
,   $        .     
 &   "    % ! . Y   , 
  '  #$  #,  $ &  #   #   
UNIX,   $  #       # &$  Python.
         #$ &     &$  Python
   !  #    &, %  !#  
 #  $#   "   
snmpdf
   (  %   ' 
!   $   #   !
"CRITICA"
.    13.11
 $ ,     & #  &   .
% F.. L#%   %"+ snmpdf   %%   
#!/usr/bin/env python
import optparse
from subprocess import Popen, PIPE
import re
def main():
p = optparse.OptionParser(description="Python wrapped snmpdf command",
prog="pysnmpdf",
version="0.1a",
usage="%prog machine")
p.add_option(" c", " community", help="snmp community string")
p.add_option(" ", " ersion", help="snmp version to use")
p.set_defaults(community="public",ersion="2c")
options, arguments = p.parse_args()
SNMPDF = "snmpdf"
if len(arguments) == 1:
machine = arguments[0]
474
 13.  !  
#G  Q    
def parse():
"""G7 +W          - snmpdf"""
ps = Popen([SNMPDF, " c", options.community,
" v",options.ersion, machine],
stdout=PIPE, stderr=PIPE)
     *          !" Python
 $                 " ?   
  %  $  ' &,  &(    %  ( $% 
       $     .   % # " ,
       #      ' &   
, %   % #  $#   &    ( $%  70  80
|    ,  $ ' , $&       ',
%   (  # .  $ ' , %"   $ #  
  #   #"(   #( % ,   '
      #. )          ( 
  "  .
`'    $  '  V '  
    $
  $ Python
 %     
;"         %   ,     
       $  &   &   (  
   UNIX,    $   # (  &  " 
& !!   .   % , 
 ' & #     ,
        (    %    (  #  
 . |  $     !        , 
   &    & $ " &    (  &  #  
$  .
     $    $     ,   $
 ! $     # 
,  (  # .
 $#      $     $           ,
  '    #$ 
#     .  ,
 %     $ &   $       
   ,    &
&   &    ! 
    . )(    &   &    13.12.
% F.=.  %" dd
from subprocess import Popen, PIPE
import optparse
import sys
class ImageFile():
"""  +  -[email protected] dd"""
def __init__(self, num=None, sie=None, dest=None):
self.num = num
self.sie = sie
self.dest = dest
def createImage(self):
""" N   X  +  10 + """
value = "%sMB " % str(self.sie/102q)
476
 13.  !  
for i in range(self.num):
try:
cmd = "dd if=/dev/ero of=%s/file.%s bs=102q count=%s"\
% (self.dest,i,self.sie)
Popen(cmd, shell=True, stdout=PIPE)
except Exception, err:
sys.stderr.write(err)
def controller(self):
"""? -   - dd"""
p = optparse.OptionParser(description="aunches Many dd",
prog="Many dd",
version="0.1",
usage="%prog [options] dest")
#  !  / 
$ '  '  $ #, %          #& &
  &  $  #  
        
     (    ( ]ibre SAN  NAS.  ' 
   ,  '    # !  &  $ & % 
  !  P[]     $#         % .  
   #, % '   '    $  #   
    &,   
       '  
  ,   (   " #.
+  $ !    !"
) & ! ( !         
      '  # &
 " &     #$ 
&    &   #(      . ;  
$& $        #$ &       
   ' &     ,
  % %    
  & #   #  '   !%    
!      ' . |    ,   %  
         $'   '  #   
" &        #$ &,   & &   $
  '   !%    !  .
 !  !  '  '  #   $     &
  $    &          , $
    $( "(. Y
  $ &   !
   !  '   % #    N]S,   %   
"    %  #  $  #      
     ,  $   .      ,    '
 #&  &    &    , &  '  
  #$  #& &   % ! ( !   
  ,  $  .
           &$  Python (  $ % #
 #
ConfigParser
,  $%  & % &  $ !
 ( ! ,  #$   
! . $ 
&, ! 
&& &       ( &   ( 
! ( (,   
 %   ,  & 
    !,  #$ & XML  $ &$  Python.
   #   , %  &  & $   !
   !   $% &. Y&    &  
'  !   !  #
ConfigParser

 #$  #,   '   #&    
   $ , %   % #   '  .
 ' %    #    ! ( !
           ,   $   ! 
478
 13.  !  
! hello world.  $  !    
hello_config.ini
 #
       :
[Section A]
phrase=Config
@  #,      &   " !  !, 
 '    #      !  "   
          
 Vello World,   $
  13.13.
% F.F. L % %"&     ""  &
 A &
#!/usr/bin/env python
import optparse
import ConfigParser
def readConfig(file="hello_config.ini"):
Config = ConfigParser.ConfigParser()
Config.read(file)
sections = Config.sections()
for section in sections:
#--    @7@  ,  +  3,
#   +  Q 
#print Config.items(section)
phrase = Config.items(section)[0][1]
return phrase
def main():
p = optparse.OptionParser()
p.add_option(' sysadmin', ' s')
p.add_option(' config', ' c', action="store_true")
p.set_defaults(sysadmin="BOFH")
options, arguments = p.parse_args()
if options.config:
options.sysadmin = readConfig()
print 'Hello, %s' % options.sysadmin
if __name__ == '__main__':
main()
{  # $  #      $  (   ,
  % $%    %
BOFH
,    #   
   Vello World:
[ngiftYMacintosh 8][H:105qz][`:0]# python hello_config_optparse.py
Hello, BOFH
 ,   $ #  
config
,    %   '
 !   !      :
[ngiftYMacintosh 8][H:105q5][`:0]# python hello_config_optparse.py config
Hello, Config
 "& 
  #"  %      %  &  
config
 #$  #  # !   %,   $  #
   &  $ #     '  !  
!. Y&       &  &
store_true
 '
   #   :
p.add_option(' config', ' c',
help='Path to read in config file')
{      &    $&  ,    
   #    #$  ,
'  $  &$  Python.
 $   (  $      #     
, $ && $%    
phrase=Config
,  $  (   
 #&    . Y'
  #$  #   $
 &$  Python,   $          (
 ( '        ,      ( &   # 
   .
 ; 
H 
optparse

ConfigParser
, ( &          
  &$  Python, % #        '  % 
 ,     '  #     #"  
,     &    #&. {     & 
 #  '       
     ,  #  
  #   #  $ '    &
optparse
,   
!     $   "     &
optparse
. 
 '     #&   # $ &$(   , 
          
 ,    : qommandLine
App +
http:44www.doughellmann.co
m4projects4Command[ineQpp4
-, Arg
parse +
http:44pypi.python.org4pypi4argparse
-  qonfigObj +
http:44pypi.py�
thon.org4pypi4ConfigVbj
      
   FNS :;  
$ Python
D      [NS && &   %    $ %  
 ,  ,   
  !  !
    Apache.       " ( $ 
   [NS   &&   ,   &  " # %
 #          (  . $ &,    
 &$  Python  &  #
dnspython
,   '   
 #&   "   ( $ %.     #, %   
   #,    "  [NS,
PyDNS
,    
  # #
dnspython
&$ # $ # #     ,    

http:44www.dnspython.org4
.    ,    $ % #
&   #&   #$   &
dnspython
,    
  
http:44vallista.idyll.org4~grig4articles4
 % #  #$  #  #
dnspython
,   (  "#
  #   
easy_install
   #     $
     Python:
ngiftYMacintosh 8][H:100q8][`:0]# sudo easy_install dnspython
Password:
Searching for dnspython
Reading http://pypi.python.org/simple/dnspython/
[3   + ]
@  #       #  #    #   %  IPython
 ' ,    &#   
       .   
     $   $ A  MX &  
oreilly.com
'   DNS   %$&     !" Python
481
In [1]: import dns.resolver
In [2]: ip = dns.resolver.~uery("oreilly.com","A")
In [z]: mail = dns.resolver.~uery("oreilly.com","M")
In [q]: for i,p in ip,mail:
....: print i,p
....:
....:
208.201.2z9.z^ 208.201.2z9.z6
20 smtp1.oreilly.com. 20 smtp2.oreilly.com.
       
$% & $  A     
 $% & $  MX     
mail
.  $#  ,  % 
$ $  A,     (    ,   $#  ,  % 
$ $  MX,  ' . @  #,     %  
    ,      #, "   ,
   % # $% & $  A &   (  .
% G.. 1   %A "  + 0
import dns.resolver
hosts = ["oreilly.com", "yahoo.com", "google.com", "microsoft.com", "cnn.com"]
def ~uery(host_list=hosts):
collection = []
for host in host_list:
ip = dns.resolver.~uery(host,"A")
for i in ip:
collection.append(str(i))
482
 14.      
 %  &   ,   '  " #   
$ ,      # %  ( $  A &
 ( (  ,   (     ! .
  #
dnspython
      #" :     #  '
& # $  [NS   & #    ' $ , %  
 $ #. {        #   #
   #$ &  &,  #     URL,  $
  " .
+    
 LFAP $ '
OpenLFAPK Active Firectory  
       $ Python
L[AP        % &  #"   ,  
$     '  #$  $ ( L[AP &  
&   "   #   #. {   $   L[AP,
 ' , %      "!  &  Lightweight [i
rectory Access Protocol +  %         
 -.  $ (  %(   ,    ( 
 #    #&,   &    :      
,  $ &  #& '    ,    
 (  � TqPIP.  %       $ '  '
$ # '   ! , &,  $  , && & 
 $ (  &(       .  
 (   ,  '(   L[AP,  
' # Open [irectory, Open L[AP, Red Vat [irectory Server  Active
[irectory.      !  pythonldap  ' $ 
   &   
OpenL[AP  Active [irectory.
     !  L[AP  &$ Python $ & python
ldap   %   &  '  ?          
  OpenL[AP 2.x.     '  '   (  
   L[AP,  %&      !  L[I]  L[APv3.
 ' %  % #        ,   (  $
$ #  $   pythonldap,
 (  &   source
forge    : http��:pythonld
ap.sourceforge.net�download.shtml.
        pythonldap,  $ ' ,     & 
% $  #&       % IPython. ;'   
&        ,  %     %&
    % #&   
     L[AP,  $   
 %&   . )$%               
L[AP (   $      ,     ,   ' 
% #    #      !    pythonldap, 
 #$&       L[AP    "   H%.
#$"   LDAP
483
In [1]: import ldap
In [2]: l = ldap.open("ldap.itd.umich.edu")
In [z]: l.simple_bind()
Out[z]: 1
H
simple_bind()
  , %        "
 ,         #   %       
,    & #:
In [5]: try:
....: l = ldap.open("12^.0.0.1")
....: except Exception,err:
....: print err
....:
....:
In [6]: l.simple_bind()

SERER_DON Traceback (most recent call last)
/root/ipython console�
/usr/lib/python2.q/site packages/ldap/ldapobject.py in simple_bind(self, who,
cred, serverctrls, clientctrls)
16^ simple_bind([who='' [,cred='']]) � int
168 """
� 169 return self._ldap_call(self._l.simple_bind,who,cred,
EncodeControlTuples(serverctrls),EncodeControlTuples(clientctrls))
1^0
1^1 def simple_bind_s(self,who='',cred='',serverctrls=None,
clientctrls=None):
/usr/lib/python2.q/site packages/ldap/ldapobject.py in _ldap_call(self, func,
*args, **kwargs)
92 try:
9z try:
� 9q result = func(*args,**kwargs)
95 finally:
96 self._ldap_object_lock.release()
SERER_DON: {'desc': "Can't contact DAP server"}
   $    , "
   "  $
     L[AP  $$&  # .
+    !" LFIG
   %    
    L[AP   #
  $&  &, %    %#   "   . ;'  
 &     & (      L[I]:
import ldap
import ldap.modlist as modlist
484
 14.      
ldif = "somefile.ldif"
def create():
l = ldap.initialie("ldaps://localhost:6z6/")
l.simple_bind_s("cn=manager,dc=example,dc=com","secret")
dn="cn=root,dc=example,dc=com"
rec = {}
rec['objectclass'] = ['top','organiationalRole','simpleSecurityObject']
rec['cn'] = 'root'
)        Apache
485
  3   #   #    $ !  ' 
    Apache, $ ( $
 #  & ! &.
           #$ &  &, 
&  3, %       #,   $  #   %  
%  $      !  ' .      (
!  ' ,  (  & & # ,   '
 $ #    , %  '  ?  # ! ' 
  $  #  % . )(       &  
  14.2.
% G.=. -"+&    &  
-�   Qpache
#!/usr/bin/env python
from optparse import OptionParser
def open_files(files):
for f in files:
yield (f, open(f))
def combine_lines(files):
for f, f_obj in files:
for line in f_obj:
yield line
def obfuscate_ipaddr(addr):
486
 14.      
print " " * 60
report_dict = generate_log_report(file_obj)
for ip_addr, bytes in report_dict.items():
print "% 20s%s" % (obfuscate_ipaddr(ip_addr), sum(bytes))
print "=" * 60
   %  &  & &  ! :
open_files()
combine_lines()
.  $     !     #$  #&   
  ( &   &    . * &
open_files()
 ! &   , &   +   # 
       ? -   ! . Y& '   
!   $   ' $   !       
?    !. * &
combine_lines()
  
  ?   ( !          .
  & ( ?  !    
for
. Y& '  !
 & & (      ! . )  '    
  #   
yield
 $ %     . ) 
  ? ,  %  ! 
combine_lines()
,  ' 
 #  ! :   '   & # (      ? .
     #  &
optparse
 & & $     
     ,  % (  #$  &. H    #
#    ,   %   : $ ?  &
!  '   $  (
    #$  #  
 &( ' .  
consolidate
   ,
%  ! '  # ?        % . {
     &  
, ,      ,  
&      '  ! . ;       
&.  
regex
   , %     split
   #$  #    &( ' , &
     3. 
     % ! 
 #  $ '  ,    split     .
    & &,    $  
regex
. {   
 $,    &  #
apache_log_parser_regex
%  #$ &  #
apache_log_parser_split
.    # 
    %   , %   #  $  #  #
(  .  $  #      &     
    $' .
  $ & ! &
open_files()
,      & 
  ! ,  %   #$  &.   '  ,
! &
open_files()
 ! &   , &  $
? ! & '     (    . | $% , %
'  !  & ! %  , #   ! &  $
     ? . @  #,      &   
 ?    !,   '   & #    
  . H  '    # (  ( !      #
%  '  $ (  ?  # (         
)        Apache
487
  # ?   % $ 
  !. |  $  
 ,     (  ! &
combine_lines()
. {  #$  #
   % consolidate,  ! ,     
 & #&  ,   ' #    ? ,  
 !:      (     ( !(.
Y ,  $  ,  & !  ' &   
  !, '  $
(    &
    
! 
generate_log_report()
, &  $  #  IP  
  %     ,  (      . Y& '
 !  & &   $    !      
   $#     ! 
generate_log_report()
. ;'  
 &  ,  %    $#      ! '
 $   28  :
************************************************************
access.log

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 1^q^9
200.80.2z0.0 q5zq6
200.q0.90.110 82^6
1z0.150.250.0 0
^0.0.10.1q0 2115
^0.180.0.220 ^6992
200.q0.90.110 2z860
190.20.250.190 q99
190.20.250.210 qz1
60.210.q0.20 2^681
60.2q0.^0.180 209^6
^0.0.20.120 1265
190.20.250.210 q268
190.50.200.210 q268
60.100.200.2z0 0
^0.0.20.190 z^8
190.20.250.250 59z6
============================================================
 ,  %    $#     ( !  ' 
+! %          ' !,  $   
      & ( $ #  !-, &
 ,   $ ' :
************************************************************
access.log

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 1^q^9
200.80.2z0.0 q5zq6
488
 14.      
+ �
^0.0.20.190 z^8
190.20.250.250 59z6
============================================================
************************************************************
access_big.log

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 1^q^900
200.80.2z0.0 q5zq600
+ �
^0.0.20.190 z^800
190.20.250.250 59z600
============================================================
************************************************************
access_bigger.log

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 699160000
200.80.2z0.0 181z8q0000
+ �
^0.0.20.190 15120000
190.20.250.250 2z^qq0000
============================================================
K '   & ?   % &  (  ( ! :
************************************************************
CONSOIDATED

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 ^00925z^9
200.80.2z0.0 1818q199q6
+ �
190.20.250.250 2z80z95z6
============================================================
)  ,   '  $  #  #    &F )    
   & F   , 
 & &    $  , 
 &#     Ubuntu Gutsy,       Athlon 64 X2
5400 2.8 ,  ?   D 2     '     Seagate
Barracuda 7200 RPM SATA. $  ! '   &  
 1  :
jmjonesYer:/data/logs$ ls l access*log
rw r r 1 jmjones jmjones 115^080000 2008 0q 18 12:q6 access_bigger.log
;'  & &  $#     &:
$ time python summarie_logfiles.py regex access_bigger.log
)        Apache
489
************************************************************
access_bigger.log

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 699160000
+ �
190.20.250.250 2z^qq0000
============================================================
real 0mq6.296s
user 0mq5.5q^s
sys 0m0.^qqs
jmjonesYer:/data/logs$ time python summarie_logfiles.py access_bigger.log
************************************************************
access_bigger.log

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 699160000
+ �
190.20.250.250 2z^qq0000
============================================================
real 0mzq.261s
user 0mzz.z5qs
sys 0m0.896s
  #$   ,
 &  $ %  (
  #  &( ' , 
 $  %  "  & 
46   .   #$   ,  #$  
string.
split()
,   $  %  " 34   . ;  $     
& &  $# % . ?  $&  &   
130H . %  , % ! &
generate_log_report()
 (
&    (   & '  IP    ! '
.   , %   #" !,   #" ?  &    
 & #   . ;   '     %   #. ;'
  &   ' & &
  &  ,  &
  $ ! ':
#!/usr/bin/env python
def dictify_logline(line):
'''7 3,  7  -Q@,   @
 -+  
G  7  -    @ 3    X X 
      X + ,       3 - 
- + +   .
'''
split_line = line.split()
490
 14.      
'bytes_sent': split_line[9],
}
def generate_log_report(logfile):
'''7 3  - :
remote_host=�[    X + ]
 Q - +W   file,  +X  X  
          + ,   X
 - +7    X    +   .
'''
report_dict = {}
for line in logfile:
line_dict = dictify_logline(line)
host = line_dict['remote_host']
#print line_dict
try:
bytes_sent = int(line_dict['bytes_sent'])
except alueError:
## [email protected]  3    - +
continue
)        Apache
491
action='store_true', help="use mem parser")
(options, args) = parser.parse_args()
logfiles = args
if options.regex:
from apache_log_parser_regex import generate_log_report
elif options.mem:
from apache_log_parser_split_mem import generate_log_report
else:
from apache_log_parser_split import generate_log_report
opened_files = open_files(logfiles)
if options.consolidate:
opened_files = (('CONSOIDATED', combine_lines(opened_files)),)
for filename, file_obj in opened_files:
print "*" * 60
print filename
print " " * 60
print "% 20s%s" % ("IP ADDRESS", "BTES TRANSFERRED")
print " " * 60
report_dict = generate_log_report(file_obj)
for ip_addr, bytes in report_dict.items():
if options.mem:
print "% 20s%s" % (obfuscate_ipaddr(ip_addr), bytes)
else:
print "% 20s%s" % (obfuscate_ipaddr(ip_addr), sum(bytes))
print "=" * 60
|  $  &   , %      & #&  
    , %   &   #"      & :
jmjonesYer:/data/logs$ time ./summarie_logfiles_mem.py mem
access_bigger.log
************************************************************
access_bigger.log

IP ADDRESS BTES TRANSFERRED

190.q0.10.0 699160000
snip�
190.20.250.250 2z^qq0000
============================================================
real 0mz0.508s
user 0m29.866s
sys 0m0.6z6s
;  &'       &     &    
 &  4 H . |         # 2  
! '  $   . @  %   $  !   
 #      #"  $ ,       # 
      %  ?     &   & ,    
492
 14.      
   .  ,   #  & ( & (  #$ &
 #, '  %     # IP  ,    
 &       %   %  #( IP   .
{ ?    &   &    "    ,    
$  #  #   # (  (,  '  &
   $  (,    Berkeley [B.
@  GTP
     $ ,   & #&      ]TP   
  % #  !  
   , %&    
  ,  &    #$   .    ,   
 $ &  & # !    ,     % .   
' $  #&    : %  '     F $  
 #$&   #    # rsyncF.     : Y,   . 
  #,    
rsync
       ,     
,       % , %     # F +|  % &
      ,   '  .- )   #, 
        ,      #  % # !,
%  $ SSV  rsyncF   (  &(     
' # #   . )(    & $   & 
  & ' :
#!/usr/bin/env python
import ftplib
import os
class FTPSync(object):
def __init__(self, host, username, password, ftp_base_dir,
local_base_dir, delete=False):
self.host = host
self.username = username
self.password = password
self.ftp_base_dir = ftp_base_dir
self.local_base_dir = local_base_dir
self.delete = delete

self.conn = ftplib.FTP(host, username, password)
self.conn.cwd(ftp_base_dir)
try:
os.makedirs(local_base_dir)
except OSError:
pass
os.chdir(local_base_dir)
def get_dirs_files(self):
dir_res = []
self.conn.dir('.', dir_res.append)
files = [f.split(None, 8)[ 1] for f in dir_res if f.startswith(' ')]
@  FTP
493
dirs = [f.split(None, 8)[ 1] for f in dir_res if f.startswith('d')]
return (files, dirs)
def walk(self, next_dir):
print "alking to", next_dir
self.conn.cwd(next_dir)
try:
os.mkdir(next_dir)
except OSError:
pass
os.chdir(next_dir)
ftp_curr_dir = self.conn.pwd()
494
 14.      
options.remote_dir, options.local_dir, options.delete)
f.run()
|   &      #$   .    
    #   .    #&    
 ,     (     # &     (   +
host
&  #$  & +
username
-   # +
password
-.  
ftp_ba
se_dir

local_base_dir
   &, %       #&    
                #  # . 
 
delete
 % !,   $ ,   & 
 & # !           ( $$ .    
      , %       % 
 & $% 
False
       ( $%       ?   & &
     $     ]TP   $  &   &.
    & &   (  %#          
   %#      #  #  .  ' %  
  #   (          #  #  ,  
 %   &  $  #  . {    '    , 
 %   % 
OSError
,    &   .
   & &    #(  :
get_dirs_files()
walk()

run()
get_dirs_files()
 & ,   ! ( 
& &          $ ( && & % !
,      . +    $ #,         #
#  %   ,        UNIX.-  
  ,   $ !  && & % !,     
 ,  $  &    
     (  %   
 . {    
, $% ,    .
{    
, $% ,  !. J &         #
$  %      $ #&    %(
   .
   ,       ,  
walk()
    & & &  &  . H
walk()

     :     ,    &
   #.  ' %   #& 
#" ,  , %   
& ! &.   $ #   &. {     
 '    , 
walk()
 '   (. H
walk()
%   (    $ 
        . 
  & &   (   
      #  
#  ,   ,  %  (   ,     $  &.  
&  $&     ]TP    #  #   (&
&     (
ftp_curr_dir

local_curr_dir
&     
 #$ &. Y    #  
get_dirs_files()
,   '
   # " ,  $  &  %    !     
 . $  '  !      $  &    #  
 ]TP
@  FTP
495
 & &    !.    & &   (  
          ]TP    #  #   $
 & 
walk()
& (  '  '(    .   (  
     & & &  , %    $  $  
( $    
walk()
 $#   '     ,
  .
    ,  
    ,  
run()
run()
 $   % # &   .    $  
walk()
         ]TP.
       # &  ( &   "
   % #(  . 
 (,      &
#  #               #$  #
'    % #   %,      ,  (     
     (  ,    #$  &   &. {  
$  (         #,   % #   $ 
" &       " .    ,   $ "  % 
 ,      &  
 $$ # !. @  #, 
%    &    # $$ !,   %  %  ,
       $ " &. {   $ " 
     ,   & $$ 
! ,     $
     $$ !,  '  $' .
    $  #   
,      , % 
!  $'  # % % ,          
  .
% 
& '  
  & !     $     % !    
    ' $ #&   $  . {   ,   
     #&  $%  , %   & #   %
(  " &   &   
,      ,  #
, %    #, %  (    ,    
  % # .  &$ Python !  && & % ? 
,  #   '    #
(   #&     ?
,   %    # && & ? .  
   1.
% .  A + - +
In [1]: def foo():
...: print foo
...:
...:
In [2]: foo
Out[2]: function foo at 0x12zz2^0�
In [z]: type(foo)
Out[z]: type 'function'�
In [q]: dir(foo)
Out[q]:
['__call__',
'__class__',
'__delattr__',
'__dict__',
'__doc__',
'__get__',
'__getattribute__',
'__hash__',
'__init__',
'__module__',
'__name__',
'__new__',
'__reduce__',
'__reduce_ex__',
, *  "
497
'__repr__',
'__setattr__',
'__str__',
'func_closure',
'func_code',
'func_defaults',
'func_dict',
'func_doc',
'func_globals',
'func_name']
    ! ,   
$      
,    $ . &#  & ! ,  '  
% # $% & (    ! ,    ,  '
 #& !      ,   $    2.
% =. -   A  %
In [1]: def foo():
...: """K    -  """
...: print "IN FUNCTION FOO"
...:
...:
In [2]: foo
Out[2]: function foo at 0x8z195zq�
In [z]: foo.__doc__
Out[z]: 'this is a docstring'
In [q]: bar = foo
In [5]: bar
Out[5]: function foo at 0x8z195zq�
In [6]: bar.__doc__
Out[6]: 'this is a docstring'
In [^]: foo.a = 1
In [8]: bar.a
Out[8]: 1
In [9]: foo()
IN FUNCTION FOO
In [10]: bar()
IN FUNCTION FOO
 #   $   & ! &
foo
,  %    '   
    &.      $&, %    &

 $ #  # %  $  ! 
foo
.  &$ Python
, %    %  #  
 ,    #   &&
&    ,  $ + &-   
 ? .    &   ?  $ & &
$   .   ,     $  ! 
,   
498
  
   $  ? ! ,  $  &$     
  #$ "#       %  IPython, %   % #
  !    
foo
,   %    ,
%  ! &
foo
. )   , %   %   $ ' 
   
bar
,    , %  ! &
foo
. H    $% 
    ! 
foo
     #&      #  
bar
. K $    
foo

    $#  .
 $       ,    #$  !     
$ ,   5  .   %
!   %     ,
      $      ,     
 #$   &
ftplib
,   %   $   &
  &    #   & $    ' ' "& #
 $ '        #$  
    . Y' 
    , %       &  #$  # ! 
   $ ,           " &   
  ( $ "   #      &
 #"    #.
*! " 
  
+     "-,
      #  ,
105
 +   # $ -,   
      % , 64
 +     #( $ -,
      
  % , 65
uickref,  , 59
TAB,    #  #, 58
+   !-,  $    , 103
F +   # $ -,  % 
 , 34, 58
_ +   %  &-
  (    (, 67
__, +     %  &-,
? , 88
___, +     %  &-,
? , 88
Active [irectory,  #$  $
    &$ Python, 482
alias, ! & + #&-, 61, 95
Apache,   
$ '  + -, 146
   !  ! 
+ -, 131
appscript,  , 294
ARP,  , 271
asr,   , 296
attrib,   +ElementTree-, 155
bookmark, ! & + #&-, 69
Boto + ' Amazon-, 301
Buildout,    , 335
$    #$  , 339
bzip2,    ' &, 248
call+-, ! & +subprocess-, 351
cd, ! & + #&-, 68
close+-,  , 136
close+-,  +shelve-, 434
500
 " $
easy_install,  #, 315
  #     , 318
easy_install,   , 48
edit, ! & + #&-, 55
.egg, ! + -, 48
eggs, ! 
&  &  , 314, 324
 $  #  ! .py
  , 322
ElementTree,  , 153
email,  , 181
end+-,  , 130
endswith+-,  , 109
__enter__+-,  , 136
EPM,   '   , 344
exec_command+-,  , 207
__exit__+-,  , 136
fields+-,  , 75
file, ? ,  $  , 135
filecmp,  #, 230
find+-,  , 108
find+-,  +ElementTree-, 155
findall+-,  , 121, 125, 126
findall+-,  +ElementTree-, 155
finditer+-,  , 126
fnmatch,  #, 239
fork+-,  , 385
]TP, $   , 492
ftplib,  #, 195
gdchart,  #, 174
get+-,  +ElementTree-, 155
getresponse+-,  + # httplib-, 195
glob,  #, 239
GNU�Linux,   &  
PyInotify,  #, 291
      Red Vat
Linux, 298
      Ubuntu,
299
     Windows
$Linux, 309
Google App Engine, 302
grep+-,  , 74
groupdict+-,  , 130
groups+-,  , 130
gzip, '  , 248
Vardwareqomponent, , 415
VBox +PyGT\-, 397
hist, ! &, 91
VTML,  %  $ !   ReST, 169
httplib,  #, 193
IMAP,  , 161
imaplib,  #, 162
import,   &, 39
In,   &    &, 52, 53
in,   , 107
index+-,  , 108
__IP,    &, 66
IPAddress,  +[jango-, 417
ipy_user_conf.py, !, 56
IPython,   &   % , 45, 48
edit, ! & + #&-, 55
  $&    &, 95
$    IPython, 49
 $ '  #   &, 54
$$      , 29, 46
 &  , 90
   , 56
  ! , 81
.ipython,   , 56
IPython,      #$   , 45
join+-,  , 116
L[AP,  #$  $    
&$ Python, 482
L[I] !,     , 483
listdir+-, ! & + # os-, 232
lower+-,  , 113
ls+-, ! & +Scapy-, 217
lsmagic, ! & + #&-, 57
lstrip+-,  , 110
macro, ! & + #&-, 95
magic, ! & + #&-, 58
 " $
match+-,  , 126
mglob,  , 80
MIB +Management Information Base
$ &  ! -, 253
Mq +Modeliewqontroller  #
        -, 405
MT +ModeliewTemplate  #
    " -, 405
n,        , 105
__name__,    &, 88
502
 " $
ReportLab,  , 178
__repr__,       , 106
reuest+-,  + # httplib-, 195
reset, ! & + #&-, 97
ReST +reStructuredText- !  , 169, 330
 $   !  VTML, 169
ReSTless,   , 330
 " $
U[P    &    SNMP, 252
upper+-,  , 113
urllib,  #, 145, 197
urllib2,  #, 199
Box +PyGT\-, 397
virtualenv,    , 339
Mware, 300
web2ldap,    , 484
who, ! & + #&-, 88
who_ls, ! & + #&-, 88
whos, ! & + #&-, 89
with,   &, 136
wrapper+-, ! & +curses-, 401
write+-,  , 136, 139
writelines+-,  , 139
XMLRPq, 200
AML, !  (, 437
Zenoss API, 254
     Windows $
Linux, 309
Zenoss,      ! , 276
ZO[B,  #, 441
K    +Aaron Villegass-, 164
  $&    &, 95
  $&    $ &
$ , 296
  $   
! , 160
  $   
     % , 161
  %      
 , 296
   
Red Vat Linux, 298
Solaris, 299
Ubuntu, 299
 &  &  , $   , 322
$ ' , 146
   !,  $    , 103
(  (, 246
     '  !  TAR,
249
  ! &
     , 323
   SMTP, 181
     ,
    , 55
     +Perspective
Broker-,  ($, 213

       , 140
  ' &,  $  , 403
 ' Amazon    Boto, 301
$    IPython, 49
$  &  '    , 199
  +ille ainio-, 47
 $&, 300
 # ' &,     ,
342
 ' & +  &  % -,
 , 183
      % 
         
&$ Python, 470
     (, 246

       , 140
  $#    IPython   Python,
$    (   , 199
Pyro,  ! , 202
XMLRPq, 200
     , 30
    (  , 64
    ? , 228
      SNMP
+ $  -, 270
504
 " $
 ,  $  , 174
!%    ! ,  $  , 390
[jango,  !  $   
 ' , 404
  ' &, 403
 '  $ ( + -,
413
 '  &    !
'     Apache
   # curses, 398
   # [jango, 405
   # PyGT\, 394
  +   ' 
PyGT\-, 392
&, 390
 , 221
os,  #, 222
rsync,   , 241
(  , '  ,
'        , 246
  ,      ,
         , 224
   , 244
?   (, 233
  " , 239
 ,     !, 226
  , 230
 , 384
  (
     #  &
shutil + -, 224
        #  &
shutil + -, 225
      #  & shutil
+ -, 226
 #&    
     ! , 240
    , 235
( $&    #   
rsync, 241
Y' *  +`im ]ulton-, 335
,  $  , 174
   , ! &, 54
$      ,  , 82
$$  IPython, 29, 46
$ '    &  , 376
$#  !, 139
$
 , 384
      % , 31
$   ]TP, 492
  !   ?  +OI[-, 253
$ %  ( $   , 107
      , 107
$ %   $   , 109
$        , 113
   
  , 31, 32
! L[I], 483
  $&  '  
#  , 263
 & ! ( ! ,
477
       (,
260
 %   '   $% , 263
 &  , 90
 &  $#  , 93
% ,  $    , 103
   N]S  (   , 283
     Python +Python Package
Index, PyPI-, 26
  
(  , 246
(    #  & os, 226
?    #     , 233
   " , 239
( $&    #   
rsync, 241
     #  &
filecmp, 230
,   ! &
  # pwd, 72
      
    ( 
  , 321
   +\evin Gibbs-, 302
% ssh, 282
  $ ,  #$ 
  #  & subprocess, 352
  &, 90
 " $
 &   %  UNIX, 61
 +   # $ -, 65
 +     #( $ -, 65
alias, ! &, 61
bookmark, ! &, 69
cd, ! &, 68
dhist, ! &, 71
pwd, ! &, 72
rehash, ! &, 65
rehashx, ! &, 67
sh,  !#, 77
    (  , 64
    , 73
        (, 72
 &   , 459
qonfigParser,  #, 477
optparse,  #, 462
      % , 470
 & ! (
! , 477
   #$ &  
      , 460
  &   , 116
!  !, 
    , 323
!   '   ,
   , 339
  !  
     , 285
  !  
    &$ Python
UNIX, 279
 & ,  $  , 175
  '    , 136
   , 244
  $ %  #
     &, 365
   , 378
    %  , 104
$   #   , 115
 
    , 31, 32
 &  #$  Python, 28
    IPython, 56
 !      , 105
  &( ' &(, 124
      " &
 , 50
  , 31
      , 31
         
    &  &$ Python,
470
%&   ( +cloud
computing-, 301
 ' Amazon    Boto,
301
    , 319
       , 377
    , 73
 %    , 391
(   MIB, 258
?      , 116
?   (, 233
?   & &   &
+ObjectRelational Mapping, ORM-, 452
?   & + MIB-, 253
    , 278
OS X, 293
PyInotify,  # �& GNULinux,
291
     
Red Vat Linux, 298
Solaris, 299
Ubuntu, 299
 $&, 300
  !  
    &$
Python  UNIX, 279
%&   ( +cloud
computing-, 301
     Windows $
Linux, 309
       
 , 280, 285
  Python, 29
     , 30
    #$ 
   , 39
! , 35
   #$ &  
      , 460
  % ssh,  $  , 282
'  (, 246
506
 " $
   &$ Python, 35
%  ,     &, 370
 
  (  $   , 26
     !   , 319
  %      % , 180
     !    #&(
   , 240
     ! 
   #    rsync, 241
   $  $ , 296
  $     , 382
    #$    
, 39
   (, 222
 '  readline, 90
        (, 72
 
    , 107, 117
  & ' &, 120
    ? & (
  (, 235
?   &  + -, 265
!        " , 239
    &, 365
"     IPython
Python, 52
       % , 161
 '  $ (,  $ 
  # [jango + -, 413
 '  &    !
'     Apache
   # curses, 398
   # [jango, 405
   # PyGT\, 394
       + -, 188
  #$   Twisted, 211
  #$    & socket, 188
   & OS X, 293
  &  $&, 428
pickle,  #, 428
shelve,  #, 434
AML, !  (, 437
ZO[B,  #, 441
Pickle,  , 433
   &$  Python, 28
 !, 77
  , 350, 378
subprocess  #, 350
 #$    $ ,
 , 384
   $ %  #, 378
  $ , 382
    &, 365
     #  
screen, 364
     #  
Supervisor, 361
$  XML    #  
ElementTree, 153
$  , $    , 113
    ! , 180
   '     
 % , 183
  %      % , 180
 & ' &, 120
  !      , 124
 $    , 222
     '  !  TAR,
249
 $#    &, 93
 & &  $&, 448
SQLAlchemy ORM, 456
SQLite,  , 449
Storm ORM, 452
%    ! , 163
 , $    ,    
 , 323
  ! , 81
  $ , 160
%, 163
       % , 161
&$  , 497
 $&
  &, 428
pickle,  #, 428
shelve,  #, 434
AML, !  (, 437
ZO[B,  #, 441
Pickle,  , 433
 & &, 448
SQLAlchemy ORM, 456
 " $
SQLite,  , 449
Storm ORM, 452
   ' &, & 
  &, 209
 , 186
ftplib,  #, 195
httplib,  #, 193
Scapy,  , 216
 $    , 219
508
 " $
  , 103
Apache, $ '  + -,
146
Apache,    ! 
!  + -, 131
$ %  (
      , 107
$        , 113
 !      , 105, 124
?   +   &-, 116
      , 107
 & ' &, 120
$    
$  &, 113
 $  +  str-, 103
 $  + -, 118
    , 118
    (  $ "(
  #(   , 110
    '  , 110
       , 51
   , 329
    , 65, 67
     , 376
  !
   !, 134
$ ' , 146
$#  !, 139
$  XML    #
  ElementTree, 153
%  $ ! , 137
 $  ! , 135
   
  ! &, 72
  %   ,    
    ( 
 , 321
 &  &, 93
%  ( , 329
  % , 104
  
 (  $ "(
  #(       (,
110
$  , 70
   ( $    
     , 97
 '    , 110
 (& (    (, 97
! , 235
  [NS    #   
 &$ Python, 480
   , 313
Buildout,    , 335
EPM,   '   , 344
virtualenv,    , 339
  &    Python Package
Index, 330
 $       #
distutils, 332
     Windows $
Linux, 309
      %  $ SNMP,
275
&  ,    ssh,
284
    
 Perl  Bash, 23
    IPython, 29, 46
       !   ,
319
!
(  , 246
   , 244
(    #  & os, 226
?    #     , 233
       #&(
   , 240
   " , 239
   !, 134
$ ' , 146
$#  !, 139
$  XML    #
  ElementTree, 153
%  $ ! , 137
 $  ! , 135
     #  &
filecmp, 230
   , 235
*    $ +]ernando Perez-, 46
!    ', 259
!    ! , 174
 (    !  P[], 178
 " $
! , 35
!     $ , 496
! &    &, 33
%  $ ! , 137
"   #$ & optparse
Tr�ue]alse, 464
 $ % , 462
 %  %   , 466
   $%   ,
467
  #    , 469
"    &   $
      
 &  &$ Python
$    (   &, 473
      
 &  &$ Python
  '      , 475
"    &  $, 471
      
 &  &$ Python, 471
      
 &  &$ Python
$    (   &, 473
      
 &  &$ Python
  '      , 475
      #  ,
105
  &  % 
+( &&-,  , 161
+( &&-, $#, 180
   ' , 183
^ J  +Ian Bicking-, 340
             
 Books.Ru          
        !  ISBN 9785932861493,   
 Python          UNIX Linux 
!!       Books.Ru    . " # 
      ! !      , #  $ 
   !   !    !
%   &  '  !   . #   '    
   ,  ! (      
)[email protected]*,    #      .

Приложенные файлы

  • pdf 11183374
    Размер файла: 4 MB Загрузок: 0

Добавить комментарий