从 python 启动 nano 作为子进程,捕获输入
我试图从Python内部启动一个文本编辑器(nano),让用户输入文本,然后在写出后捕获文本(Control-O)。我之前没有使用过 subprocess
模块,也没有使用过管道,所以我不知道接下来要尝试什么。
到目前为止,我有这段代码:
a = subprocess.Popen('nano', stdout=subprocess.PIPE, shell=True)
其中 a
应该捕获输出。然而,这段代码并没有启动 nano,而是使 python 终端表现得很奇怪。向上和向下键(历史记录)停止工作,退格键无法正常工作。
有人可以指出我解决这个问题的正确方向吗?我意识到我可能需要阅读 Python 中的管道,但我能找到的唯一信息是 Pipes 模块,而且它没有多大帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Nano 中的 Control-O 写入正在编辑的文件,即不到标准输出 - 因此,放弃捕获标准输出的尝试,只需在用户使用时读取文件将其写出并退出 Nano。例如,在我的 Mac 上:
在这里,我写下“Hello world!”然后点击 control-O 返回 control-X ,并且:
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:
Here, I write "Hello world!" then hit control-O Return control-X , and:
我不确定您是否可以捕获用户在
nano
中输入的内容。毕竟,那是 nano 的工作。您可以(而且我认为应该做)从编辑器获取用户输入的方法是使用 临时文件。然后,当用户输入他想要的内容时,他保存并退出。您的程序从文件中读取内容,然后将其删除。
只需使用 os.system 生成编辑器即可。您的终端表现得很有趣,因为 nano 是一个全屏程序,并且将使用终端转义序列(可能通过.curses)来操纵屏幕和光标。如果您在未连接到终端的情况下生成它,它会出现异常行为。
另外,如果它是定义的而不是 nano,您应该考虑打开
$EDITOR
。这正是人们所期望的。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.