簡體   English   中英

在 Jenkins 管道 Shell 中運行 Python 腳本

[英]Running A Python Script In Jenkins Pipeline Shell

我遇到了一個問題,我似乎無法在 Jenkins 管道腳本中運行 python 腳本。

如果我創建 Jenkins 自由式作業並執行 shell :

#!/usr/bin/env python
import boto3

導入工作,我可以運行我的 python 代碼的 rest。

但是,如果我創建一個 Jenkins 管道並嘗試運行以下命令:

pipeline {
    agent { label 'master' }
    stages {
        stage('job') {
            steps {
                sh '''
                    #!/usr/bin/env python
                    import boto3
                '''
            }
        }
    }
}

我得到import: command not found

我需要以其他方式設置環境嗎?

更新:

所以我嘗試了這個:

pipeline {
    agent { label 'master' }
    stages {
        stage('job') {
            steps {
                sh '''#!/usr/bin/env python
                import boto3
                '''
            }
        }
    }
}

現在我得到一個縮進錯誤。

我試過以百萬種方式縮進它,但沒有運氣。

當我在沒有導入 boto3 的情況下運行上述內容時,作業運行良好。

我還檢查了 Jenkins 服務器上的代碼片段生成器並閱讀以下內容:

“可以使用解釋器選擇器,例如:#!/usr/bin/perl”

更新

以下作品:

pipeline {
    agent { label 'master' }
    stages {
        stage('job') {
            steps {
                sh '''#!/usr/bin/env python \n''' +
                '''import boto3'''
            }
        }
    }
}

唯一的問題是在每行似乎有點太多之后必須使用 \n 和 + ......必須有另一種方式

如果您的文件中已經有 python 代碼,那就更好了

stage('build') {
steps {
    sh 'python abc.py'
}

只需確保在 jenkins 實例上安裝了 python 即可。 使用which python檢查您可能需要相對路徑

這里的問題是您調用 shell 步驟方法在 shell 解釋器中執行命令,而您想要執行 Python 代碼。 To enable this within the shell interpreter, you need to instruct the Python interpreter to execute Python code within the shell interpreter:

steps {
  sh(label: 'Execute Python Code', script: 'python -c "import boto3"')
}

這將實現所需的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM