OSA Unit - IV

Views:
 
Category: Education
     
 

Presentation Description

Operating System and Administration:Booting and Shut Down, Scripting and Shell

Comments

Presentation Transcript

Booting and Shut Down, Scripting and Shell:

Booting and Shut Down, Scripting and Shell Reference: UNIX AND LINUX SYSTEM ADMINISTRATION HANDBOOK Authors : Evi Nemeth Garth Snyder Trent R. Hein Ben Whaley

Index:

Index Bootstrapping: Booting PCs, GRUB, Booting with single user mode, Rebooting and Shutting down. Shell Basics, bash scripting, Regular Expression, Perl Programming, Python Scripting, Scripting Best Practices, Working with Startup Scripts. 2

Booting and Shutting Down:

Booting and Shutting Down Bootstrapping The computer must pull itself up During bootstrapping, the kernel is loaded into memory and begins to execute. When a computer is turned on, it first executes boot code that is stored in ROM Before the system is fully booted, file systems must be checked and mounted, and system daemons started. Steps in the boot process Reading of the boot loader from the master boot record Loading and initialization of the kernel Device detection and configuration Creation of kernel processes Administrator intervention (single-user mode only) Execution of system startup scripts 1- 3

Booting and Shutting Down:

Booting and Shutting Down Kernel initialization Pathname is vender dependent Traditional /vmunix Two steps loading ROM loads a small boot program into memory from disk This program then arranges for the kernel to be loaded Memory for internal data structure is allocated Hardware configuration Check what hardware present Locate and initialize each device as specified Probe the bus for devices and ask the appropriate drivers for information. Reboot maybe needed for new devices connected later. 1- 4

Booting and Shutting Down:

Booting and Shutting Down System processes Spontaneous processes Vary from system to system On system V-ish machines: sched – process 0 init – process 1 various memory and kernel process handlers. Not real processes, but port of kernel Once the spontaneous processes have been created, the kernel’s role in bootstrapping in complete. 1- 5

Booting and Shutting Down:

1- 6 Booting and Shutting Down

Booting and Shutting Down:

Booting and Shutting Down Single user Password may or maynot be required to enter into root shell The root partition / is mounted /usr maybe mounted too You can mount other partition manually You can change the read only mount to be write-mode # mount -o rw, remount / Execution of startup scripts Normal shell scripts Process init run them according some rules 1- 7

Booting and Shutting Down:

Booting and Shutting Down Booting in single-user mode Solaris At the GRUB splash screen, highlight the desired kernel and press ‘a’ to append to the boot options boot –s HP-UX During prompt Type “boot pri isl” Then type “hpux –iS /stand/vmunix 1- 8

Booting PC:

Booting PC More complex than … Firmware in machine designed for Unix knows How to use the device connected to the machine How to talk to the network on a basic level How to understand disk based file system On PC, initial boot code is BIOS – extremely simplistic compare to the firmware Set the boot priority, try cdrom, then disk, … Load the first 512 bytes of the disk – Master Boot Record (MBR) MBR load a secondary boot program (“boot loader”) from a disk partition Lilo (Linux Loader) Grub (Grand Unified Bootloader) 1- 9

Grub:

Grub Powerful boot loader Is designed to address the complexity of booting a personal computer A wide variety of free OS + proprietary OS How to boot OS’ Loading an OS directly Chain-loading Naming convention The first hard disk partition 1: (hd0,1) (hd0,0)/vmlinuz 1- 10

Loading OS from Grub:

Loading OS from Grub Grub can boot any multiboot-compliant OS in the steps directly: Set root device with command root Load the kernel image with command kernel Append parameters to kernel after the filename Load modules with module Run the command with boot Example: title GNU/Linux Kernel (hd1,0) /vmlinuz root=/dev/hdb1 1- 11

Loading OS from Grub:

1- 12 Loading OS from Grub

Grub’s user interface:

Grub’s user interface Menu interface Choose preconfigured Edit the configuration Command line flexible. – do what ever you need Get into the interface Interrupt before the timeout timeout sec 1- 13

Exercise:

Exercise Take a look at your grub configuration file /etc/grub.conf what is the root device Get into the grub menu interface Get into the grub command line 1- 14

Rebooting and shutting down:

