多功能命令行工具:解析、执行和处理各种文本内容

57 阅读3分钟

多功能命令行工具:解析、执行和处理各种文本内容

功能说明:

这个命令行工具是一个多功能工具,可以帮助用户解析、执行和处理各种文本内容,用于结合quicker使用,主要功能包括:

image.png 读取运行时传入的参数,如果没有参数则进行以下逻辑判断:

如果参数是:kimi,则打开kimi网址。 如果传入参数是:None,则不执行任何操作。 文本内容识别: 选中网址文本,直接打开网址。 选中运算文本,直接计算并显示结果。 选中命令文本,直接执行命令。 选中文件路径文本,直接打开对应的文件路径。 其他文本类型,默认进行搜索操作。 该命令行工具通过结合正则表达式和系统调用,实现了对各种文本内容的识别和处理,提供了丰富的功能和灵活的应用场景。

code

import sys

import argparse

import subprocess

import webbrowser

import clipboard

import re

import pyperclip

import pyautogui

import os

import shlex

  


# 创建解析器

parser = argparse.ArgumentParser(description='A versatile command line tool.')

parser.add_argument('--kimi', help='询问kimi')

parser.add_argument('query',nargs='?', type=str, help='解析query')

# 解析命令行参数

args = parser.parse_args()

  


def open_url(url):

    webbrowser.open(url)

  


def calculate_expression(expression):

    try:

        result = eval(expression)

        return result

    except Exception as e:

        return str(e)

  


def run_python_command(command):

    try:

        # 使用 subprocess.run 捕获标准输出

        result = subprocess.run(['python', '-c', command], shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        return result.stdout

    except subprocess.CalledProcessError as e:

        return e.stderr

   

def run_terminal_command(command):

    try:

        # 使用 os.system 执行终端命令

        os.system(command)

    except Exception as e:

        return str(e)

  


def open_file_path(file_path):

    # 检查路径是否存在

    if os.path.exists(file_path):

        # 使用os.startfile打开文件夹

        os.startfile(file_path)

    else:

        print("指定的路径不存在。")

  
  


def search_text(text):

    webbrowser.open(f"https://www.baidu.com/s?wd={text}")

  


def handle_clipboard_content(content_type, content):

    if content_type == "text":

        if content.startswith("http"):

            open_url(content)

        elif any(char.isdigit() for char in content):

            result = calculate_expression(content)

            return result

        elif content.startswith("python") or content.startswith("cd") or content.startswith("dir"):

            if content.startswith("python"):

                return run_python_command(content)

            else:

                return run_terminal_command(content)

        elif any(char in content for char in ":/\\"):

            open_file_path(content)

        else:

            search_text(content)

    elif content_type == "file":

        print("File content")

    elif content_type == "image":

        print("Image content")

    else:

        print("No content")

  
  


# 识别判断

def process_text(text):

   

    # 正则表达式匹配路径文本,包括那些包含空格的路径

    path_pattern = r'^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]+$'

  


    if re.match(path_pattern, text):

        open_file_path(text)

        return

   

    # 正则表达式匹配网址

    url_pattern = r'(https?://\S+)'

    if re.match(url_pattern, text):

        open_url(text)

        return

   

    # 正则表达式匹配运算文本

    expression_pattern = r'^[\d\+\-\*\/\(\)\.]+$'

    if re.match(expression_pattern, text):

        result = calculate_expression(text)

        pyperclip.copy(text+"="+str(result))

        pyautogui.hotkey('ctrl', 'v')

        return result

   

    # 正则表达式匹配Python命令

    python_command_pattern = r"""

        # 匹配Python的关键字和内置函数

        (?:inline\s+)?            # 可选的 'inline' 关键字

        (import|from|class|def|if|elif|else|for|while|try|except|finally|with|return|break|continue|pass|assert|yield|lambda|del|print)\b

    """

  


    # 检查是否为Python命令

    is_python_command = re.search(python_command_pattern, text, re.VERBOSE)

    if is_python_command:

        res=run_python_command(text)  # 传递要执行的 Python 命令

        return res

    # 正则表达式匹配终端命令

    terminal_command_pattern = r"""

        # 匹配常见的终端命令

        ^\s*(ls|cd|mkdir|touch|rm|mv|cp|grep|sed|awk|chmod|chown|find|kill|ps|top|ping|wget|curl|ssh|scp|pip)\b

        # 匹配命令的参数和选项

        |                           # 或者

        (\b[a-zA-Z0-9_-]+\b(?:\s+[-a-zA-Z0-9_./:=]+)*)

        # 匹配管道操作符

        |                           # 或者

        (\|\s*[a-zA-Z0-9_-]+)

        # 匹配重定向操作符

        |                           # 或者

        (\s*[><]*\s*[a-zA-Z0-9_./]+)

    """

    # 检查是否为终端命令

    is_terminal_command = re.search(terminal_command_pattern, text, re.VERBOSE)

    if is_terminal_command:

        print('命令',text)

        run_terminal_command(text)

        return

  


   

    search_text(text)

   

   

  


def main():

  


    # 使用参数

    if args.kimi:

        open_url('https://kimi.moonshot.cn/')

    elif args.query:

        print("收到内容,开始识别",args.query)

        res=process_text(args.query)

        print(res)

    elif len(sys.argv) < 2:

        print('没有传递内容')

  
  
  


if __name__ == "__main__":

    main()