TypeError: Can't convert 'int' object to str implicitly

Chris Angelico rosuav at gmail.com
Fri Apr 26 11:05:29 EDT 2013


On Sat, Apr 27, 2013 at 12:26 AM,  <tunacubes at 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



More information about the Python-list mailing list