Editing text with an external editor in Python

Chris Angelico rosuav at gmail.com
Mon Sep 1 12:35:16 EDT 2014


On Tue, Sep 2, 2014 at 2:11 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Anyone able to test it on Windows for me please?
>

Seems to partially work. I added an 'import os' at the top, and a
simple test call to the function, and it did give me my editor (nano)
and retrieved the text. It did give a warning, though:

----
C:\>Python34\python 123123123.py
cygwin warning:
  MS-DOS style path detected: C:\DOCUME~1\M\LOCALS~1\Temp\tmp94rcwd57
  Preferred POSIX equivalent is: /DOCUME~1/M/LOCALS~1/Temp/tmp94rcwd57
  CYGWIN environment variable option "nodosfilewarning" turns off this warning.
  Consult the user's guide for more details about POSIX paths:
    http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
Your text is:
asdf
Hello, world!
----

Windows doesn't have a nice $EDITOR environment variable to call on,
so I'm not sure what the best way to actually choose an editor is. I
would hope that you can make it externally configurable (I've done
some very weird things with changed editors, like one that connects to
a TCP socket, alerts a server with its arguments, and then SIGSTOPs
itself, and the server sends the file's contents to another
socket-connected client that has a human at the other end, and when it
gets back a response from that client, it rewrites the file and
SIGCONTs the 'editor', which then terminates - so to all intents and
purposes, it's as if that program really did edit the file), but doing
that on Windows may not be easy.

You'll also have to cope with some other possibilities. What happens
if someone tries Notepad? (Don't try this at home. We are experts and
are testing on a closed track. Do not use Notepad unless you, too,
have thirty years of special effects experience.) Turns out it doesn't
like working with a file that another process has open. Nor can SciTE;
it shows an empty file on load, and then is unable to save. I suspect
the comment here is what's biting you:

https://docs.python.org/3.5/library/tempfile.html#tempfile.NamedTemporaryFile
"""Whether the name can be used to open the file a second time, while
the named temporary file is still open, varies across platforms (it
can be so used on Unix; it cannot on Windows NT or later)."""

So it works fairly nicely as long as you're using a Cygwin editor.
Otherwise, not so much. :(

ChrisA



More information about the Python-list mailing list