On 04/26/2013 11:05 AM, Chris Angelico wrote:
On Sat, Apr 27, 2013 at 12:26 AM, <tunacu...@gmail.com> wrote:
##This next step will seek out the word Device within firstdev.ahk, and replace
with devlist[0]
for line in fileinput.input(["firstdev.ahk"], inplace=True):
line = line.replace("device", devlist[0])
sys.stdout.write(line)
##next step runs firstdev.ahk
os.system('firstdev.ahk')
##next step is replacing devlist[0] with "device"
for line in fileinput.input(["firstdev.ahk"], inplace=True):
line = line.replace(devlist[0], "device")
sys.stdout.write(line)
I've checked out what fileinput.input() is doing here (ought to have
done that earlier, sorry!) and I now understand this block of code
more. You're replacing that word _in the file, on disk_, and then
making the inverse replacement. This strikes me as dangerous; if
anything happens to your process in the middle, the file will be
damaged on disk. I would STRONGLY recommend rewriting this to use some
other file - for instance, a temporary file. I haven't looked into the
details, as I haven't actually done this lately in Python, but you
should be able to use tempfile.NamedTemporaryFile(delete=False) [1],
write to it, make it executable, run it, and unlink it. That way,
you're creating a temporary file to run, not running the original.
This is semantically different from your code, but I think it'd be a
lot safer.
[1] http://docs.python.org/3.3/library/tempfile.html#tempfile.NamedTemporaryFile
ChrisA
fileinput.Fileinput class already creates the temp file when you specify
inplace=True
If it didn't, I'd also have to point out the hazards of doing in-place
updates in a text file where the new data and old is a different length.
There still may be reasons to make an explicit backup, but I don't know
what they are.
--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list