如何合并Python脚本:将ping.py与conf.py合并为单个文件
Merge ping.py and conf.py into a Single File
No problem at all! Since your ping.py imports settings and sites from conf.py, we just need to embed those configuration variables directly into the main script. Here's the full combined file, plus a quick breakdown of what changed:
Step-by-Step Breakdown
- Move configuration values from conf.py directly to the top of the merged file (replace the dummy values below with your actual settings)
- Remove the import line
from conf import settings, sitessince we no longer need to pull from a separate file - Keep all the existing logic from
ping.pyintact—it’ll work exactly as before, just in one file
Full Combined Code
#!/usr/bin/env python import smtplib import pyping import time import datetime # --- Configuration (from conf.py) --- settings = { "monitor_email": "your-monitor-email@example.com", "recipient_email": "your-recipient-email@example.com", "email_subject": "Site Availability Alert", # Add any other settings from your original conf.py here } sites = [ "example.com", "google.com", # Add all your target sites from original conf.py here ] # --- End Configuration --- """Sends an e-mail to the specified recipient.""" sender = settings["monitor_email"] recipient = settings["recipient_email"] subject = settings["email_subject"] headers = [ "From: " + sender, "Subject: " + subject, "To: " + recipient, "MIME-Version: 1.0", "Content-Type: text/plain; charset=utf-8" ] headers = "\r\n".join(headers) def send_email(message): try: server = smtplib.SMTP("your-smtp-server.com", 587) server.starttls() # Uncomment and fill in if your SMTP server requires authentication # server.login(settings["monitor_email"], settings["email_password"]) server.sendmail(sender, recipient, headers + "\r\n\r\n" + message) server.quit() print(f"Alert email sent at {datetime.datetime.now()}") except Exception as e: print(f"Failed to send email: {str(e)}") def monitor_sites(): while True: for site in sites: try: response = pyping.ping(site) if response.ret_code != 0: message = f"ALERT: {site} is unreachable at {datetime.datetime.now()}" print(message) send_email(message) else: print(f"{site} is reachable at {datetime.datetime.now()}") except Exception as e: message = f"ERROR checking {site}: {str(e)}" print(message) send_email(message) time.sleep(300) # Wait 5 minutes between checks if __name__ == "__main__": monitor_sites()
Quick Notes
- Fill in your actual SMTP server details, email credentials, and target sites in the configuration section to match your original
conf.py - If your original
conf.pyhad extra settings or variables, just add them to thesettingsdictionary or as standalone variables in the configuration block - Double-check that
pypingis installed (pip install pyping) if you haven’t already set up dependencies
内容的提问来源于stack exchange,提问作者Maximus
相关产品推荐
相关产品推荐