Rebooting and shutting down The need to reboot/shutdown Scheduled maintenance, such as OS upgrade Hardware changes or additions Running diagnostics Performance tunning, such as changing static system configuration Administrative tasks, such as testing new startup scripts, etc. System not responding 1- 15

Rebooting and shutting down:

Rebooting and shutting down Clean system shutdown All users are notified, with some reasonable advance warning. All running process are sent a singal to exit gracefully, provided the program has mage provisions to do so All subsystems are shutdown gracefully All remaining users are logged off and remaining process are killed File system integrity is maintained Depending on the type of shutdown, the system moves to single-user mode, the processor is halted, or the system is rebooted… 1- 16

Rebooting and shutting down:

Rebooting and shutting down Ways to shutdown or reboot Turn off power Use shutdown command Use halt or reboot commands Sending init a TERM signal Using telinit to change init’s run level Killing init 1- 17

The shell of Linux:

The shell of Linux Linux has a variety of different shells: Bourne shell (sh), C shell (csh), Korn shell (ksh), TC shell (tcsh), Bourne Again shell (bash). Certainly the most popular shell is “bash” . Bash is an sh-compatible shell that incorporates useful features from the Korn shell (ksh) and C shell (csh) . It is intended to conform to the IEEE POSIX P1003.2/ISO 9945.2 Shell and Tools standard . It offers functional improvements over sh for both programming and interactive use .

Programming or Scripting ?:

Programming or Scripting ? bash is not only an excellent command line shell , but a scripting language in itself. Shell scripting allows us to use the shell's abilities and to automate a lot of tasks that would otherwise require a lot of commands. Difference between programming and scripting languages : Programming languages: more powerful and a lot faster than scripting languages . Programming languages generally start from source code and are compiled into an executable . A scripting language : also starts from source code, but is not compiled into an executable . Rather, an interpreter reads the instructions in the source file and executes each instruction .

The first bash program :

The first bash program There are two major text editors in Linux: vi, emacs (or xemacs). So fire up a text editor; for example: $ vi & and type the following inside it: #!/bin/bash echo “Hello World” The first line tells Linux to use the bash interpreter to run this script. We call it hello.sh. Then, make the script executable: $ chmod 700 hello.sh $ ./hello.sh Hello World

The second bash program :

The second bash program We write a program that copies all files into a directory, and then deletes the directory along with its contents. This can be done with the following commands: $ mkdir trash $ cp * trash $ rm -rf trash $ mkdir trash Instead of having to type all that interactively on the shell, write a shell program instead: $ cat trash.sh #!/bin/bash # this script deletes some files cp * trash rm -rf trash mkdir trash echo “Deleted all files!”

Variables :

Variables We can use variables as in any programming languages. Their values are always stored as strings , but there are mathematical operators in the shell language that will convert variables to numbers for calculations . We have no need to declare a variable , just assigning a value to its reference will create it. Example #!/ bin/bash STR =“Hello World!” echo $STR Line 2 creates a variable called STR and assigns the string "Hello World!" to it. Then the value of this variable is retrieved by putting the '$' in at the beginning.

Single and Double Quote:

Single and Double Quote When assigning character data containing spaces or special characters, the data must be enclosed in either single or double quotes. Using double quotes to show a string of characters will allow any variables in the quotes to be resolved $ var=“test string” $ newvar=“Value of var is $var” $ echo $newvar Value of var is test string Using single quotes to show a string of characters will not allow variable resolution $ var=’test string’ $ newvar=’Value of var is $var’ $ echo $newvar Value of var is $var

Read command:

Read command The read command allows you to prompt for input and store it in a variable. Example: #!/bin/bash echo -n “Enter name of file to delete: ” read file echo “Type 'y' to remove it, 'n' to change your mind ..” rm -i $file echo "That was YOUR decision!” Line 2 prompts for a string that is read in line 3. Line 4 uses the interactive remove ( rm -i ) to ask the user for confirmation.

Arithmetic Evaluation :

Arithmetic Evaluation The let statement can be used to do mathematical functions : $ let X=10+2*7 $ echo $X 24 $ let Y=X+2*4 $ echo $Y 32 An arithmetic expression can be evaluated by $[expression] or $((expression)) $ echo “$((123+20))” 143 $ VALORE=$[123+20] $ echo “$[123*$VALORE]” 17589

