如何为Jenkins设置Python目录结构



我有一个我正在从事的python项目,并且正在尝试使用Pytest和Jenkins实施测试。

我的目录结构就是这样:

project/
  src/
    __init__.py
    hello.py
    input.py
    person.py
  test/
    test_hello.py

当我从项目目录运行pytest时,它可以正常工作。但是当我使用詹金斯时,我会不断遇到以下错误:

[-1_10-finish-basic-ci-setup-IIB3G6YENVYIQDST5MPMDBNVOZLYD6VSLP5ZCT6VUVQSNZJKGYEA] Running shell script
+ python src/hello.py true
Traceback (most recent call last):
  File "src/hello.py", line 1, in <module>
    import src.person as person
ImportError: No module named 'src'

我在Docker容器中运行Jenkins,并用另一个Docker容器来测试我的项目。任何人都可以向我提示我如何让它识别用于运行测试的SRC目录?

我不确定我是否正确识别了您的问题(我希望您已经搜索了此错误(,但是当我尝试运行Python时,我遇到了非常相似的例外带有cron的脚本。

我的解决方法是在文件的开始时添加它。因此,当您进行python main.py 时,第一个事情正在运行此操作。sys.path...之后,您导入其他模块。它基本上将工作目录附加到PythonPath,因此Python从哪里运行它。有一些其他解决方案。这很丑陋,但是非常便携,您只需要复印。

import sys, os
def get_abs_dir_for_module(*args):
    return os.path.join(os.path.dirname(os.path.realpath(__file__)), *args)
repo_dir = get_abs_dir_for_module("..", "..")
sys.path.append(repo_dir)

您需要将一定数量的".."传递给此功能。玩耍,让我知道它是否有效。

最新更新