Tuesday, June 23, 2015

Re: vim replace a string when a change occurred in another place

On 23.06.15 08:00, Rudra Banerjee wrote:
> function! Edname()
> python<<EOF
> import vim
> import fileinput
> with open("i.f90") as inp:
> for line in inp:
> if line.startswith("Program"):
> var = line.rsplit(' ', 1)[-1].strip()
> if line.startswith("End Program"):
> v2 = line.strip()
> print v2
> inp.close()
> STR="End Program "+var
> print STR
> for line in fileinput.input("i.f90", inplace=True):
> print line.replace(v2, STR).strip()
> EOF
> endfunction
>
> Now it is not working. It is printing the v2 and STR properly, but the
> file is NOT getting updated. Any clue?

Caveat: Yours is the first python program I've ever seen.
IIRC, it is the weird language which uses indentation
in place of brackets.

Tentative thoughts:
You have two file-reading loops, one of which appears to detect the
initial "foo", then print it. The second seems intended to make a single
replacement. If "inplace=True" ought to empower python to implicitly modify
the input file, then hopefully it is also implicitly printing the lines
you do not modify, or they must surely be lost? (Based solely on your
expectation that the input file should be modified, despite no explicit
mechanism to do that.)

Possible causes of failure:
Does the "i." indicate that file "f90" is opened for input? If so, then
how can you write to it? (Does python hide writing to a temp file, with
subsequent overwriting of the input file?) Is some form of
output.close() needed instead when closing for write? If python still
permits printing to stdout while "inplace=True", then you would need to
print to "f90", I expect, to modify the file instead. Are you relying
on the "endfunction" to implicitly invoke an ???.close() and that the
file will then be written?

I'm afraid that there's too much that is implicit in python for more
detailed guessing than that.

Erik

--
--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment