Kann mir hier vllt. jemand zeigen wie ich meinen Code performanter gestallte. Ich meine eine Datei 10 mal zu öffnen und zu schreiben ist bestimmt nicht so schlau wie einmal zu öffnen und einmal zu beschreiben!
Würde mich über einen fertigen Code-Snippet sehr freuen!
CODE:
Code: Alles auswählen
import shutil
from tempfile import mktemp
import argparse
import os
parser = argparse.ArgumentParser(description='Build Cloud iso Image.') #Argumente umwandeln
parser.add_argument('--source', '-sr',
action='store',
help='Sourcepath -sr or --source')
parser.add_argument('--destination', '-dn',
action='store',
help='Targetpath -dn or --destination')
parser.add_argument('--password', '-pw',
action='store',
help='Root image password -pw or --password')
parser.add_argument('--networkmode', '-n',
action='store',
help='Networkmode -nm or --networkmode')
parser.add_argument('--ipadress', '-ip',
action='store',
help='Ipadress -ip or --ipadress')
parser.add_argument('--gateway', '-gw',
action='store',
help='Gateway -gw or --gateway')
parser.add_argument('--nameserver', '-ns',
action='store',
help='Nameserver -ns or --nameserver')
parser.add_argument('--netmask', '-nm',
action='store',
help='Netmask -nm or --netmask')
parser.add_argument('--hostname', '-hn',
action='store',
help='Hostname -hn or --hostname')
args = parser.parse_args()
final_path = mktemp(prefix='tmpiso_', dir=args.destination)
shutil.copytree(args.source, final_path)
cfgedit = os.path.join(final_path, 'autounattend.cfg')
p = open(cfgedit).read()
p = p.replace("%PASSWORD", args.password)
pw = open(cfgedit, 'w')
pw.write(p)
pw.close()
nw = open(cfgedit).read()
nw = nw.replace("%NWMODE", args.networkmode)
nwm = open(cfgedit, 'w')
nwm.write(nw)
nwm.close()
ip = open(cfgedit).read()
ip = ip.replace("%IP_ADDRESS", args.ipadress)
ipa = open(cfgedit, 'w')
ipa.write(ip)
ipa.close()
gw = open(cfgedit).read()
gw = gw.replace("%GATEWAY", args.gateway)
gwa = open(cfgedit, 'w')
gwa.write(gw)
gwa.close()
ns = open(cfgedit).read()
ns = ns.replace("%NAME_SERVER_IP", args.nameserver)
nsi = open(cfgedit, 'w')
nsi.write(ns)
nsi.close()
nm = open(cfgedit).read()
nm = nm.replace("%NETMASK", args.netmask)
nma = open(cfgedit, 'w')
nma.write(nm)
nma.close()
hn = open(cfgedit).read()
hn = hn.replace("%HOSTNAME", args.hostname)
hns = open(cfgedit, 'w')
hns.write(hn)
hns.close()
exit()
Danke im Voraus!