Monday, September 26, 2011

How to get the New Facebook Timeline Profile Page

This is how the new profile page looks like :) 
 
CLICK ON "Allow"

CLICK ON "Create New App"


FILL THE TEXT BOXES
(you can provide anything you want)


CLICK ON "Open Graph"


FILL THE TEXT BOXES AND CLICK ON "Get Started"
(you can provide anything you want, here also)


YOU WILL HAVE TO TRAVERSE THROUGH MANY PAGES BEFORE YOU GET THIS
CLICK ON "Save" or  "Continue" UNTIL YOU GET THE ABOVE PAGE



WAIT FOR A FEW MINUTES AND TAKE YOUR FACEBOOK HOME PAGE
YOU WILL SEE SOMETHING AS IN THE ABOVE PICTURE
CLICK ON "Get It Now"




Now you will get the new Facebook timeline profile page. But only Facebook developers can see your timeline page. Others can only view the old type page (as of now).




Thursday, September 22, 2011

Java - GTalk Client using SMACK XMPP API



/*GtalkClient.java*/


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Iterator;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;


/**
 *
 * @author dhanoopbhaskar
 */
public class GtalkClient implements Runnable, MessageListener {
   
    ConnectionConfiguration connConfig = null;
    XMPPConnection xMPPConnection = null;
    BufferedReader readFromKeyboard = null;
    String toAddresss = null;
    String[] buddies = null;
    int buddySize = 0;


    public GtalkClient() {
        /**
         * Set the 'ConnectionConfiguration' with
         * -host name
         * -port number
         * -service name
         */
        connConfig = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com");
        /**
         * Create an instance of 'XMPPConnection' with the already created
         * instance of 'ConnectionConfiguration'
         */
        xMPPConnection = new XMPPConnection(connConfig);      
        try {
            /**
             * Connecting to the service
             */
            xMPPConnection.connect();
            /**
             * Login to the GMail account from which you want to chat
             * Provide
             * -email id
             * -password
             */
            xMPPConnection.login("user-name@gmail.com", "password");
        } catch (XMPPException ex) {
            System.out.println("Error: " + ex.getMessage());
        }
        /**
         * BufferedReader to read from the keyboard
         */
        readFromKeyboard = new BufferedReader(new InputStreamReader(System.in));
       
        displayBuddyList();
       
        System.out.println("\n\nEnter the recipient's Email Id! or "
                + "buddy id in the list");
        try {
            String temp = readFromKeyboard.readLine();
            try {
                int j = Integer.parseInt(temp);
                toAddresss = getBuddy(j);
                System.out.println("Buddy <" + toAddresss + "> selected!");
            } catch(NumberFormatException exp) {
                toAddresss = temp;
            }
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
        }
       
       
        System.out.println("Enter your chat messages one by one!");
        System.out.println("[Enter \"quit\" to end the chat!]");
       
        String msg = "";
        while(true) {
            try {
                msg = readFromKeyboard.readLine();
            } catch (IOException ex) {
                System.out.println("Error: " + ex.getMessage());
            }
           
            if(msg.equalsIgnoreCase("quit")) {
                System.out.println("--Chat Ended--");
                break;
            } else {
                sendMessage(toAddresss, msg);
            }
        }
    }


    /**
     *
     * @param recipient
     * @param message
     */
    private void sendMessage(String recipient, String message) {
        /**
         * Create an instance of 'Chat' providing the recipient's email-id
         * and an instance of MessageListener interface(The predefined
         * reference 'this' will do, since the class
         * implements the MessageListener interface.        
         */
        Chat chat = xMPPConnection.getChatManager().createChat(recipient, this);
        try {
            /**
             * Sending the chat message
             */
            chat.sendMessage(message);
        } catch (XMPPException ex) {
            System.out.println("Error: " + ex.getMessage());
        }
    }
    

      /**
       * This method belongs to MessageListener interface.
       * It listens for the incoming chat messages.
       */
    @Override

    public void processMessage(Chat chat, Message msg) {       
        String msgStr = msg.getBody();
        System.out.println("<" + chat.getParticipant() + ">  says " + msgStr);
    }
   
    public static void main(String[] args) {
        GtalkClient gtalkClient = new GtalkClient();      
    }


