Thomas Troeger
1/10/2008 2:02:00 PM
Ok I've written a small example program to clarify matters:
================ [SNIP] ================
#!/usr/bin/python
import os, sys, time
def template(src, dst, sep):
"""
Copy file from src to dst, executing embedded python code.
"""
try:
# read template file.
f=open(src, "rU")
data="".join(f.readlines())
f.close()
# find embedded python code and execute it.
while True:
# find embedded embedded python command.
offset=data.find(sep)
if offset < 0:
break
offset2=data.find(sep, offset+1)
if offset2 < 0:
break
cmd=data[offset+len(sep):offset2]
# execute command.
try:
ret=""
exec(compile(cmd,
'<from string>', 'exec'))
except:
print "error compiling code `%s'." % cmd
# substitute command with return value.
data=data[:offset]+str(ret)+ data[offset2+len(sep):]
# write translated input.
f=open(dst, "w")
f.write(data)
f.close()
except:
print "error processing template file `%s'." % src
# ------------------------------ main -------------------------------
if len(sys.argv) > 2:
template(sys.argv[1], sys.argv[2], '$$')
================ [SNIP] ================
This is the example input that works:
================ [SNIP] ================
process id: $$ret=os.getpid()$$
current date: $$ret=time.ctime()$$
superuser: $$
if os.geteuid():
ret="No"
else:
ret="Yes"$$
================ [SNIP] ================
Now the `ret= ...' mechanism is not nice, I'd prefer to have a return
statement instead.