Arithmetic Evaluation :

Arithmetic Evaluation Available operators : + , - , / , * , % Example $ cat arithmetic.sh #!/bin/bash echo -n “Enter the first number: ”; read x echo -n “Enter the second number: ”; read y add=$(($x + $y)) sub=$(($x - $y)) mul=$(($x * $y)) div=$(($x / $y)) mod=$(($x % $y)) # print out the answers: echo “Sum: $add” echo “Difference: $sub” echo “Product: $mul” echo “Quotient: $div” echo “Remainder: $mod”

Conditional Statements:

Conditional Statements Conditionals let us decide whether to perform an action or not, this decision is taken by evaluating an expression. The most basic form is: if [ expression ]; then statements elif [ expression ]; then statements else statements fi the elif (else if) and else sections are optional Put spaces after [ and before ], and around the operators and operands.

Expressions:

Expressions An expression can be: String comparison , Numeric comparison , File operators and Logical operators and it is represented by [expression] : String Comparisons: = compare if two strings are equal != compare if two strings are not equal -n evaluate if string length is greater than zero -z evaluate if string length is equal to zero Examples: [ s1 = s2 ] (true if s1 same as s2 , else false) [ s1 != s2 ] (true if s1 not same as s2 , else false) [ s1 ] (true if s1 is not empty , else false) [ -n s1 ] (true if s1 has a length greater then 0 , else false) [ -z s2 ] (true if s2 has a length of 0 , otherwise false)

Expressions:

Expressions Number Comparisons: -eq compare if two numbers are equal -ge compare if one number is greater than or equal to a number -le compare if one number is less than or equal to a number -ne compare if two numbers are not equal -gt compare if one number is greater than another number -lt compare if one number is less than another number Examples: [ n1 -eq n2 ] (true if n1 same as n2 , else false) [ n1 -ge n2 ] (true if n1greater then or equal to n2 , else false) [ n1 -le n2 ] (true if n1 less then or equal to n2 , else false) [ n1 -ne n2 ] (true if n1 is not same as n2 , else false) [ n1 -gt n2 ] (true if n1 greater then n2 , else false) [ n1 -lt n2 ] (true if n1 less then n2 , else false)

Expressions:

Expressions Files operators: -d check if path given is a directory -f check if path given is a file -e check if file name exists -r check if read permission is set for file or directory -s check if a file has a length greater than 0 -w check if write permission is set for a file or directory -x check if execute permission is set for a file or directory Examples: [ -d fname ] (true if fname is a directory , otherwise false) [ -f fname ] (true if fname is a file , otherwise false) [ -e fname ] (true if fname exists , otherwise false) [ -s fname ] (true if fname length is greater then 0 , else false) [ -r fname ] (true if fname has the read permission , else false) [ -w fname ] (true if fname has the write permission , else false) [ -x fname ] (true if fname has the execute permission , else false)

Example:

Example #!/bin/bash if [ -f /etc/fstab ]; then cp /etc/fstab . echo “Done.” else echo “This file does not exist.” exit 1 fi Exercise. Write a shell script which: accepts a file name checks if file exists if file exists, copy the file to the same name + .bak + the current date (if the backup file already exists ask if you want to replace it). When done you should have the original file and one with a .bak at the end.

Expressions:

Expressions Logical operators: ! negate ( NOT ) a logical expression -a logically AND two logical expressions -o logically OR two logical expressions Example: #!/bin/bash echo -n “Enter a number 1 < x < 10:” read num if [ “$num” -gt 1 –a “$num” -lt 10 ]; then echo “$num*$num=$(($num*$num))” else echo “Wrong insertion !” fi

Expressions:

Expressions Logical operators: && logically AND two logical expressions || logically OR two logical expressions Example: #!/bin/bash echo -n "Enter a number 1 < x < 10: " read num if [ “$number” -gt 1 ] && [ “$number” -lt 10 ]; then echo “$num*$num=$(($num*$num))” else echo “Wrong insertion !” fi

Shell Parameters :