    @Override
    public void run() {      
    }
   
    private void displayBuddyList() {
        Roster roster = xMPPConnection.getRoster();
        Collection entries = roster.getEntries();


        System.out.println("\n\n------------Your Buddies!!------------");
        System.out.println(entries.size() + " buddy(ies):\n");
        Iterator iter = entries.iterator();
        buddySize = entries.size();  
        buddies = new String[buddySize];
        int i = 0;
        while (iter.hasNext()) {
            RosterEntry rosterEntry = (RosterEntry) iter.next();
            buddies[i] = rosterEntry.getUser();
            i++;
            System.out.println(i + ". " + rosterEntry.getUser());          
        }
        System.out.println("--------------------------------------");
    }
   
    private String getBuddy(int i) {
        String buddy = "";
        if(i > 0 && i <= buddySize) {
            buddy = buddies[i-1];
        } else {
            System.out.println("Invalid Buddy Id!! Selected default one!!");
            buddy = buddies[0];
        }
        return buddy;
    }
}





------Sample Output------





------------Your Buddies!!------------
3 buddy(ies):

1. dhanoopbhaskar@gmail.com
2. dhanoopbhaskar4@gmail.com
3. dhanoopbhaskar3@gmail.com
--------------------------------------


Enter the recipient's Email Id! or buddy id in the list
1
Buddy <dhanoopbhaskar@gmail.com> selected!
Enter your chat messages one by one!
[Enter "quit" to end the chat!]
hi
<dhanoopbhaskar@gmail.com> says hello
quit
--Chat Ended--





NB: To run and test the above program you need to download Smack XMPP API from here ... 



Tuesday, September 20, 2011

Python - First Step Towards Programming

Let's start with an example program to find Fibonacci series

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...     print(b) 
...     a, b = b, a+b 
...     
1




8


