Python Introduction #3
Results 1 to 4 of 4

Thread: Python Introduction #3

  1. #1
    Senior Member
    Join Date
    Jan 2003
    Posts
    3,914

    Python Introduction #3

    Python Introduction #3

    Because I have nothing to do until my friends get off work, it's time to start working on another one of these.

    As promised this file will include execution of system files, the reading and writing of files and the use of error control.

    Before I jump into those there is another chart I would like to add. In my last tutorial I mentioned a new way to use the print command, to make it a little more C/C++ like. However I didn't realize that some users may not have C/C++ experience and not know about the %<letter> options. So here is a chart with all of your options.

    Source: Python 101 - Beginning Python

    d Signed integer decimal.
    i Signed integer decimal.
    o Unsigned octal.
    u Unsigned decimal.
    x Unsigned hexidecimal (lowercase).
    X Unsigned hexidecimal (uppercase).
    e Floating point exponential format (lowercase).
    E Floating point exponential format (uppercase).
    f Floating point decimal format.
    F Floating point decimal format.
    g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
    G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
    c Single character (accepts integer or single character string).
    r String (converts any python object using repr()).
    s String (converts any python object using str()).
    % No argument is converted, results in a "%" character in the result.

    Now on to our new lesson.

    I would like to look at executing files located on your system. As I mentioned in the first tutorial I would like to keep this OS inspecific so we will deal with the ping command as it is universal. I will be using the count flag and I will use the windows flag which is -n, so *nix users must remember to change it to -c or they will get an error.

    ********************
    Step-by-Step Process
    ********************
    1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
    2. Type
    Code:
    from os import *
    count = input("Number of times to ping host: ")
    host = raw_input("IP of host to ping: ")
    pingcmd = "ping -n %i %s" % (count, host)
    execute = popen(pingcmd)
    results = execute.readlines()
    execute.close()
    length = len(results)
    for x in range (length) :
            print results[x]
    3. Save the script as pingtest.py
    4. Open a command prompt and type python pingtest.py
    5. This one is a little more difficult to walk you threw. First you will see Number of times to ping host: . Enter a number and press enter. Then you will see IP of host to ping: . Enter an IP and again press enter. There will be a pause (the length of which will depend on how many times you told it to ping). Then you will see the standard output of a ping command written to the screen.

    Now to walk you threw this script. We import the OS module and then query the user for the number of pings and the host to ping. Then we define our ping command using the same format as the print command. The next line actually executes the command followed by a line which reads the output of the command into a variable. We then close the variable which executed the command. The next line introduces another new command the len command, which returns the length. In this case since results in an array it returns the number of lines in the array. We then make use of the for command we learned in our last tutorial and have it print the actual content of the array, line by line. Notice the use of the whitespace again for the for command.

    Alrighty.... moving on, I believe I promised you file reading/writing next. We'll work with a simple txt file.

    ********************
    Step-by-Step Process
    ********************
    1. Open your favourite editor (Vi, Pico, Notepad, Wordpad, Textpad, DOS Edit).
    2. Type
    Code:
    print "File Write/Create Example."
    filename = raw_input("File to Write To/Create: ")
    openfile = file(filename, 'w')
    print "Enter text to write to file (Type 'quit' to quit):"
    line = ""
    alllines = ""
    while 1 :
            line = raw_input()
            if line == 'quit' :
                    break
            alllines = alllines + line + "\n"
    file.write(openfile, alllines)
    file.close(openfile)
    print "You just wrote to a file, Now Let's see what you wrote."
    print "File Read Example."
    openfile = file(filename, 'r')
    filedata =  openfile.readlines()
    length = len(filedata)
    for x in range(length) :
            print filedata[x]
    openfile.close
    3. Save the script as filetest.py
    4. Open a command prompt and type python filetest.py
    5. When you run this program you will be prompted to enter a filename. Call the file anything you want. The next line of code then open's that file in write ('w') mode (will create it if it doesn't exist). The code then tells you to type your text, and declares to blank variables. The while 1 : is just a way of creating an infinite loop, so that every time the user hits enter, it moves to a new line of the file. The line is used to receive input, but we aren't prompting the user each time. The if statement introduces another new command, break. This will exit the loop upon seeing the string 'quit'. The next line of code simply concatenates the previous lines with the new line and then adds a newline character. After the user has entered quit we write to the file and close the file. You then see a few lines of text. The script them opens the file in read ('r') mode. We read the lines into an array and determine the number of lines like we did in our ping tutorial. We then enter a fore statement and print each line until we get to the end of the file. Then we close the file.

    The last thing I promised for this tutorial was error handling. This is useful for small things like if you've forgotten to declare a variable and other such events. I can't think of a useful example at the moment, so I'll just go over the commands and if I think of some code later I'll add it.


    Basically the commands are try and except.

    Instead of just issuing the code, you try it. For example if you were attempting to read a file that didn't exist. The program would exit and return an error. However if you try and have an except...

    Code:
    try :
    	<code to open file>
    except : 
    	print "File doesn't exist."
    Now if the file doesn't exist it will simple print File doesn't exist and continue on with the program.


    Anyways that's all for now... I think I'll take a break ( a few hours or something) before I start on the next one....

    Peace

    HT

  2. #2
    Senior Member
    Join Date
    Jan 2002
    Posts
    1,207
    Your ping example is OS specific and relies on the behaviour of "ping", which is not the same in all systems

    Code:
    ping -n 3 localhost
    Is not the correct syntax for the ping command on my OS (Linux)

  3. #3
    Senior Member
    Join Date
    Jan 2003
    Posts
    3,914
    Originally posted here by slarty
    Your ping example is OS specific and relies on the behaviour of "ping", which is not the same in all systems

    Code:
    ping -n 3 localhost
    Is not the correct syntax for the ping command on my OS (Linux)
    Nope it's not the syntax for Linux, but if you read what i said before the code, you'd see what to change

    I would like to look at executing files located on your system. As I mentioned in the first tutorial I would like to keep this OS inspecific so we will deal with the ping command as it is universal. I will be using the count flag and I will use the windows flag which is -n, so *nix users must remember to change it to -c or they will get an error.

  4. #4
    Senior Member
    Join Date
    Nov 2002
    Posts
    186
    That comment on using the ping command reminded me of something.
    A lot of people would write that chunk of code and create a socket on the system to do the ping (since it makes it OS independent)(Obviosuly doing it here was well outside the scope of an introductory tutorial).
    I was working a co-op term and we wrote a perl script to ping all our hosts, so we could check if they came back up after power outages. It was written under Win 95 and used raw sockets. When we upgraded to NT, even though we did app support, we only had regular user rights on the local machines. That meant no permission to create raw sockets. We had to rewrite the script with an embedded DOS ping command in it and then 'grep' the output for the word 'Reply'.
    Even though this was just a Python example, there are situations where things have to be written this way (OS specific)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •