2

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
  • Hey @Thomas , I am facing the same issue with some difference.. I am trying to run python code after setting virtual env but unable to do so.. Were you able to crack it? Commented Sep 22, 2022 at 17:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting. How would you add a whole script to that(60 lines)?
@ThomasLord You would probably want to assign that as a value to a string variable and interpolate it within the argument to the method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.