Hi, everybody!
I'm teaching myself Python, and I have no experience in programming
apart from some years of shell scripting. So, please bear with me.
These two funktions are part of an administrative script I've set
myself as a first lesson, and, as you will see, they're practically the same,
except for one variable. So I'd like to weld them together -- but I
can't find out how to.
def writeIP(ip):
""" IP schreiben """
regex = re.compile('(.*)address(.*)')
confFile = open(networkConf, 'r')
conf = confFile.readlines()
confFile.close
for line in conf:
if regex.search(line):
addressLine = line
addressLineNum = conf.index(addressLine)
address = string.split(addressLine, ' ')
address[1] = ip + "\n"
conf[addressLineNum] = string.join(address)
confFile = open(networkConf, 'w')
confFile.writelines(conf)
confFile.close
def writeMask(mask):
""" netmask schreiben """
regex = re.compile('(.*)netmask(.*)')
confFile = open(networkConf, 'r')
conf = confFile.readlines()
confFile.close
for line in conf:
if regex.search(line):
netmaskLine = line
netmaskLineNum = conf.index(netmaskLine)
netmask = string.split(netmaskLine, ' ')
netmask[1] = mask + "\n"
conf[netmaskLineNum] = string.join(netmask)
confFile = open(networkConf, 'w')
confFile.writelines(conf)
confFile.close
I feel it should be possible to use something like
def writeFile(ip,keyword):
...
but how would I construct expressions like
netmaskLineNum = conf.index(netmaskLine)
in that case (netmask being the keyword here)?
I fear this is a really silly question and I guess I've missing a very
basic concept here. But I can't figure it out alone. Any advice much
appreciated!
Mit schönem Gruß
- Thomas
--
On the day that she left
He died but it did not show
- Neil Young, The Loner
/* PGP key auf Wunsch per e-mail || PGP key sent on request */ 7 1653
On Sun, 24 Apr 2005 23:40:22 +0200,
Thomas Köllmann <ko*******@gmx.net> wrote: Hi, everybody! I'm teaching myself Python, and I have no experience in programming apart from some years of shell scripting. So, please bear with me.
These two funktions are part of an administrative script I've set myself as a first lesson, and, as you will see, they're practically the same, except for one variable. So I'd like to weld them together -- but I can't find out how to.
[ two very similar functions snipped ]
I feel it should be possible to use something like
def writeFile(ip,keyword): ...
Absolutely.
but how would I construct expressions like
netmaskLineNum = conf.index(netmaskLine)
in that case (netmask being the keyword here)?
netmaskLineNum and addressLineNum are just names. They may mean
something to you and to people who read your program, but they mean
nothing to Python. So just use generic names:
for line in conf:
if regex.search( line )
theLine = line
theLineNum = conf.index( theLine )
etc.
HTH,
Dan
--
Dan Sommers
<http://www.tombstonezero.net/dan/>
μ₀ × ε₀ × c² = 1
Thomas Köllmann <ko*******@gmx.net> writes: confFile.close
You want ``confFile.close()`` -- the above won't do anything [1].
'as
Footnotes:
[1] Best practice would be something like this (don't worry to much about it
-- it just ensures the file is properly closed, even if something goes
wrong):
confFile = None
try:
confFile = open(networkConf, 'w')
confFile.writelines(conf)
finally:
if confFile: confFile.close()
Thomas Köllmann wrote: Hi, everybody!
I'm teaching myself Python, and I have no experience in programming apart from some years of shell scripting. So, please bear with me.
These two funktions are part of an administrative script I've set myself as a first lesson, and, as you will see, they're practically the same, except for one variable. So I'd like to weld them together -- but I can't find out how to.
def writeIP(ip): """ IP schreiben """ regex = re.compile('(.*)address(.*)')
This is the only difference between the functions, isn't it?
So, instead of hardwiring 'address' or 'netmask' into the regexp template, you
should insert it based on an argument passed to the function. String
interpolation works well here: e.g., '(.*)%s(.*)' % 'netmask'
'(.*)netmask(.*)'
confFile = open(networkConf, 'r') conf = confFile.readlines() confFile.close
Note, here you presumably mean confFile.close() i.e., you must supply the parens
to call the function.
[snip] I feel it should be possible to use something like
def writeFile(ip,keyword): ...
Indeed. Use keyword as the argument to the string interpolation regex = re.compile('(.*)%s(.*)' % keyword)
but how would I construct expressions like
netmaskLineNum = conf.index(netmaskLine)
I think these should work unchanged. But it would be easier to read if you
changed these names to be neutral to the application e.g., instead of
netmaskLine, foundLine
HTH
Michael
Alexander Schmolck wrote: [1] Best practice would be something like this (don't worry to much about it -- it just ensures the file is properly closed, even if something goes wrong):
confFile = None try: confFile = open(networkConf, 'w') confFile.writelines(conf) finally: if confFile: confFile.close()
A clearer equivalent is:
confFile = open(networkConf, 'w')
try:
confFile.writelines(conf)
finally:
confFile.close()
You did not say whether you are looking to replace all, the first,
or the last occurrence of your search target. Assuming you really
mean all lines and the first occurrence on those lines:
def replaces(source, search, replacement):
'''Replace first of search on lines with replacement'''
pat = re.compile(search)
for line in source:
yield re.sub(pat, replacement, line, 1)
And your application might go like:
input = open(networkConf, 'r')
part1 = replaces(input, 'address', 'ip')
part2 = replaces(part1, 'netmask', 'mask')
result = list(part2)
input.close()
output = open(networkConf, 'w')
try:
output.writelines(result)
finally:
output.close()
--Scott David Daniels Sc***********@Acm.Org
Thomas Köllmann wrote: Hi, everybody!
I'm teaching myself Python, and I have no experience in programming apart from some years of shell scripting. So, please bear with me.
These two funktions are part of an administrative script I've set myself as a first lesson, and, as you will see, they're practically the same, except for one variable. So I'd like to weld them together -- but I can't find out how to.
Pass the variable as an argument probably.
But because generally you wouldn't want to recompile the regexp (this
should be done once), you could say:
# untested
def makewriter (regexp_string):
def writeFunc(ip, regex=re.compile(regexp_string)):
confFile = open(networkConf, 'r')
conf = confFile.readlines()
confFile.close
for line in conf:
if regex.search(line):
addressLine = line
addressLineNum = conf.index(addressLine)
address = string.split(addressLine, ' ')
address[1] = ip + "\n"
conf[addressLineNum] = string.join(address)
confFile = open(networkConf, 'w')
confFile.writelines(conf)
confFile.close
return writeFunc
writeIP=makewriter('(.*)address(.*)')
writeMask=makewriter('(.*)netmask(.*)')
This is rather advanced python programming though, but it shows
cool dynamic function creation features and it's never early to
get into it;)
jfj
Michael Spencer <ma**@telcopartners.com> writes: Thomas Köllmann wrote: regex = re.compile('(.*)address(.*)')
This is the only difference between the functions, isn't it? So, instead of hardwiring 'address' or 'netmask' into the regexp template, you should insert it based on an argument passed to the function. String interpolation works well here: e.g., >>> '(.*)%s(.*)' % 'netmask' '(.*)netmask(.*)' >>>
Thanks, I somehow missed this (presumably very basic) feature.
confFile = open(networkConf, 'r') conf = confFile.readlines() confFile.close
Note, here you presumably mean confFile.close() i.e., you must supply the parens to call the function.
Yes, thanks -- to Alexander as well, who also pointed me to that!
Mit schönem Gruß
- Thomas
--
/* PGP key auf Wunsch per e-mail || PGP key sent on request */
Dan Sommers <me@privacy.net> writes: On Sun, 24 Apr 2005 23:40:22 +0200, Thomas Köllmann <ko*******@gmx.net> wrote:
netmaskLineNum and addressLineNum are just names. They may mean something to you and to people who read your program, but they mean nothing to Python. So just use generic names:
Thanks. I still get easily confused when trying to "abstract" such
things, but I guess I'll get it some fine day. I appreciate you took
the time to point that out to me -- you must have found it _extremely_
obvious. :-)
Mit schönem Gruß
- Thomas
--
I filled and lit my pipe and sat there smoking. Nobody came in, nobody
called, nothing happened, nobody cared whether I died or went to El Paso.
- Raymond Chandler, The High Window
/* PGP key auf Wunsch per e-mail || PGP key sent on request */ This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Eric A. Forgy |
last post by:
Hello,
I am just learning Java and am trying to write a method that does
something like
//===========================================
public Static List find(double array,double val,String...
|
by: Brian Angliss |
last post by:
I'm relatively new to scripting in JavaScript, so I'm not too
surprised I'm having difficulty scripting up an animation effect for
my personal site.
What I'm trying to do is the following: When...
|
by: in |
last post by:
You know, why does Microsoft even bother to spend money to thwart Linux
when it's top supporters act like such buffoons anyway...?!
http://www.eweek.com/article2/0,1759,1772633,00.asp#talkback
...
|
by: Susan Baker |
last post by:
Hi,
I want to store data in a 3-tuple {a,b,c}.
Element a is an enumeration, and element c is an enumeration which is
specific (i.e. determined) by a.
An example will help clarify further. I...
|
by: James A. Donald |
last post by:
I am contemplating getting into Python, which is used by engineers I
admire - google and Bram Cohen, but was horrified to read
"no variable or argument declarations are necessary."
Surely that...
|
by: MLH |
last post by:
If this is what MySQL is set to...
SELECT DISTINCTROW qryVehiclesNowners5.SerialNum,
qryVehiclesNowners5.VDescr, qryVehiclesNowners5.Owner,
qryVehiclesNowners5.VehicleJobID ,...
|
by: maniac |
last post by:
Hey guys, I'm new here, just a simple question.
I'm learning to Program in C, and I was recommended a book called,
"Mastering C Pointers", just asking if any of you have read it,
and if it's...
|
by: Matt Kruse |
last post by:
Consider the following two functions:
function func1() {
var o ;
if ( (o=document.forms)
&& (o=o)
&& (o=o.elements)
&& (o=o.sel)
&& (o=o.options)
&& (o=o)
|
by: js |
last post by:
HI guys,
How do you write Perl's
print a ... z, A ... Z, "\n"' in Python
In Python?
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
| |