You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重写slippy工具遇阻:无法按数字后缀匹配终止输出

解决方案

我们需要扩展代码以支持两种q终止规则:行号匹配终止和正则表达式匹配终止。以下是修改后的代码:

import sys
import re

def main():
    if len(sys.argv) != 2:
        print("Usage: python3 slippy '<command>'", file=sys.stderr)
        sys.exit(1)
    
    slippy_command = sys.argv[1]
    target_line = None
    regex_pattern = None

    # 解析q命令格式
    if slippy_command.endswith('q'):
        # 识别正则匹配型命令(格式:/pattern/q)
        if slippy_command.startswith('/') and slippy_command[-2] == '/':
            regex_pattern = slippy_command[1:-2]
            regex = re.compile(regex_pattern)
        else:
            # 识别行号匹配型命令(格式:Nq)
            try:
                target_line = int(slippy_command[:-1])
            except ValueError:
                print(f"Invalid command: {slippy_command}", file=sys.stderr)
                sys.exit(1)
    else:
        print(f"Command does not end with 'q': {slippy_command}", file=sys.stderr)
        sys.exit(1)

    line_number = 0
    while True:
        line = sys.stdin.readline()
        line_number += 1
        if not line:  # 读取到输入末尾,退出循环
            break
        
        print(line, end='')
        
        # 检查终止条件
        if target_line is not None:
            if line_number == target_line:
                break
        elif regex_pattern is not None:
            if regex.search(line):
                break

if __name__ == "__main__":
    main()

代码说明

  • 命令解析逻辑:

    • 先校验命令是否以q结尾,不符合则直接报错退出
    • 若命令以/开头且倒数第二个字符为/,则提取中间内容作为正则匹配规则
    • 否则尝试将q前的内容转为整数,作为目标终止行号,转换失败则报错
  • 终止执行逻辑:

    • 行号匹配:当当前行号等于目标行号时,立即停止输出并退出
    • 正则匹配:当当前行内容匹配指定正则表达式时,立即停止输出并退出

测试验证

  • 行号终止测试:执行seq 1 10 | python3 slippy '5q',输出前5行后自动停止
  • 正则终止测试:执行seq 10 15 | python3 slippy '/.1/q',输出到11后停止(/.1/会匹配到11中的字符组合)
  • 若需要精确匹配行末尾为1的数字,可使用正则/1$/q,执行seq 10 15 | python3 slippy '/1$/q'也会在11行停止

内容的提问来源于stack exchange,提问作者Ruthann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:39:25