开发者

Start nano as a subprocess from python, capture input

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 subprocess module before, nor pipes, so I don't know what to try next.

So far I have this code:

a = subprocess.Popen('nano', stdout=subprocess.PIPE, shell=True)

Where a should capture the output. This code, however, doesn't bring up nano, and instead makes the python terminal behave strangely. Up and down keys (history) stop working and the backspace key becomes dysfunctional.

Can someone point me in the right direction to solve this issue? I realize that I may need to read up on pipes in Python, but the only info I can find开发者_开发百科 is the pipes module and it doesn't help much.


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!


>>> 


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