[Tutor] another couple of questions

Martijn Faassen M.Faassen@vet.uu.nl
Thu, 03 Jun 1999 19:37:23 +0200


Todd Martin wrote:
> 
> Ok so I can now create a file and name it what I want to name it, I can
> write to it and all seems ok.

Great!

> Now I have this shell script that I use for dealing with IP address's and
> what it does essentially is takes an IP, breaks it down to its 4 octets like
> 255.255.255.255 and stores each octet into its own variable, like $OCT1, $OCT2,
> $OCT3, and $OCT4. By doing that I can add and subtract from $OCT4 and glue it
> all bake together again.
> 
> So if I have 111.111.111.111 and I want to give a list of usuable IP's for a
> customer I can just add to $OCT4 and produce 111.111.111.112 etc......
> 
> How can I do this in python?

I'm not sure I get entirely what you want, but perhaps something like
this helps you get started:

# warning, untested code!
import string

# basic & dumb exception thing
class Error(Exception): 
   pass

ip_address = "111.111.111.111" # or read this as an argument or from a
file
# split the string at the .
octets = string.split(ip_address, ".")
# we get a list, if it contains more or less than 4 elements, we bail
out
if len(octets) != 4:
    raise Error, "There should be 4 octets, not more, not less!"
# convert the octets to numbers (should actually do more error checking)
# yeah, I know you can write this more compactly with map and such
numerical_octets = []
for octet in octets:
    numerical_octets.append(int(octet))
numerical_octets[3] = numerical_octets[3] + 1 # add one to the 4th octet
# now turn octets back into strings
new_octets = []
for octet in numerical_octets:
    new_octets.append(int(octet))
# now make a nice ip address
final_address = string.join(new_octets, ".")
 
> -----------------------------
> Second question
> -----------------------------
> 
> I can print to a file, but how do I read a template into a file? For instance
> I want to have a file called "foc" that I can read into a file. I would also
> like to be able to change certain fields in the template, for instance
> 
> Name:           username
> Address:        address
> 
> I would like the program to prompt the user for the variable address (username
> is given as an argument via argv[1]) then fill in the appropriet field in the
> template.

I'm not quite sure what you want here either, but perhaps this'll help:

import string

username = "luser"
# construct string 
foo = "%s%s\n" % (string.ljust("Name:", 10), username)
# then write this line to the file
f = open("foofile.txt", "w")
f.write(foo)
f.close()

Of course you can come up with a set of functions or classes than
handles the same thing in a more sophisticated way, too.

Regards and good luck!

Martijn