从python启动nano作为子进程,捕获输入 [英] Start nano as a subprocess from python, capture input

查看:170
本文介绍了从python启动nano作为子进程,捕获输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Python内部启动文本编辑器(nano),让用户输入文本,然后在写出内容时(Control-O)捕获文本.我以前没有使用subprocess模块,也没有管道,所以我不知道下一步该怎么做.

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)

a应该捕获输出的位置.但是,此代码不会显示nano,而是使python终端的行为异常.向上键和向下键(历史记录)停止工作,并且退格键不起作用.

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.

有人可以指出正确的方向来解决这个问题吗?我意识到我可能需要阅读Python中的管道,但是我能找到的唯一信息是pipes模块,它并没有太大帮助.

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将正在编辑的文件写入,即,将 not 写入标准输出- -因此,放弃尝试捕获标准输出并在用户将其写出并退出Nano后立即读取文件的尝试.例如,在我的Mac上:

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])

在这里,我写你好,世界!"然后按control-O Return control-X,然后:

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

0
>>> with open(n) as f: print f.read()
... 
Hello world!


>>> 

这篇关于从python启动nano作为子进程,捕获输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