Shell Parameters Positional parameters are assigned from the shell’s argument when it is invoked. Positional parameter “ N ” may be referenced as “ ${N} ”, or as “ $N ” when “ N ” consists of a single digit. Special parameters $# is the number of parameters passed $0 returns the name of the shell script running as well as its location in the file system $* gives a single word containing all the parameters passed to the script $@ gives an array of words containing all the parameters passed to the script $ cat sparameters.sh #!/bin/bash echo “$#; $0; $1; $2; $*; $@” $ sparameters.sh arg1 arg2 2; ./sparameters.sh; arg1; arg2; arg1 arg2; arg1 arg2

Example (case.sh):

Example (case.sh) $ cat case.sh #!/bin/bash echo -n “Enter a number 1 < x < 10: ” read x case $x in 1) echo “Value of x is 1.”;; 2) echo “Value of x is 2.”;; 3) echo “Value of x is 3.”;; 4) echo “Value of x is 4.”;; 5) echo “Value of x is 5.”;; 6) echo “Value of x is 6.”;; 7) echo “Value of x is 7.”;; 8) echo “Value of x is 8.”;; 9) echo “Value of x is 9.”;; 0 | 10) echo “wrong number.”;; *) echo “Unrecognized value.”;; esac

Using Arrays with Loops:

Using Arrays with Loops In the bash shell, we may use arrays . The simplest way to create one is using one of the two subscripts: pet[0]=dog pet[1]=cat pet[2]=fish pet=(dog cat fish) We may have up to 1024 elements . To extract a value, type ${arrayname[i]} $ echo ${pet[0]} dog To extract all the elements , use an asterisk as: echo ${arrayname[*]} We can combine arrays with loops using a for loop: for x in ${arrayname[*]} do done

What is Perl?:

What is Perl? Perl is a general-purpose programming language, and can be used for practically any programming task any other high-level language can be used for. However, Perl is usually thought of as a “glue” language, so called because it binds things together (such as tying databases to Web pages, converting files from one format to another, and so on). Perl is very flexible and is currently available on over two dozen operating system platforms

Perl:

Perl The name Perl comes from “Practical Extraction and Report Language”. Perl has many features borrowed from other programming languages. The Perl system uses an interpreter, called “perl”. Usually Perl and perl are considered to be the same thing for practical purposes.

Installing Perl:

Installing Perl

Versions of Perl:

Versions of Perl The current versions of Perl are all in the 5.X and 6.X series (6.X was released in 2001). If you have an older version of Perl (such as Perl 4.X), you should upgrade it as many changes were made between releases. Perl 4.X was a very buggy release of Perl and should not be used. Also, many Perl programs designed for 5.X will not work with 4.X.

Maybe Perl is already installed:

Maybe Perl is already installed Many operating systems (Linux and UNIX notably, but also Windows NT Resource Kit) come with Perl installed. You can easily check whether Perl is loaded on your system by opening a console or terminal window and issuing the command: perl –v If you get a version number, Perl is installed. If you get an error message about command not found (or something similar), Perl is not installed.

More on perldoc:

More on perldoc The Perl documentation is divided into parts by purpose: perlfunc (Perl functions) perlfaq (Perl FAQs) perlop (Perl operators) To search for a particular keyword, use the –tf options. For example to look up the print keyword: perldoc –tf print To search the FAQs use –q as an option: perldoc –q free

A first Perl program:

A first Perl program

What you need:

What you need When you have installed Perl on your system, all you need to use the language is a text editor that can save ASCII files. All Perl scripts are written and saved in ASCII characters. On some operating systems that do not have a Perl GUI front end, you will need to use a console or terminal window to interact with Perl. Some GUI-based Perl front ends are available for Linux, UNIX, Macintosh and Windows.

Comments in Perl:

Comments in Perl All comments in Perl are written starting with a # sign. Anything after the # sign through to the end of the line is ignored by the interpreter. Comments can be placed anywhere on the line, but commands cannot follow a comment on the same line Multiline comments should have a # symbol as the first character on every line

The #! directive:

The #! directive The sole exception to # indicating a comment is on the first line of a Perl program (or “script”). All Perl programs can begin with the line: #!/usr/bin/perl The #! is a hold-over from UNIX that instructs the operating system to use the /usr/bin/perl program to run whatever is in this file The path may be different for your system, and many environments such as Windows do not need this line. However, it will not cause errors.

Semicolons:

