如何使用Python自动应答终端中eslint --init的交互式选项问题
解决方案
方案1:使用eslint --init非交互模式(优先推荐)
eslint --init本身支持通过命令行参数指定所有配置项,完全跳过交互式提问步骤,是最稳定的实现方案,你可以根据自己的需求直接拼接参数即可,示例命令如下:
eslint --init --env browser,node \ --parser @typescript-eslint/parser \ --plugins @typescript-eslint \ --extends eslint:recommended,@typescript-eslint/recommended \ --ignore-path .gitignore \ --yes
你可以根据自己的项目需求调整参数内容,直接替换你原来代码里的eslint --init命令即可,不需要额外处理交互逻辑。
方案2:模拟终端按键处理交互式命令(通用方案)
如果你遇到的其他命令没有非交互模式,必须处理交互式选择菜单,可以使用pexpect库模拟终端输入,实现自动选择和确认。
原理说明
你遇到的箭头选择菜单实际是读取终端的控制字符序列实现的,对应按键的转义序列如下:
- 上箭头:
\x1b[A - 下箭头:
\x1b[B - 左箭头:
\x1b[D - 右箭头:
\x1b[C - 回车确认:
\r
实现步骤
- 首先安装依赖库
pip install pexpect
- 替换原有代码实现自动应答
import pexpect import pathlib def eslint_init(): if pathlib.Path('.eslintrc.js').exists(): print('already initialized') return # 启动eslint --init子进程 child = pexpect.spawn('eslint --init', timeout=30) # 匹配第一个问题,选择第二个选项 child.expect(r'How would you like to use ESLint\?') child.send('\x1b[B') # 按一次下箭头选中第二个选项 child.send('\r') # 回车确认 # 匹配第二个问题,选择CommonJS选项 child.expect(r'What type of modules does your project use\?') child.send('\x1b[B') # 按一次下箭头选中第二个选项 child.send('\r') # 回车确认 # 后续问题按照你的选择需求依次添加匹配和发送逻辑即可 # 等待进程执行完成 child.wait() print('eslint初始化完成')
Windows系统兼容说明
pexpect不支持Windows系统,你可以使用wexpect库替代,接口逻辑完全一致,安装命令为pip install wexpect,引入时替换为import wexpect as pexpect即可使用。
内容的提问来源于stack exchange,提问作者Rasheed kotoor
相关产品推荐
相关产品推荐

