How to tell Jenkins to use a particular virtualenv python - python

I have already created a virtualenv for running my python script.
Now when I integrate this python scrip with Jenkins, I have found at the time execution Jenkins is using wrong python environment.
How I can ensure Jenkins is using the correct virtualenv?
As an example, for my case I want to use virtualenv test. How I can use this pre-prepared virtualenv to run my python script.
source test/bin/activate

You should install one of python plugins. I've used ShiningPanda. Then you'll be able to create separate virtual environment configurations in Manage Jenkins > Configure System > Python > Python installation.
In job configuration there will be Python Builder step, where you can select python environment.
Just make sure you're not starting Jenkins service from within existing python virtual environment.

First, you should avoid using ShiningPanda because is broken. It will fail if you try to run jobs in parallel and is also not compatible with Jenkins2 pipelines.
When builds are run in parallel (concurrent) Jenkins will append #2,#3... to the workspace directory so two executions will not share the same folder. Jenkins does clone the original worksspace so do not be surprised if it will contain a virtualenv you created in a previous build.
You need to take care of the virtualenv creation yourself but you have to be very careful about how you use it:
workspaces folder may not be cleanup and its location could change from one build to another
virtualenvs are knows to get broken when they are moved, and jenkins moves them.
creating files outside workspace is a really bad CI practice, avoid the temptation to use /tmp
So your only safe option is to create an unique virtual environment folder for each build inside the workspace. You can easily do this by using the $JOB_NUMBER environment variable.
This will be different even if you have jobs running in parallel. Also this will not repeat.
Downsides:
speed: virtualenvs are not reused between builds so they are fully recreated. If you use --site-packages you may speedup the creation considerably (if the heavy packets are already installed on the system)
space: if the workspace is not cleaned regularly, the number of virtualenvs will grow. Workaround: have a job that cleans workspaces every week or every two weeks. This is also a good practice for spotting other errors. Some people choose to clean workspace for each execution.
Shell snippet
#/bin/bash
set -euox pipefail
# Get an unique venv folder to using *inside* workspace
VENV=".venv-$BUILD_NUMBER"
# Initialize new venv
virtualenv "$VENV"
# Update pip
PS1="${PS1:-}" source "$VENV/bin/activate"
# <YOUR CODE HERE>
The first line is implementing bash string mode, more details at http://redsymbol.net/articles/unofficial-bash-strict-mode/