Semicolons All valid Perl command lines end in semicolons. Without a semicolon, Perl continues to read onto the next line and doesn’t assume a carriage-return is the end of a statement. You can break Perl commands over multiple lines because of this, as long as a semicolon is the end character in the complete statement. Perl uses semicolons in the same way as C/C++ and Java

Whitespace:

Whitespace Whitespace is ignored by the Perl intepreter. You can use whitespace (spaces and tabs) anywhere in your programs to make them more readable. You should use whitespace to help format your scripts to show loops, logic layout, and continuation of statements, as you will see later in this course

The print command:

The print command The print function tells Perl to display whatever follows, such as a string, variable name, and so on. You’ll see how to build complex print statements later. The print statement allows the C or Java escape characters to be used for line feeds, backspace, tabs, and so on. For example, the command: print“Hello\n”; will print “Hello” followed by a newline.

A Hello World script:

A Hello World script We can write a simple Perl script for the traditional Hello World application: #!/usr/bin/perl print “Hello World!\n”; These two lines can be save in a file as ASCII and then run by perl by issuing the command: perl filename

Declaring variables:

Declaring variables Unlike many programming languages, variables do not need to be declared prior to use with Perl. When the variable is assigned an initial value, Perl can figure out the data type. If you try to use an uninitalized variable, Perl will use the value zero for a numeric, or Null for a string. Avoid uninitialized variables as much as possible, as results can be unpredictable.

Assigning values:

Assigning values Variables are assigned values using the equal sign: $string1=“This is a test”; $var1=6; $var2=3.14159; You can assign operation results, as you would expect: $var3=$var2 + $var1;

The $_ variable:

The $_ variable The $_ variable is used by Perl as a default variable. You can use it in place of variable names in your scripts: $_=“This is a test”; print; This will print the default variable $_ and display the string. Use the default operator carefully as it can easily be confusing, but some operators and functions work best with default variables, as you will see later in this course.

Perl operators:

Perl operators

Standard operators:

Standard operators Perl supports the standard mathematical operators +, -, *, /, % (modulus) and ** (exponent) Operator order of precedence applies according to standard rules; parentheses group operations Operators can be combined in statements: $num1=$num2 * ((3 + 8)*$num3/2); Multiple assignments can be made on one line: $num1=$num2=$num3=7;

Positive and negative:

Positive and negative Numbers are assumed to be positive unless you specify a negative sign in front: $num1=6; # positive $num2=-6; # negative $num3=-(-6); # positive You can convert positive to negative any time using the minus sign in front of the variable: $num4=-$num4;

Increment and decrement:

Increment and decrement Like C/C++ and Java, Perl supports autoincrement and autodecrement operators, which increase or decrease a value by one: $var1++; is the same as $var1=$var1+1; and $var2--; is the same as $var2=$var2-1;

Shortform assignment:

Shortform assignment As with autoincrement and autodecrement, Perl supports shortform assignments like this: $var1+=5; which is the same as $var1=$var1 + 5; This can be performed for all four basic mathematical operators.

Operators and strings:

Operators and strings Strings can be used with the “.” operator for concatenation: $str1=“Hello ”; $str2=“World!”; $str3=$str1 . $str2; print $str3; would print “Hello World!” You can also concatenate on output in most cases by specifying the string variables together: print $str1 . $str2;

Converting strings to numbers:

Converting strings to numbers Perl is flexible when using string types as numbers, as long as the conversion makes sense. For example, this works: $str1=“6”; $num1=10-$str1; print $num1; will display the value 4. Perl can convert the string to a number if the string looks like a number. This applies to decimal strings as well.

Converting numbers to strings:

Converting numbers to strings Perl can also convert numbers to strings when the conversion makes sense: $num1=3; $str1=“I did it” . $num1 . “ times”; print $str1; will display the message “I did it 3 times.” If the conversion doesn’t make sense to Perl, it will use a zero instead when you try to call the number.

Code blocks:

Code blocks Perl statements can be grouped together into blocks, each block surrounded by braces (like with Java) Code blocks can be nested many deep Each code block is treated as a unit by Perl, although execution is still always top to bottom unless moderated by control structures Usually blocks will be associated with other statements, such as if conditions

Comparison operators:

Comparison operators Perl supports the standard comparison operators: > greater than < less than >= greater than or equal to <= less than or equal to == exactly equal to != not equal to

