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

Jenkins Pipeline脚本中无法执行Python命令问题求助

解决Jenkins Pipeline中找不到calc.py文件的问题

我来帮你排查这个问题!你遇到的calc.py: not found错误,大概率是代码拉取后的文件路径不对导致的,咱们一步步来解决:

第一步:确认代码拉取后的目录结构

首先,在你的Test阶段里,拉取代码后先执行一个查看目录的命令,确认calc.py是否在当前工作目录里。修改Pipeline脚本如下:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building the application....'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing the application....'
                git branch: 'python', url: 'https://github.com/jatin633/Calculator.git'
                // 新增这行,查看当前目录的所有文件和文件夹
                sh 'ls -la'
                sh 'python calc.py'
                sh 'python calculator_unittest.py'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploy the application....'
            }
        }
    }
}

运行这个Pipeline后,查看Test阶段的日志,看看输出里有没有calc.py,或者是不是代码被拉取到了某个子文件夹里(比如Calculator目录)。

第二步:根据目录结构调整执行路径

如果日志显示calc.py在子文件夹里(比如拉取的代码存放在Calculator目录下),那你需要切换到对应目录再执行Python命令。有两种方式:

方式一:用cd命令切换目录

修改Test阶段的脚本:

stage('Test') {
    steps {
        echo 'Testing the application....'
        git branch: 'python', url: 'https://github.com/jatin633/Calculator.git'
        // 先进入代码所在的子目录
        sh 'cd Calculator && python calc.py'
        sh 'cd Calculator && python calculator_unittest.py'
    }
}

方式二:用Jenkins的dir步骤指定工作目录

这种方式更清晰,适合多目录场景:

stage('Test') {
    steps {
        echo 'Testing the application....'
        git branch: 'python', url: 'https://github.com/jatin633/Calculator.git'
        // 指定后续命令在Calculator目录下执行
        dir('Calculator') {
            sh 'python calc.py'
            sh 'python calculator_unittest.py'
        }
    }
}

额外检查点:Python命令的兼容性

如果确认文件路径没问题还是报错,可能是环境里的Python命令名称问题——有些系统里python指向Python2,而你的代码需要Python3,这时候可以尝试用python3代替python:

sh 'python3 calc.py'

按照这个流程排查调整,应该就能解决文件找不到的问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 20:17:31