Home > Software design >  Running A Python Script In Jenkins Pipeline Shell
Running A Python Script In Jenkins Pipeline Shell

Time:12-18

I'm having an issue to where I can't seem to run a python script in a Jenkins Pipeline script.

If I create a Jenkins Freestyle job and execute a shell with:

#!/usr/bin/env python
import boto3

The import works and I can run the rest of my python code.

But if I create a Jenkins Pipeline and try to run the following:

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

I get import: command not found

Do I need to set the env some other way?

UPDATE

So I tried this:

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

And now I'm getting an indent error.

I've tried indenting it a millions ways with no luck.

CodePudding user response:

The issue here is your invocation of the shell step method executes commands in the shell interpreter, and you want to execute Python code instead. 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"')
}

and that will achieve the desired behavior.

CodePudding user response:

its better if you have your python code in a file already

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

} just make sure you have python installed on that jenkins instance. Use which python to check as you may need the relative path

  • Related