views:

51

answers:

2

Hello, 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.

+2  A: 

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!


>>> 
Alex Martelli
Perfect, thank you!
alecwh
@alecwh, you're welcome!
Alex Martelli
+3  A: 

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.

Noufal Ibrahim