在curses应用程序中使用子进程
我正在创建一个使用 curses
构建简单用户界面的应用程序。它还使用 subprocess
模块来运行外部文本编辑器,以便用户可以键入一些文本,然后关闭编辑器并返回主程序。
问题是,当编辑器是基于控制台的(例如 Vim 或 Nano)时,curses 无法正确取消初始化。这意味着如果使用颜色模式(curses.start_color()
),程序完成后终端将保持彩色状态。
这是一个存在此问题的测试脚本(至少对我来说,我使用 Ubuntu 和 gnome-terminal):(
import curses
import subprocess
screen = curses.initscr()
curses.noecho()
curses.cbreak()
screen.keypad(1)
try:
curses.curs_set(0)
except curses.error:
pass
curses.start_color()
screen.addstr(0, 0, 'hello, world!')
screen.refresh()
while 1:
c = screen.getch()
if c == ord('q'):
break
if c == ord('r'):
subprocess.call('vim', shell=False)
screen.clear()
screen.addstr(0, 0, 'hello, world!')
screen.refresh()
curses.nocbreak()
screen.keypad(0)
curses.echo()
curses.curs_set(1)
curses.endwin()
按 r
进入 Vim,然后按 q
退出。)
有办法解决这个问题吗?
I'm creating an application that uses curses
to build a simple user interface. It also uses the subprocess
module to run external text editor so a user can type some text, then close the editor and go back to the main program.
The problem is that when the editor is console-based such as Vim or Nano, curses doesn't de-initialize properly. Which means if the color mode is used (curses.start_color()
), terminal stays colored after the program is finished.
Here's a test script that has this issue (at least for me, I use Ubuntu and gnome-terminal):
import curses
import subprocess
screen = curses.initscr()
curses.noecho()
curses.cbreak()
screen.keypad(1)
try:
curses.curs_set(0)
except curses.error:
pass
curses.start_color()
screen.addstr(0, 0, 'hello, world!')
screen.refresh()
while 1:
c = screen.getch()
if c == ord('q'):
break
if c == ord('r'):
subprocess.call('vim', shell=False)
screen.clear()
screen.addstr(0, 0, 'hello, world!')
screen.refresh()
curses.nocbreak()
screen.keypad(0)
curses.echo()
curses.curs_set(1)
curses.endwin()
(Press r
to enter Vim, then q
to exit.)
Is there a way to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将您的代码修改为:
对您来说足够了吗?或者您的真实脚本中是否存在一些不在您粘贴到此处的代码中的其他行为,这使得此解决方法不适合您的目标?
Would modifying your code to:
be enough for you? Or is there some additional behaviour in your real script that is not in the code you pasted here, that makes this workaround unsuitable to your goal?