True and false:

True and false In Perl, any condition that evaluate to false is assigned a value of zero. Anything that is non-zero is true. This applies to conditions in statements (such as the if you’ll see in a moment) as well as for numeric evaluation: 0 false 3 true (non-zero) 5-5 false (evaluates to zero) 0.00 false (it’s zero with precision) “” Null string is false “ ” String with a space or anything not null is true

The if statement:

The if statement Perl’s if statement is similar to those of other high-level languages: if (condition) { do if true } else { do if false } The blocks of code can contain many statements. The else and its statements are optional. Only one block of code is executed, depending on whether the condition is true or false

Example of if:

Example of if A simple if statement is: if ( $num1 > 5 ) {print “It is greater than 5.”;} else {print “It is less than or equal to 5.”;} If there is only one statement in a block, you can leave the curly braces off as long as a semicolon is used, however many programmer use curly braces to make the code more readable

Nested if-elses:

Nested if-elses The if statement can be nested within other if statements, either inside the blocks or as part of the else: if (cond1) { if (cond2) {statements}} else { if (cond3) { statements} else {statements} }

Array:

#!/usr/bin/perl @item=(“socks”, “shoes”, “Shorts”); Printf “There are %d articles of clothing. \n”, $#items +1; Printf “Put on ${item[2]} first, then”, join (“and”, @item[0,1]), “.\n”; 1- 68 Array

Brief History of Python:

Brief History of Python Invented in the Netherlands, early 90s by Guido van Rossum Named after Monty Python Open sourced from the beginning Considered a scripting language, but is much more Scalable, object oriented and functional from the beginning Used by Google from the beginning Increasingly popular

The Python Interpreter:

