热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
以专家视角生成满足任务需求的完整脚本方案
下面是一个Python脚本,使用PyMySQL库实现了连接远程数据库、执行SQL查询、格式化数据为CSV文件并处理潜在错误的需求。脚本支持通过命令行参数传入数据库账户信息文件路径和CSV保存路径。
先安装依赖库:
pip install pymysql
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()
脚本参数:
credentials: 数据库连接信息保存为一个JSON文件,包含如下格式:
{
"host": "your_host",
"user": "your_username",
"password": "your_password",
"database": "your_database",
"port": 3306
}
port参数是可选的(默认为3306)。query: 用于执行的SQL查询语句。output: CSV文件保存路径。脚本步骤:
错误处理:
运行方式: 使用如下命令运行:
python script.py credentials.json "SELECT * FROM your_table WHERE condition" output.csv
可扩展性:
假设有以下SQL查询:
SELECT id, name, email FROM users WHERE status = 'active';
命令行运行示例:
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脚本,脚本包括基本功能(清洗数据并生成折线图)以及可选功能(支持命令行参数、处理错误等):
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()
读取CSV文件
sales_data.csv,支持通过--input_file参数指定文件路径。pandas.read_csv读取数据,带有错误处理,如文件不存在或数据为空。数据去重与日期规范化
drop_duplicates清理重复的行。date列解析为标准datetime格式。按月汇总销售数据
groupby对销售数据按月份进行汇总。生成折线图
matplotlib绘制图表,并保存为PNG文件(默认保存为trend_chart.png,支持通过--output_file指定路径)。错误处理
命令行参数支持
argparse构建更灵活的脚本,通过命令行接受用户指定的输入和输出路径。# 使用默认文件名和输出路径
python sales_trend.py
# 指定输入和输出路径
python sales_trend.py --input_file=my_sales_data.csv --output_file=my_trend_chart.png
这个脚本通用性强,灵活可配置,并通过错误处理保证了稳定运行。请确保文件中包含必要字段(如date和sales)。
以下是实现以上需求的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
grep 命令:
grep -i "error" 忽略错误关键字大小写。假如该脚本命名为 log_analyzer.sh,则可以如下使用:
# 提取 /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 工具间无缝衔接。
免费获取高级提示词-优惠即将到期