Start nano as a subprocess from python, capture input

前端 未结 2 1236
死守一世寂寞
死守一世寂寞 2021-01-21 05:14

I\'m trying to start a text editor (nano) from inside Python, have the user enter text, and then capture the text once they writeout (Control-O). I haven\'t worked with the

相关标签:
2条回答
  • 2021-01-21 05:39

    I'm not sure you can capture what the user has entered into nano. After all, that's nano's job.

    What you can (and I think should do) to get user input from an editor is to spawn it off with a temporary file. Then when the user has entered what he wants, he saves and quits. Your program reads the content from the file and then deletes it.

    Just spawn the editor using os.system. Your terminal is behaving funny because nano is a full screen program and will use terminal escape sequences (probably via. curses) the manipulate the screen and cursor. If you spawn it unattached to a terminal, it will misbehave.

    Also, you should consider opening $EDITOR if it's defined rather than nano. That's what people would expect.

    0 讨论(0)
  • 2021-01-21 05:43

    Control-O in Nano writes to the file being edited, i.e., not to standard output -- so, forego the attempt to capture stdout and just read the file once the user writes it out and exits Nano. E.g., on my Mac:

    >>> import tempfile
    >>> f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
    >>> n = f.name
    >>> f.close()
    >>> import subprocess
    >>> subprocess.call(['nano', n])
    

    Here, I write "Hello world!" then hit control-O Return control-X , and:

    0
    >>> with open(n) as f: print f.read()
    ... 
    Hello world!
    
    
    >>> 
    
    0 讨论(0)
提交回复
热议问题