Redirect text from editor directly to python script
Question: is there a way to open text editor like vim or gedit from python script and
then redirect typed text from text editor back directly to python script so I
could save it in database? Something like git commit command which opens
external text editor and on exit saves commit message but not into file.


Answer: I think you would end up depending too much on $EDITOR specific behaviour
without a tempfile. The tempfile module deals with the choice of a tempdir and
tempfilename so you will not have to. Try the following.

manedit.py:

    
    
        import os
        import tempfile
        import subprocess
    
        data = '6 30 210 2310 30030'
    
        mefile = tempfile.NamedTemporaryFile( delete=False )
        # delete=False otherwise delete on close() 
        mefile.write( data )
        mefile.close()
    
        subprocess.call( [ os.environ.get('EDITOR','') or 'vim', mefile.name ] )
        # unset EDITOR or EDITOR='' -> default = vim
        # block here
    
        mefile = open( mefile.name, 'r' )
        newdata = mefile.read()
        mefile.close()
        os.remove( mefile.name )
    
        print( newdata )
    
    

And then try the following commands to verify each scenario. Replace ed with
an editor that differs from your $EDITOR

    
    
        python manedit.py
    
        env EDITOR= python manedit.py
    
        env EDITOR=ed python manedit.py
    
        env -u EDITOR python manedit.py
    

The pitfall: The script blocks only while EDITOR is running. An editor may
just open a new window on an existing editor session and return, suggesting
that the manual edit session completed. However I know no such editor.

edit: If you are interested specifically in vim or you want to see how
specific such thing can get, see the following:  
<http://vimdoc.sourceforge.net/htmldoc/remote.html>  
<http://petro.tanrei.ca/2010/8/working-with-vim-and-ipython.html>  
<http://www.freehackers.org/VimIntegration>

