如何修复jenkins中的python模块导入错误

时间:2016-08-27 02:16:35

标签: python django jenkins

我在Jenkins中有模块导入错误,尽管根据堆栈溢出的问题设置我的路径和python路径

我试过这个

Jenkins: putting my Python module on the PYTHONPATH

和这个

Python module import failure in Jenkins

此命令在我的本地计算机上运行,​​没有任何导入问题,但在Jenkins上失败

命令

#!/bin/bash

export PYTHONPATH=$WORKSPACE:$PYTHONPATH
export PATH=$WORKSPACE:$PATH
export DJANGO_SETTINGS_MODULE=myapp.settings.test

echo "Working directory: "
pwd

echo "path: "
echo $PATH

echo "Python path: "
echo $PYTHONPATH


/home/adminuser/.virtualenvs/myapp/bin/python myapp/manage.py jenkins --project-apps-tests  --enable-coverage --settings=myapp.settings.test

构建错误

Working directory: 
/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace
path: 
/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/:/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
Python path: 
/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/:/home/adminuser/.virtualenvs/myapp/bin:/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace:

-------- USING TEST SETTINGS ------

Traceback (most recent call last):
 ......
    File "/var/lib/jenkins/jobs/myapp_QA_TESTS/workspace/myapp/apps/accounts/models.py", line 18, in <module>
        from apps.registration.tokens.token import GenerateToken
    ImportError: No module named registration.tokens.token

我的文件结构

概述

myapp/
├── apps
│   ├── __init__.py
│   ├── accounts
│   ├── registration
├── myapp
│   ├── __init__.py
│   ├── celery.py
│   ├── settings
│   ├── urls.py
│   └── wsgi.py
├── manage.py

查看模块目录

myapp/apps/registration/tokens
├── __init__.py
└── token.py

myapp/apps/accounts/
├── __init__.py
├── models.py

我甚至尝试将workspace目录和virtualenv路径附加到PATH和PYTHONPATH,我甚至还将模块目录添加到PATH和PYTHONPATH

当我在服务器上运行命令时,我得到了同样的错误。这可能是因为我的virtualenv是由admin用户创建的,但现在Jenkins正在尝试使用它,但所有包都加载

如何解决此导入错误,我们非常感谢您提供帮助

1 个答案:

答案 0 :(得分:1)

所以终于想通了

您需要在测试期间创建虚拟环境,这是最终的命令

#!/bin/bash


export WORKSPACE=`pwd`

# Create/Activate virtualenv
virtualenv testenv -p /usr/bin/python3

source testenv/bin/activate

# Install requirements
pip install -r requirements/test.txt 


# Run them tests
python myapp/manage.py jenkins --project-apps-tests  --enable-coverage --settings=myapp.settings.test

希望这有助于像我一样陷入困境的人