以专家视角生成满足任务需求的完整脚本方案
下面是一个Python脚本,使用PyMySQL库实现了连接远程数据库、执行SQL查询、格式化数据为CSV文件并处理潜在错误的需求。脚本支持通过命令行参数传入数据库账户信息文件路径和CSV保存路径。 先安装依赖库: ```bash pip install pymysql ``` ### Python脚本代码 ```python import pymysql import csv import argparse import json import sys def load_db_credentials(file_path): """ Load database connection credentials from a given JSON file. """ try: with open(file_path, 'r') as file: credentials = json.load(file) return credentials except FileNotFoundError: print(f"Error: Credential file '{file_path}' not found.") sys.exit(1) except json.JSONDecodeError: print(f"Error: Unable to parse the JSON file '{file_path}'. Ensure it's valid.") sys.exit(1) def connect_to_database(credentials): """ Establish a connection to the database with error handling. """ try: connection = pymysql.connect( host=credentials['host'], user=credentials['user'], password=credentials['password'], database=credentials['database'], port=credentials.get('port', 3306), # Default port for MySQL is 3306 cursorclass=pymysql.cursors.DictCursor ) return connection except pymysql.MySQLError as e: print(f"Database connection error: {e}") sys.exit(1) def execute_query(connection, query): """ Execute the given SQL query and fetch results. """ try: with connection.cursor() as cursor: cursor.execute(query) results = cursor.fetchall() return results except pymysql.MySQLError as e: print(f"SQL execution error: {e}") sys.exit(1) def save_to_csv(data, output_file): """ Save the query results to a CSV file. """ try: if len(data) == 0: print("No data returned to save as CSV file.") sys.exit(0) # Extract headers from the keys of the first dictionary in the data list headers = data[0].keys() with open(output_file, mode='w', newline='', encoding='utf-8') as file: writer = csv.DictWriter(file, fieldnames=headers) # Write header row writer.writeheader() # Write data rows writer.writerows(data) print(f"Data successfully saved to {output_file}") except Exception as e: print(f"Error while saving CSV: {e}") sys.exit(1) def main(): # Set up argument parser parser = argparse.ArgumentParser(description="Connect to a database, execute an SQL query, and save results to a CSV file.") parser.add_argument("credentials", help="Path to JSON file with database connection credentials.") parser.add_argument("query", help="SQL query to execute.") parser.add_argument("output", help="Path to save the CSV file.") args = parser.parse_args() # Load database credentials credentials = load_db_credentials(args.credentials) # Connect to the database connection = connect_to_database(credentials) # Execute the SQL query results = execute_query(connection, args.query) # Close the database connection connection.close() # Save results to CSV save_to_csv(results, args.output) if __name__ == "__main__": main() ``` --- ### 功能说明 1. **脚本参数**: - `credentials`: 数据库连接信息保存为一个JSON文件,包含如下格式: ```json { "host": "your_host", "user": "your_username", "password": "your_password", "database": "your_database", "port": 3306 } ``` `port`参数是可选的(默认为3306)。 - `query`: 用于执行的SQL查询语句。 - `output`: CSV文件保存路径。 2. **脚本步骤**: - 从用户指定的账户信息JSON文件加载数据库连接配置。 - 使用PyMySQL库连接到MySQL数据库。 - 执行SQL查询语句。 - 查询数据并保存为CSV文件。 3. **错误处理**: - 捕获文件读取错误(如账户信息文件不存在或JSON语法错误)。 - 数据库连接错误(如用户名密码错误,主机不可达)。 - SQL语法错误或查询问题。 - CSV文件写入过程中的错误。 4. **运行方式**: 使用如下命令运行: ```bash python script.py credentials.json "SELECT * FROM your_table WHERE condition" output.csv ``` 5. **可扩展性**: - 可自行修改JSON文件中的键名或增加更多数据库配置。 - 自定义数据过滤SQL语句。 - 扩展支持其他数据库类型(通过替换PyMySQL库)。 --- ### 示例 假设有以下SQL查询: ```sql SELECT id, name, email FROM users WHERE status = 'active'; ``` 命令行运行示例: ```bash python script.py db_credentials.json "SELECT id, name, email FROM users WHERE status = 'active'" active_users.csv ``` 结果:保存查询到的`id`, `name`, `email`数据于`active_users.csv`。 通过这份脚本,你可以快速实现远程数据库操作并生成CSV,非常适用于脚本化查询任务的场景。
以下是实现你需求的Python脚本,脚本包括基本功能(清洗数据并生成折线图)以及可选功能(支持命令行参数、处理错误等): ```python import pandas as pd import matplotlib.pyplot as plt import argparse import os from datetime import datetime def clean_and_visualize_data(input_file, output_file): try: # 1. 读取数据文件 print(f"Reading file: {input_file}") data = pd.read_csv(input_file) # 2. 去重处理 print("Removing duplicates...") data.drop_duplicates(inplace=True) # 3. 日期字段规范化处理 if 'date' not in data.columns or 'sales' not in data.columns: raise ValueError("The input data must contain 'date' and 'sales' columns.") print("Normalizing date column...") try: data['date'] = pd.to_datetime(data['date']) except Exception as e: raise ValueError(f"Error parsing column 'date': {e}") # 4. 按月汇总销售数据 print("Aggregating sales data by month...") data['month'] = data['date'].dt.to_period('M').dt.to_timestamp() monthly_sales = data.groupby('month')['sales'].sum().reset_index() # 5. 生成销售趋势折线图 print(f"Generating trend chart and saving to {output_file}...") plt.figure(figsize=(10, 6)) plt.plot(monthly_sales['month'], monthly_sales['sales'], marker='o', linestyle='-', color='b', label='Monthly Sales') plt.title('Monthly Sales Trend') plt.xlabel('Month') plt.ylabel('Total Sales') plt.grid(True) plt.legend() plt.tight_layout() plt.savefig(output_file) print("Trend chart successfully saved.") except FileNotFoundError: print(f"Error: The file '{input_file}' was not found.") except pd.errors.EmptyDataError: print(f"Error: The file '{input_file}' is empty.") except ValueError as ve: print(f"Value Error: {ve}") except Exception as e: print(f"An unexpected error occurred: {e}") def main(): # 设置命令行参数解析 parser = argparse.ArgumentParser(description="Clean sales data and generate a monthly sales trend chart.") parser.add_argument('--input_file', type=str, default='sales_data.csv', help="Path to the input CSV file (default: sales_data.csv).") parser.add_argument('--output_file', type=str, default='trend_chart.png', help="Path to save the output trend chart image (default: trend_chart.png).") args = parser.parse_args() # 检查文件是否存在 if not os.path.exists(args.input_file): print(f"Error: Input file '{args.input_file}' does not exist.") return # 调用主要清洗与可视化功能 clean_and_visualize_data(args.input_file, args.output_file) if __name__ == "__main__": main() ``` ### 功能解读: 1. **读取CSV文件** - 默认文件名为`sales_data.csv`,支持通过`--input_file`参数指定文件路径。 - 使用`pandas.read_csv`读取数据,带有错误处理,如文件不存在或数据为空。 2. **数据去重与日期规范化** - 去重:使用`drop_duplicates`清理重复的行。 - 统一日期字段:尝试将`date`列解析为标准`datetime`格式。 3. **按月汇总销售数据** - 使用`groupby`对销售数据按月份进行汇总。 4. **生成折线图** - 使用`matplotlib`绘制图表,并保存为PNG文件(默认保存为`trend_chart.png`,支持通过`--output_file`指定路径)。 5. **错误处理** - 包含文件不存在、CSV为空、日期解析失败等错误类型的处理逻辑,保证脚本的健壮性。 6. **命令行参数支持** - 使用`argparse`构建更灵活的脚本,通过命令行接受用户指定的输入和输出路径。 ### 脚本运行方式: ```bash # 使用默认文件名和输出路径 python sales_trend.py # 指定输入和输出路径 python sales_trend.py --input_file=my_sales_data.csv --output_file=my_trend_chart.png ``` 这个脚本通用性强,灵活可配置,并通过错误处理保证了稳定运行。请确保文件中包含必要字段(如`date`和`sales`)。
以下是实现以上需求的Bash脚本: ```bash #!/bin/bash # 自动化分析服务器日志,提取错误信息 # 检查是否提供日志文件路径和汇总文件路径参数 if [ "$#" -lt 2 ]; then echo "Usage: $0 <log_file_path> <output_summary_path>" exit 1 fi # 接收参数 LOG_FILE="$1" OUTPUT_FILE="$2" # 检查日志文件是否存在 if [ ! -f "$LOG_FILE" ]; then echo "Error: Log file <$LOG_FILE> not found!" exit 1 fi # 创建/清空汇总文件 > "$OUTPUT_FILE" # 提取包含错误关键字的日志信息并写入汇总文件 echo "Extracting error information from <$LOG_FILE>..." grep -i "error" "$LOG_FILE" > "$OUTPUT_FILE" if [ $? -eq 0 ]; then echo "Error information extracted successfully to <$OUTPUT_FILE>." else echo "No errors found in <$LOG_FILE>." fi exit 0 ``` ### 脚本说明 1. 参数传递: - **脚本第1步**通过检查参数列表确定用户是否指定了日志文件路径和输出路径。如果未指定,将输出使用方法说明并退出程序。 2. 错误处理: - 若日志文件路径不存在,脚本将检测到文件不存在并终止运行,提示用户。 3. `grep` 命令: - 使用 `grep -i "error"` 忽略错误关键字大小写。 - 提取的日志行直接写入指定的汇总文件。 4. 灵活性: - 用户可以通过命令行指定任意日志文件路径和输出文件路径。 ### 用法示例 假如该脚本命名为 `log_analyzer.sh`,则可以如下使用: ```bash # 提取 /logs/error.log 中的错误信息到 error_summary.log ./log_analyzer.sh /logs/error.log ./error_summary.log # 提取其他指定日志,比如 /var/logs/my_app.log 中的错误信息 ./log_analyzer.sh /var/logs/my_app.log ./output_errors.log ``` ### 测试与改进 - 可以将脚本扩展为提取特定格式的错误信息(如日期、类别等),或者对错误内容统计。 - 如果您需要更复杂错误类型处理或者日志格式解析,请提供详细需求,我将优化实现!
需要为特定任务快速生成高效、可扩展的脚本,提升日常开发效率,优化项目交付质量。
需编写脚本以处理复杂数据或完成自动化任务,减少处理时间并提升数据操作准确性。
需要在日常维护中快速生成脚本用于自动化部署、故障排查和系统优化,提升工作效率。
面对复杂脚本编写难题,可以通过提示词获得专业级脚本模板,轻松完成学习任务。
可用提示词生成脚本案例,通过快速构建演示代码辅助教学与实验。
帮助用户通过简单输入,快速生成满足任务需求的完整脚本,提高开发效率并降低编程难度。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
免费获取高级提示词-优惠即将到期