The Python Interpreter Typical Python implementations offer both an interpreter and compiler Interactive interface to Python with a read-eval-print loop [finin@linux2 ~]$ python Python 2.4.3 (#1, Jan 14 2008, 18:32:40) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def square(x): ... return x * x ... >>> map(square, [1, 2, 3, 4]) [1, 4, 9, 16] >>>

Installing:

Installing Python is pre-installed on most Unix systems, including Linux and MAC OS X The pre-installed version may not be the most recent one (2.6.2 and 3.1.1 as of Sept 09) Download from http://python.org/download/ Python comes with a large library of standard modules There are several options for an IDE IDLE – works well with Windows Emacs with python-mode or your favorite text editor Eclipse with Pydev (http://pydev.sourceforge.net/)

Running Interactively on UNIX:

Running Interactively on UNIX On Unix… % python >>> 3+3 6 Python prompts with ‘>>>’. To exit Python (not Idle): In Unix, type CONTROL-D In Windows, type CONTROL-Z + <Enter> Evaluate exit()

Running Programs on UNIX:

Running Programs on UNIX Call python program via the python interpreter % python fact.py Make a python file directly executable by Adding the appropriate path to your python interpreter as the first line of your file #!/usr/bin/python Making the file executable % chmod a+x fact.py Invoking file from Unix command line % fact.py

Example ‘script’: fact.py:

Example ‘script’: fact.py #! /usr/bin/python def fact(x): """Returns the factorial of its argument, assumed to be a posint""" if x == 0: return 1 return x * fact(x - 1) print print ’N fact(N)’ print "---------" for n in range(10): print n, fact(n)

Python Scripts:

Python Scripts When you call a python program from the command line the interpreter evaluates each expression in the file Familiar mechanisms are used to provide command line arguments and/or redirect input and output Python also has mechanisms to allow a python program to act both as a script and as a module to be imported and used by another python program

Example of a Script:

Example of a Script #! / usr /bin/python """ reads text from standard input and outputs any email addresses it finds, one to a line. """ import re from sys import stdin # a regular expression ~ for a valid email address pat = re.compile (r'[-\w][-.\w]*@[-\w][-\w.]+[a- zA -Z]{2,4}') for line in stdin.readlines (): for address in pat.findall (line): print address

Getting a unique, sorted list:

Getting a unique, sorted list import re from sys import stdin pat = re.compile(r'[-\w][-.\w]*@[-\w][-\w.]+[a-zA-Z]{2,4}’) # found is an initially empty set (a list w/o duplicates) found = set( ) for line in stdin.readlines(): for address in pat.findall(line): found.add(address) # sorted() takes a sequence, returns a sorted list of its elements for address in sorted(found): print address

A Code Sample (in IDLE):

A Code Sample (in IDLE) x = 34 - 23 # A comment. y = “Hello” # Another one. z = 3.45 if z == 3.45 or y == “Hello” : x = x + 1 y = y + “ World” # String concat. print x print y

Enough to Understand the Code:

Enough to Understand the Code Indentation matters to code meaning Block structure indicated by indentation First assignment to a variable creates it Variable types don’t need to be declared. Python figures out the variable types on its own. Assignment is = and comparison is == For numbers + - * / % are as expected Special use of + for string concatenation and % for string formatting (as in C’s printf) Logical operators are words ( and, or, not ) not symbols The basic printing command is print

Basic Datatypes:

Basic Datatypes Integers (default for numbers) z = 5 / 2 # Answer 2, integer division Floats x = 3.456 Strings Can use “” or ‘’ to specify with “abc” == ‘abc’ Unmatched can occur within the string: “matt’s” Use triple double-quotes for multi-line strings or strings than contain both ‘ and “ inside of them: “““a‘b“c”””

Whitespace:

Whitespace Whitespace is meaningful in Python: especially indentation and placement of newlines Use a newline to end a line of code Use \ when must go to next line prematurely No braces {} to mark blocks of code, use consistent indentation instead First line with less indentation is outside of the block First line with more indentation starts a nested block Colons start of a new block in many constructs, e.g. function definitions, then clauses

Comments:

Comments Start comments with #, rest of line is ignored Can include a “documentation string” as the first line of a new function or class you define Development environments, debugger, and other tools use it: it’s good style to include one def fact (n): “““fact(n) assumes n is a positive integer and returns facorial of n.””” assert(n>0) return 1 if n==1 else n*fact(n-1)

Assignment:

Assignment Binding a variable in Python means setting a name to hold a reference to some object Assignment creates references, not copies Names in Python do not have an intrinsic type, objects have types Python determines the type of the reference automatically based on what data is assigned to it You create a name the first time it appears on the left side of an assignment expression: x = 3 A reference is deleted via garbage collection after any names bound to it have passed out of scope Python uses reference semantics (more later)

Naming Rules:

Naming Rules Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores. bob Bob _bob _2_bob_ bob_2 BoB There are some reserved words: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while

Naming conventions:

Naming conventions The Python community has these recommend-ed naming conventions joined_lower for functions, methods and, attributes joined_lower or ALL_CAPS for constants StudlyCaps for classes camelCase only to conform to pre-existing conventions Attributes: interface, _internal, __private

Assignment:

Assignment You can assign to multiple names at the same time >>> x, y = 2, 3 >>> x 2 >>> y 3 This makes it easy to swap values >>> x, y = y, x Assignments can be chained >>> a = b = x = 2

Accessing Non-Existent Name:

Accessing Non-Existent Name Accessing a name before it’s been properly created (by placing it on the left side of an assignment), raises an error >>> y Traceback (most recent call last): File "<pyshell#16>", line 1, in -toplevel- y NameError: name ‘y' is not defined >>> y = 3 >>> y 3

Startup scripts:

Startup scripts System V style /etc/init.d /etc/rc0.d /etc/rc1.d … Startup scripts perform Setting the name of the computer Setting the time zone Checking the disks with fsck Mounting the system’s disk Removing old files from /tmp directory Configuring the network interfaces Starting up daemons and network services 1- 88

Startup scripts:

Startup scripts Run levels: Level 0: system is completely shut down Level 1 or S: single-user mode Level 2 –5 : multiuser levels 2 or 3 are normal 4 or 5 rarely used Level 6: reboot level What to do for each level Defined in /etc/inittab 1- 89

Startup scripts:

Startup scripts The startup scripts called by inittab Individual script master copy stays in init.d, typically under /etc or /sbin Understand argument start, stop, [restart] Symbolic links are made to appropriate directories /etc/rc*.d or /sbin/rc*.d Links start with S or K followed by a number and the name of the service Example, on Fedora1 under /etc/rc3.d K20nfs -> ../init.d/nfs S12syslog -> ../init.d/syslog 1- 90

authorStream Live Help