perl to python
Duncan Booth
me at privacy.net
Tue May 11 08:03:02 EDT 2004
Kirk Job-Sluder <kirk at eyegor.jobsluder.net> wrote in
news:slrnca0ub4.1bdc.kirk at eyegor.jobsluder.net:
> The above code runs, but is not very good because I'm not that
> familiar with exec statements. Anyway I've tried to capture what
> "perl -pi -e" actually does which is to execute an arbitrary command
> over every line of an arbitrary list of files, editing them in place,
> with a temporary backup copy.
Your code might have been a bit shorter if you had used the existing
facility in Python for editing files in place. The code below is completely
untested, so I can all but guarantee it doesn't work, but you get the idea:
#!/usr/local/bin/python
import getopt,sys,os,re
import fileinput
#get your command line options
#files will be in
optlist, args = getopt.getopt(sys.argv[1:],'e:')
for line in fileinput.input(args, inplace=1):
#execute all of the -e statements.
for command in optlist:
#warning bad mojo here
foo=(command[1] % line.rstrip("\n"))
exec(("line=%s" % foo))
#save to the new file
print line
fileinput.close()
More information about the Python-list
mailing list