Idiom for shelling out to $EDITOR/$PAGER?

Peter Otten __peter__ at web.de
Fri Dec 23 03:28:52 EST 2011


Tim Chase wrote:

> After a little searching, I've not been able to come up with what
> I'd consider canonical examples of consider calling an external
> editor/pager on a file and reading the results back in.  (most of
> my results are swamped by people asking about editors written in
> Python, or what the best editors for Python code are)
> 
> The pseudocode would be something like
> 
>    def edit_text(data):
>      temp_fname = generate_temp_name()
>      try:
>        f = file(temp_fname, 'w')
>        f.write(data)
>        f.close()
>        before = info(temp_fname) # maybe stat+checksum?
>        editor = find_sensible_editor()
>        subprocess.call([editor, temp_fname])
>        if before == info(temp_fname):
>          return None
>        else:
>          return file(temp_fname).read()
>      finally:
>        delete_if_exists(temp_fname)
> 
> However there are things to watch out for in this lousy code:
> 
> -race conditions, unique naming, and permissions on the temp file
> 
> -proper & efficient detection of file-change, to know whether the
> user actually did anything

Just read the whole thing back into memory and compare the string to the 
original data. The file has to be quite long for the checksum calculation to 
be worthwhile.

> -cross-platform determination of a sensible editor (that blocks
> rather than spawns), using platform conventions like
> os.environ['EDITOR']
> 
> -cleanup deletion of the temp-file
> 
> I presume the code for spawning $PAGER on some content would look
> pretty similar.
> 
> Any good example code (or blog posts, or other links) that has
> been battle-tested?

You could look into mercurial to see what it does to let you edit its commit 
messages. A quick look into mercurial/ui.py 
(http://selenic.com/hg/file/9cf1620e1e75/mercurial/ui.py, start with the 
ui.edit() method) suggests that it uses the same approach as your 
pseudocode.





More information about the Python-list mailing list