This example introduces several new features.

  • The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

  • The while loop executes as long as the condition (here: b < 10) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).

  • The body of the loop is indented: indentation is Python’s way of grouping statements. Python does not (yet!) provide an intelligent input line editing facility, so you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; most text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

  • The print() function writes the value of the expression(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple expressions, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:


  • >>> i = 256*256
    >>> print('The value of i is', i)
    The value of i is 65536

    The keyword end can be used to avoid the newline after the output, or end the output with a different string:

    >>> a, b = 0, 1
    >>> while b < 1000: 
    ...      print(b, end=',') 
    ...      a, b = b, a+b 
    ... 
    1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

    Python - Strings

    Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes:

    >>> 'spam eggs'
    'spam eggs'
    >>> 'doesn\'t'
    "doesn't"
    >>> "doesn't"
    "doesn't"
    >>> '"Yes," he said.'
    '"Yes," he said.'
    >>> "\"Yes,\" he said."
    '"Yes," he said.'
    >>> '"Isn\'t," she said.'
    '"Isn\'t," she said.'

    The interpreter prints the result of string operations in the same way as they are typed for input: inside quotes, and with quotes and other funny characters escaped by backslashes, to show the precise value. The string is enclosed in double quotes if the string contains a single quote and no double quotes, else it’s enclosed in single quotes. The print() function produces a more readable output for such input strings.

    String literals can span multiple lines in several ways. Continuation lines can be used, with a backslash as the last character on the line indicating that the next line is a logical continuation of the line:

    hello = "This is a rather long string containing\n\
    several lines of text just as you would do in C.\n\
    Note that whitespace at the beginning of the line is\
    significant."

    print(hello)

    Note that newlines still need to be embedded in the string using \n – the newline following the trailing backslash is discarded. This example would print the following:

    This is a rather long string containing
    several lines of text just as you would do in C.
    Note that whitespace at the beginning of the line is significant.

    Or, strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string. So the following uses one escape to avoid an unwanted initial blank line.

    print("""\
    Usage: thingy [OPTIONS]
        -h Display this usage message
        -H hostname Hostname to connect to
    """)

    produces the following output:

    Usage: thingy [OPTIONS]
        -h Display this usage message
        -H hostname Hostname to connect to

    If we make the string literal a “raw” string, \n sequences are not converted to newlines, but the backslash at the end of the line, and the newline character in the source, are both included in the string as data. Thus, the example:

    hello = r"This is a rather long string containing\n\
    several lines of text much as you would do in C."

    print(hello)

    would print:

    This is a rather long string containing\n\
    several lines of text much as you would do in C.

    Strings can be concatenated (glued together) with the + operator, and repeated with *:

    >>> word = 'Help' + 'A'
    >>> word
    'HelpA'
    >>> '<' + word*5 + '>'
    '<HelpAHelpAHelpAHelpAHelpA>'

    Two string literals next to each other are automatically concatenated; the first line above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions:

    >>> 'str' 'ing' # <- This is ok 'string'
    >>> 'str'.strip() + 'ing' # <- This is ok 'string'
    >>> 'str'.strip() 'ing' # <- This is invalid
      File "<stdin>", line 1, in ?
        'str'.strip() 'ing'
                         ^
    SyntaxError: invalid syntax

    Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. As in the Icon programming language, substrings can be specified with the slice notation: two indices separated by a colon.

    >>> word[4]
    'A'
    >>> word[0:2]
    'He'
    >>> word[2:4]
    'lp'

    Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

    >>> word[:2] # The first two characters
    'He'
    >>> word[2:] # Everything except the first two characters
    'lpA'

    Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error:

    >>> word[0] = 'x'
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: 'str' object does not support item assignment
    >>> word[:1] = 'Splat'
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    TypeError: 'str' object does not support slice assignment

    However, creating a new string with the combined content is easy and efficient:

    >>> 'x' + word[1:]
    'xelpA'
    >>> 'Splat' + word[4]
    'SplatA'

    Here’s a useful invariant of slice operations: 's[:i] + s[i:]' equals 's'.

    >>> word[:2] + word[2:]
    'HelpA'
    >>> word[:3] + word[3:]
    'HelpA'

    Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

    >>> word[1:100]
    'elpA'
    >>> word[10:]
    ''
    >>> word[2:1]
    ''

    Indices may be negative numbers, to start counting from the right. For example:

    >>> word[-1] # The last character
    'A'
    >>> word[-2] # The last-but-one character
    'p'
    >>> word[-2:] # The last two characters
    'pA'
    >>> word[:-2] # Everything except the last two characters
    'Hel'

    But note that -0 is really the same as 0, so it does not count from the right!

    >>> word[-0] # (since -0 equals 0)
    'H'

    Out-of-range negative slice indices are truncated, but don’t try this for single-element (non-slice) indices:

    >>> word[-100:]
    'HelpA'
    >>> word[-10] # error
    Traceback (most recent call last):
    File "<stdin>", line 1, in ?
    IndexError: string index out of range

    One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:


     +---+---+---+---+---+                                             
     | H | e | l | p | A |                                              
     +---+---+---+---+---+                                              
     0   1   2   3   4   5              
    -5  -4  -3  -2  -1                  

    The first row of numbers gives the position of the indices 0...5 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

    For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.

    The built-in function len() returns the length of a string:

    >>> s = 'supercalifragilisticexpialidocious'
    >>> len(s)
    34

    Java - RSA Algorithm

    /*RSAAlgorithm.java*/ 
    /*RSA stands for Rivest, Shamir and Adleman who first publicly described it*/

    import java.security.InvalidKeyException;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;

    /**
     *
     * @author dhanoopbhaskar
     */
    public class RSAAlgorithm {
       
        private KeyPairGenerator keyPairGenerator = null;
        private PrivateKey privateKey = null;
        private PublicKey publicKey = null;
        Cipher cipher = null;
       
        public RSAAlgorithm() {
            try {
                /**
                 * Create RSA key pairs
                 * - private key
                 * - public key
                 */
                keyPairGenerator = KeyPairGenerator.getInstance("RSA");
                keyPairGenerator.initialize(512); //512 is the key size
                KeyPair keyPair = keyPairGenerator.generateKeyPair();
                privateKey = keyPair.getPrivate();
                publicKey = keyPair.getPublic();
                /**
                 * Create an instance of cipher
                 */
                cipher = Cipher.getInstance("RSA");
            } catch (NoSuchPaddingException ex) {
                System.out.println(ex);
            } catch (NoSuchAlgorithmException ex) {
                System.out.println(ex);
            }
        }
       
        /**
         *
         * @param plainText
         * @return cipherText
         */
        public byte[] encryptText(String plainText) {
            byte[] cipherText = null;
            try {
                /**
                 * Initialize the cipher for encryption
                 */
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                /**
                 * Convert the text string to byte format
                 */
                byte[] plainBytes = plainText.getBytes();
                /**
                 * Perform encryption with method doFinal()
                 */
                cipherText = cipher.doFinal(plainBytes);           
            } catch (IllegalBlockSizeException ex) {
                System.out.println(ex);
            } catch (BadPaddingException ex) {
                System.out.println(ex);
            } catch (InvalidKeyException ex) {
                System.out.println(ex);
            }
           
            return cipherText;
        }
       
        /**
         *
         * @param cipherText
         * @return plainText
         */
        public String decryptText(byte[] cipherText) {
            String plainText = null;
            try {
                /**
                 * Initialize the cipher for decryption
                 */
                cipher.init(Cipher.DECRYPT_MODE, privateKey);           
                /**
                 * Perform decryption with method doFinal()
                 */
                byte[] plainBytes = cipher.doFinal(cipherText);
                /**
                 * Convert encrypted text to string format
                 */
                plainText = new String(plainBytes);
            } catch (IllegalBlockSizeException ex) {
                System.out.println(ex);
            } catch (BadPaddingException ex) {
                System.out.println(ex);
            } catch (InvalidKeyException ex) {
                System.out.println(ex);
            }
           
            return plainText;
        }
       
        public static void main(String[] args) {
            RSAAlgorithm rsaAlgorithm = new RSAAlgorithm();
            String textToEncrypt = "RSA Algorithm";
            System.out.println("Text before Encryption: " + textToEncrypt);
            byte[] cipherText = rsaAlgorithm.encryptText(textToEncrypt);
            System.out.println("Cipher Text [bytes]: " + cipherText);       
            String textDecrypted = rsaAlgorithm.decryptText(cipherText);
            System.out.println("Text after Decryption: " + textDecrypted);
        }
    }
     

    Java - Data Encryption Standard (DES) Algorithm

    /*DESAlgorithm.java*/ 

    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.KeyGenerator;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;

    /**
     *
     * @author dhanoopbhaskar
     */
    public class DESAlgorithm {
       
        KeyGenerator keyGenerator = null;
        SecretKey secretKey = null;
        Cipher cipher = null;
       
        public DESAlgorithm() {
            try {
                /**
                 * Create a DES key
                 */
                keyGenerator = KeyGenerator.getInstance("DES");
                secretKey = keyGenerator.generateKey();
               
                /**
                 * Create an instance of cipher providing the following info
                 *
    separated by slash.
                 *
                 *      - Algorithm name
                 *      - Mode (optional)
                 *      - Padding scheme (optional)
                 *
                 * NB:
                 *      DES = Data Encryption Standard.
                 *      ECB = Electronic Codebook mode.
                 *      PKCS5Padding = PKCS #5-style padding.
                 */
                cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            } catch (NoSuchPaddingException ex) {
                System.out.println(ex);
            } catch (NoSuchAlgorithmException ex) {
                System.out.println(ex);
            }
        }
       
        /**
         *
         * @param plainText
         * @return cipherText
         */
        public byte[] encryptText(String plainText) {
            byte[] cipherText = null;
            try {
                /**
                 * Initialize the cipher for encryption
                 */
                cipher.init(Cipher.ENCRYPT_MODE, secretKey);
                /**
                 * Convert the text string to byte format
                 */
                byte[] plainBytes = plainText.getBytes();
                /**
                 * Perform encryption with method doFinal()
                 */
                cipherText = cipher.doFinal(plainBytes);           
            } catch (IllegalBlockSizeException ex) {
                System.out.println(ex);
            } catch (BadPaddingException ex) {
                System.out.println(ex);
            } catch (InvalidKeyException ex) {
                System.out.println(ex);
            }
           
            return cipherText;
        }
       
        /**
         *
         * @param cipherText
         * @return plainText
         */
        public String decryptText(byte[] cipherText) {
            String plainText = null;
            try {
                /**
                 * Initialize the cipher for decryption
                 */
                cipher.init(Cipher.DECRYPT_MODE, secretKey);           
                /**
                 * Perform decryption with method doFinal()
                 */
                byte[] plainBytes = cipher.doFinal(cipherText);
                /**
                 * Convert encrypted text to string format
                 */
                plainText = new String(plainBytes);
            } catch (IllegalBlockSizeException ex) {
                System.out.println(ex);
            } catch (BadPaddingException ex) {
                System.out.println(ex);
            } catch (InvalidKeyException ex) {
                System.out.println(ex);
            }
           
            return plainText;
        }
       
        public static void main(String[] args) {
            DESAlgorithm desAlgorithm = new DESAlgorithm();
            String textToEncrypt = "DES Algorithm";
            System.out.println("Text before Encryption: " + textToEncrypt);
            byte[] cipherText = desAlgorithm.encryptText(textToEncrypt);
            System.out.println("Cipher Text[bytes]: " + cipherText);       
            String textDecrypted = desAlgorithm.decryptText(cipherText);
            System.out.println("Text after Decryption: " + textDecrypted);
        }
    }

    Monday, September 19, 2011

    Python - An Introduction

    In Python, input and output are distinguished by the presence or absence of prompts (>>> and ...). You must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. The comments in Python starts with an hash(#) character and ends when the physical line ends.
    # this is the first comment
    SPAM = 1                 # and this is the second comment
                             # ... and now a third!
    STRING = "# This is not a comment."

    Using Python as calculator


    Just like Ruby language (introduced previously) python can also be used as a calculator.
    The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses can be used for grouping. For example:
    >>> 2+2
    4
    >>> # This is a comment
    ... 2+2
    4
    >>> 2+2  # and a comment on the same line as code
    4
    >>> (50-5*6)/4
    5.0
    >>> 8/5 # Fractions aren't lost when dividing integers
    1.6

    To do integer division and get an integer result, discarding any fractional result, there is another operator,//:

    >>> # Integer division returns the floor:
    ... 7//3
    2
    >>> 7//-3
    -3

    The equal sign ('=') is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:

    >>> width = 20
    >>> height = 5*9
    >>> width * height
    900

    A value can be assigned to several variables simultaneously:

    >>> x = y = z = 0  # Zero x, y and z
    >>> x
    0
    >>> y
    0
    >>> z
    0

    Variables must be “defined” (assigned a value) before they can be used, or an error will occur:

    >>> # try to access an undefined variable
    ... n
    Traceback (most recent call last):
      File "", line 1, in
    NameError: name 'n' is not defined

    There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

    >>> 3 * 3.75 / 1.5
    7.5
    >>> 7.0 / 2
    3.5

    Complex numbers are also supported; imaginary numbers are written with a suffix of j or J.  Complex numbers with a nonzero real component are written as (real+imagj), or can be created with the complex(real, imag) function.

    >>> 1j * 1J
    (-1+0j)
    >>> 1j * complex(0, 1)
    (-1+0j)
    >>> 3+1j*3
    (3+3j)
    >>> (3+1j)*3
    (9+3j)
    >>> (1+2j)/(1+1j)
    (1.5+0.5j)

    Complex numbers are always represented as two floating point numbers, the real and imaginary part.  To extract these parts from a complex number z, use z.real and z.imag.

    >>> a=1.5+0.5j
    >>> a.real
    1.5
    >>> a.imag
    0.5

    The conversion functions to floating point and integer (float(), int()) don’t work for complex numbers — there is not one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part:

    >>> a=3.0+4.0j
    >>> float(a)
    Traceback (most recent call last):
      File "", line 1, in ?
    TypeError: can't convert complex to float; use abs(z)
    >>> a.real
    3.0
    >>> a.imag
    4.0
    >>> abs(a)  # sqrt(a.real**2 + a.imag**2)
    5.0

    In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

    >>> tax = 12.5 / 100
    >>> price = 100.50
    >>> price * tax
    12.5625
    >>> price + _
    113.0625
    >>> round(_, 2)
    113.06

    This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

    Using the Python Interpreter

    Invoking the Interpreter

    The Python interpreter is usually installed as /usr/local/bin/python3.2 on those machines where it is available; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command
    python3.2
    
    to the shell. Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)
    On Windows machines, the Python installation is usually placed in C:\Python32, though you can change this when you’re running the installer. To add this directory to your path, you can type the following command into the command prompt in a DOS box:
    set path=%path%;C:\python32
    
    Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command: quit().
    The interpreter’s line-editing features usually aren’t very sophisticated. On Unix, whoever installed the interpreter may have enabled support for the GNU readline library, which adds more elaborate interactive editing and history features. Perhaps the quickest check to see whether command line editing is supported is typing Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive Input Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.
    The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
    A second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) in command, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quote command in its entirety with single quotes.
    Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ..., which executes the source file for module as if you had spelled out its full name on the command line.
    When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script. (This does not work if the script is read from standard input, for the same reason as explained in the previous paragraph.)

    Argument Passing

    When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the argv variable in the sys module. You can access this list by executing import sys. The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.

    Interactive Mode

    When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (>>>); for continuation lines it prompts with the secondary prompt, by default three dots (...). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt:
    $ python3.2
    Python 3.2 (py3k, Sep 12 2007, 12:21:02)
    [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
    >>> the_world_is_flat = 1
    >>> if the_world_is_flat:
    ...     print("Be careful not to fall off!")
    ...
    Be careful not to fall off!
    



    The Interpreter and Its Environment

    Error Handling

    When an error occurs, the interpreter prints an error message and a stack trace. In interactive mode, it then returns to the primary prompt; when input came from a file, it exits with a nonzero exit status after printing the stack trace. (Exceptions handled by an except clause in a try statement are not errors in this context.) Some errors are unconditionally fatal and cause an exit with a nonzero exit; this applies to internal inconsistencies and some cases of running out of memory. All error messages are written to the standard error stream; normal output from executed commands is written to standard output.
    Typing the interrupt character (usually Control-C or DEL) to the primary or secondary prompt cancels the input and returns to the primary prompt.  Typing an interrupt while a command is executing raises the KeyboardInterrupt exception, which may be handled by a try statement.

    Executable Python Scripts

    On BSD’ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line
    #! /usr/bin/env python3.2
    
    (assuming that the interpreter is on the user’s PATH) at the beginning of the script and giving the file an executable mode. The #! must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ('\n'), not a Windows ('\r\n') line ending. Note that the hash, or pound, character, '#', is used to start a comment in Python.
    The script can be given an executable mode, or permission, using the chmod command:
    $ chmod +x myscript.py
    On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.

    Source Code Encoding

    By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of most languages in the world can be used simultaneously in string literals, identifiers and comments — although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
    It is also possible to specify a different encoding for source files. In order to do this, put one more special comment line right after the #! line to define the source file encoding:
    # -*- coding: encoding -*-
    
    With that declaration, everything in the source file will be treated as having the encoding encoding instead of UTF-8. The list of possible encodings can be found in the Python Library Reference, in the section on codecs.
    For example, if your editor of choice does not support UTF-8 encoded files and insists on using some other encoding, say Windows-1252, you can write:
    # -*- coding: cp-1252 -*-
    
    and still use all characters in the Windows-1252 character set in the source files. The special encoding comment must be in the first or second line within the file.

    The Interactive Startup File

    When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells.
    This file is only read in interactive sessions, not when Python reads commands from a script, and not when /dev/tty is given as the explicit source of commands (which otherwise behaves like an interactive session). It is executed in the same namespace where interactive commands are executed, so that objects that it defines or imports can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 in this file.
    If you want to read an additional start-up file from the current directory, you can program this in the global start-up file using code like if os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read()). If you want to use the startup file in a script, you must do this explicitly in the script:
    import os
    filename = os.environ.get('PYTHONSTARTUP')
    if filename and os.path.isfile(filename):
        exec(open(filename).read())
    

    The Customization Modules

    Python provides two hooks to let you customize it: sitecustomize and usercustomize. To see how it works, you need first to find the location of your user site-packages directory. Start Python and run this code:
    >>> import site
    >>> site.getusersitepackages()
    '/home/user/.local/lib/python3.2/site-packages'
    
    Now you can create a file named usercustomize.py in that directory and put anything you want in it. It will affect every invocation of Python, unless it is started with the -s option to disable the automatic import.
    sitecustomize works in the same way, but is typically created by an administrator of the computer in the global site-packages directory, and is imported before usercustomize


    Contact Form

    Name

    Email *

    Message *