You can use Pyenv Pipeline Plugin. The usage is very easy, just add
stage('my_stage'){
steps{
script{
withPythonEnv('path_to_venv/bin'){
sh("python foo.py")
...
You can add pip install whatever in your steps to update any virtual environment you are using.
By default it will look for the virtual environment in the jenkins workspace and if it does not find it, it will create a new one.

Related

Exporting environment (yml) file during conda build

TLDR
See question at the bottom
Background/Intro
I am still quite new to the world of Python and Conda and am trying to setup a CI pipeline for a bespoke requirement.
My understanding with the 'conda build' command is that internally it creates a temporary conda environment and uses this for evaluation of this build process. I am aware of this because it a version that I used last year that we upgraded, we had to change the meta.yaml file to have a new source folder entry for unit tests that it would then run against in this special folder.
More context (sorry for waffle)
Given the above, what I am looking to do is to extract the environment file once its run its operations e.g. dependency checks, unit tests etc..
If I were trying to extract (export) the env file for an environment, I would of course to the usual:
conda export > [some_path]/env.yml
The reason behind trying to get the environment during the 'conda build' process is for two reasons:
1.) Typically the developers tend to only list in the meta.yaml file the top level dependencies not all dependencies, and I need this list for a bespoke process down the line.
2.) (less vital but still good)
I can guarantee that the version built by the 'conda build' process (and all its dependencies) are valid.
Sometimes there is the issue of the build running and then a lower level dependency version changing between the time of the build and the release.
I do appreciate that the devs should be fixing all versions in the recipe but there are still sometimes some problems.
Question
Therefore, is it possible to retrieve/extract/export the environment file from the 'conda build' command-process?? Perhaps there is some flag? Or something I can script to run pre-build finishing?
Possible solution I thought of
Let process run, then script a step in my CI to create the environment and export the env file - I just don't want to add more time to the CI process though

PyCharm Virtual Environment Concept - Understanding [duplicate]

I am fairly new to creating Python applications. I have fooling around with some small tutorials and applications using PyCharm and have always created a new project using the Virtualenv environment, ending up with a "venv" folder under my project folder. I have not had any problems with this, but then again I have not done any large projects.
However, I have been wanting to learn Flask want to try to create a new Flask project the proper way. I see in many tutorials that people are creating (and activating) the virtual environment from the (Windows/Linux) Command Line instead even though they are using PyCharm and I was just wondering what the difference is?
When I work on a project in PyCharm, created with Virtualenv, I do not activate the venv before working on it. Is this wrong or is this something that is handled by PyCharm? What if the venv is created from a Command Line? Is it still handled (activated) by PyCharm if working on the project there. And what about the folder structure? Is this affected by how the virtual environment is created? Is there somewhere I can find some "best practices" for the setup / folder structure when creating Flask project within a Virtual Environment?
PyCharm activates the VirtualEnv for you if it is configured to use one and told where it is (more specifically, where the respective Python binary in the VirtualEnv is).
There's no real difference between manually created VirtualEnvs and ones created by PyCharm. (Apart from the framework you select to create one in case this is different from what PyCharm is configured with.)
If you want, you can just create one manually and then point PyCharm to it. Either during creation of the project or later using the Settings dialog (see Settings -> Project -> Project Interpreter). It will then treat it no differently and also activate it for you when working inside the IDE.
A virtual environment is pretty much just a folder which stores installed Python packages and isolates them from the rest of your system. This is so you can work on different projects which may all have competing requirements for external packages, without getting into conflicts. "Activating" a virtual environment just sets certain environment variables in your current shell so it'll use packages from this environment. "Activating" an environment never has any impact beyond your current shell. So activating an environment on the command line won't do anything to PyCharm.
PyCharm integrates a Python interpreter to give you lots of extra functionality. You tell PyCharm which interpreter you want to use for your project and it'll figure out what packages it has available, what version it is, and automatically set everything up properly for running your code from PyCharm etc. You can tell PyCharm to use your system's Python interpreter or an existing virtual environment or even use it to create a new environment. You don't need to do anything special beyond just selecting the right interpreter/environment in the project settings.
There's no reason to activate the environment from the command line if you're not going to use it from the command line. Of course, using Flask and running its server from the command line and keeping it running in the background may be useful. Not sure if PyCharm would give you an easy or integrated option to have persistent processes run in the background. You could still select the same virtual environment in PyCharm and use it to run your tests in it directly from PyCharm, use its debugger etc.
I prefer to keep the venv out of the project folder and store all venvs in ~/.virtualenvs/ or such. It declutters the project folder and prevents accidentally checking those files into the version control system.
I was just wondering what the difference is?
There's many tools for creating and using virtual environments and there's no difference between them, the only difference between them is their commands syntax (or the way it interact with users, e.g. for Pycharm you set some settings via GUI).
Is this wrong or is this something that is handled by PyCharm?
There's nothing wrong with it. As long as you have a venv (or .venv) directory in the root of your project and it is executable for any user, Pycharm will use it and it activates this virtual environment for you (without telling you). If Pycharm was not able to do that, (because of trouble in finding venv or activating/executing it!) then it will show you messages to fix its problems and it can't run your project till you fix them.
It's better to create your virtual environment in .venv directory right into the root directory of your project. (It's kind of conventional)
See python virtual environments and configuring pycharm virtualenv as well.

Django crontab is not working in background

I am using django-crontab to run some cron jobs as part of my project. I have a virtual environment setup for this particular project.
So after activating the environment, I add the jobs by using the following command :
python manage.py crontab add
I see that my jobs are succcessfully added to the OS crontab, however when I see the logs, I found that it was not able to find certain modules(read all) that were installed in virtual environment.
However if I run those crons manually by passing the hash to the run command it runs successfully.
On further inspection I found when the crons are added to the crontab, the python binaries are pointed to the global(system level binaries) instead of the virtual level binaries.
The only solution I can think of is to run pip install at a system level but that will mess up the sanbox environment I intend to create.
Any ideas?
django-crontab is not maintained anymore. Last changes to this library happened over 2 years ago. I really advise stopping using it.
For fixing that bug, you can use either CRONTAB_PYTHON_EXECUTABLE setting to point to python executable from your env, or CRONTAB_COMMAND_PREFIX to add something that will just activate this virtualenv before running python.

Python venv programmatically

We are trying to add venv functionality to our python project ie when one runs project an venv is created in project path and project runs on that venv.
For this to work we used vurtualenv's create environment method and activatethis.py the method creates venv ,
However when project runs it still uses host machine packages. Instead of using venv ones
Am I doing anything wrong..is it possible to do this??
PS: I have tried both site-packages true and false in create environment method .. however to no help
Adding more info:
Commands used are
venv_dir = os.path.join("path to project")
virtualenv.create_environment(venv_dir)
execfile(os.path.join(venv_dir, "bin", "activate_this.py"))
Also updated path environment variable to include bin of venv
After this I expect my code (after this) to run in virtual environment.
I am not using any ide and expect the code to create venv at runtime
Using python 2.7
Is there any other way to run project in virtual environment at run time without any ide in Ubuntu server environment.
You haven't provided enough information for us to come up with a solution to your exact problem, although I will do my best to help you out.
You should not be creating a venv every time you run the project, which it sounds like you are doing. This is essentially creating a new interpreter every single time you run your project. If you're using a decent IDE, such as PyCharm, you should be able to set this up properly through the project settings.
There are plenty of tutorials out there regarding setting up venv and virtualenv on your computer, and given that we don't know much about your system, your best bet is doing some further research.
Essentially, you need to
Create a venv for the project (and a new one for each project you make from here on out, unless you want to use the machine's interpreter)
Set the project interpreter to the venv you just created. Place any external libraries within ...\venv\Lib\site-packages
Hope this helps.

Associating a python project with a virtual environment

been searching for this with no success, i don't know if i am missing something but i have a virtualenv already but how do i create a project to associate the virtualenv with, thanks
P.S. Am on windows
I could be wrong here, but I do not believe that a virtualenv is something that is by its very nature something that you associate with a project. When you use a virtualenv, you're basically saying, "I'm taking this Python interpreter, installing what I want on it, and setting it aside from the Python interpreter that the entire computer uses by default." Virtualenv does not have a concept of a Python "project"; it is just a custom version of a Python interpreter that you run code through. There are tools in IDEs like PyCharm that enable you to associate a project with a virtualenv, but those are another layer on top of the base software.
In order to use a virtualenv with a project, you will need to "activate" it every time you wish to use it. The documentation for activating a virtualenv on Windows is found here.
EDIT:
Saw that you had virtualenvwrapper tagged in your post, so I did a bit of hunting on that. It would appear that there is the mkproject command, which creates a project folder and then associates it with a virtualenv interpreter. Documentation on it can be found here.
Requirements:
Virtual Env
Pycharm
Go to Virtual env and type which python
Add remote project interpreter (File > Default Settings > Project Interpreter (cog) add remote)
You'll need to set up your file system so that PyCharm can also open the project.
NOTE:
do not turn off your virtual environment without saving your run configurations that will cause pycharm to see your run configurations as corrupt
There's a button on the top right that reads share enable this and your run configs will be saved to a .idea file and you'll have a lot less issues
If you already have your virtualenv installed you just need to start using it.
Create your projects virtual environment using virtualenv env_name on cmd. To associate a specific version of python with your environment use: virtualenv env_name -p pythonx.x;
Activate your environment by navigating into its Scripts folder and executing activate.
Your terminal now is using your virtual environment, that means every python package you install and the python version you run will be the ones you configured inside your env.
I like to create environments with the names similar to my projects, I always use one environment to each project, that helps keeping track of which packages my specific projects need to run.
If you haven't read much about venvs yet, try googling about requirements.txt along with pip freeze command those are pretty useful to keep track of your project's packages.
I like Pipenv: Python Dev Workflow for Humans to manage environments:
Pipenv is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. Windows is a first-class citizen, in our world.
It automatically creates and manages a virtualenv for your projects, as well as adds/removes packages from your Pipfile as you install/uninstall packages. It also generates the ever-important Pipfile.lock, which is used to produce deterministic builds.
Pipenv is primarily meant to provide users and developers of applications with an easy method to setup a working environment.

Categories

Resources