Running A Python Script In Jenkins Pipeline Shell

Viewed 570

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.

When I run the above without the import boto3 the job runs fine.

I also checked out the snippet generator on the Jenkins severs and read this:

"An interpreter selector may be used, for example: #!/usr/bin/perl"

UPDATE

The following works:

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

The only issue is having to to the \n and + after every line seems a bit too much...there has to be another way

1 Answers

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.

Related