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

新手求助:如何结合Jenkins、GitHub实现Python阶乘程序自动化与邮件报告

Hey there! Let's break this down step by step—since you're new to both Jenkins and GitHub, I'll keep things straightforward and actionable, covering both your general question about integrating Jenkins/GitHub with email reports and your specific Python factorial project request.

Step 1: Set Up Your Python Factorial Project on GitHub

First, let's get your code up on GitHub so Jenkins can access it:

  • Create a new repository on GitHub (name it something like python-factorial-demo), then clone it to your local machine using git clone <your-repo-url>.
  • Inside the cloned folder, create a factorial.py file with this code (I've modified it to accept command-line arguments so Jenkins can run it without manual input, plus it generates a run report):
import datetime
import sys

def factorial(n):
    if n < 0:
        return "Error: Negative numbers don't have factorials"
    elif n == 0 or n == 1:
        return 1
    else:
        result = 1
        for i in range(2, n+1):
            result *= i
        return result

if __name__ == "__main__":
    # Accept a number via command line to avoid manual input
    if len(sys.argv) != 2:
        error_msg = "Usage: python factorial.py <integer-number>"
        print(error_msg)
        with open("run_report.txt", "w") as f:
            f.write(f"Run Timestamp: {datetime.datetime.now()}\n")
            f.write(f"Error: {error_msg}\n")
        sys.exit(1)
    
    try:
        num = int(sys.argv[1])
        result = factorial(num)
        print(f"Factorial of {num} is: {result}")
        # Generate a structured run report
        with open("run_report.txt", "w") as f:
            f.write(f"Run Timestamp: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"Input Number: {num}\n")
            f.write(f"Factorial Result: {result}\n")
    except ValueError:
        error_msg = "Invalid input: Please enter a valid integer"
        print(error_msg)
        with open("run_report.txt", "w") as f:
            f.write(f"Run Timestamp: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"Error: {error_msg}\n")
  • Commit and push this code to GitHub:
    git add factorial.py
    git commit -m "Initial commit: Add factorial program with run report"
    git push origin main
    
Step 2: Configure Jenkins to Work with GitHub & Send Email Reports

Assuming you already have Jenkins installed, first install these essential plugins via Manage Jenkins > Plugins:

  • Git Plugin (to connect with GitHub)
  • Email Extension Plugin (for flexible email notifications, better than the default plugin)
  • Go to Manage Jenkins > Credentials > System > Global credentials (unrestricted).
  • Click Add Credentials, select "Username with password" as the type:
    • Username: Your GitHub username
    • Password: A GitHub Personal Access Token (PAT) with repo permissions (create this in GitHub's Settings > Developer settings > Personal access tokens)
    • Give it a descriptive ID and description, then save.
  • Next, go to Manage Jenkins > Configure System > Git:
    • Ensure your Jenkins server has Git installed (if not, install it via your OS package manager first).
    • Set the "Path to Git executable" to your Git install path (e.g., /usr/bin/git on Linux, C:\Program Files\Git\bin\git.exe on Windows).

2.2 Create a Jenkins Freestyle Project

  • Click New Item, enter a project name (e.g., Factorial-Build), select "Freestyle project", then click OK.
  • Source Code Management

    • Select Git, paste your GitHub repository URL, then choose the GitHub credential you created earlier from the dropdown.
    • Specify the branch to build (e.g., */main).
  • Build Triggers

    • Check GitHub hook trigger for GITScm polling—this tells Jenkins to automatically start a build whenever you push code to GitHub.
    • Note: You’ll need to add a webhook to your GitHub repo: Go to GitHub repo > Settings > Webhooks > Add webhook. Enter your Jenkins URL followed by /github-webhook/ (e.g., http://your-jenkins-ip:8080/github-webhook/), set "Content type" to application/json, then click "Add webhook".
  • Build Environment

    • Check Delete workspace before build starts to avoid conflicts with old files.
  • Build Steps

    • Add an Execute shell step (Linux/macOS) or Execute Windows batch command step (Windows) with these commands:
      # Verify Python is installed
      python --version
      # Run the factorial program with a test number (e.g., 5)
      python factorial.py 5
      # Print the report to Jenkins build logs (optional but helpful)
      cat run_report.txt
      

2.3 Set Up Email Notifications (Send Run Reports)

First, configure global email settings:

  • Go to Manage Jenkins > Configure System > Extended E-mail Notification:
    • Enter your SMTP server details (e.g., for Gmail: SMTP server = smtp.gmail.com, port = 587, check "Use SSL/TLS").
    • Enter your email address as the "User Name", and use an app-specific password (for Gmail, enable 2FA first then create this in Google Account > Security > App passwords).
    • Set "Default Recipients" to your email address, and "Default Subject" to something like Jenkins Build Report: ${PROJECT_NAME} - #${BUILD_NUMBER} (${BUILD_STATUS}).

Then configure email notifications for your project:

  • Back in your Jenkins project, go to Post-build Actions > Add post-build action > Editable Email Notification.
  • Under Attachments, enter run_report.txt to include the generated report as an email attachment.
  • Under Content, paste this custom message (you can tweak it as needed):

    Build Status: ${BUILD_STATUS}
    Build Number: ${BUILD_NUMBER}
    Repository: ${GIT_URL}
    Branch Built: ${GIT_BRANCH}

    Here’s your run report:
    ${FILE,path="run_report.txt"}

  • Under Triggers, check Success and Failure so you get an email regardless of whether the build passes or fails.
  • Save the project settings.
Step 3: Test the Entire Workflow
  • Make a small change to your local factorial.py (e.g., update the error message for negative numbers).
  • Commit and push the change to GitHub:
    git add factorial.py
    git commit -m "Update negative number error message"
    git push origin main
    
  • Head back to Jenkins—you should see a new build start automatically. Once it finishes, check your email: you’ll get a message with the build status and the run_report.txt attachment containing the program’s output.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:52:25