在Travis ci上Python3模块导入失败

在Travis ci上Python3模块导入失败

问题描述:

我制作了一个Python 3脚本来测试我的项目. 脚本具有以下结构:

I have made a Python 3 script for testing a project of mine. The script has this structure:

main.py
myRequest.py
external/
  requests/
    __init__.py
    many files of the library...

当我运行python3 main.py时,将导入文件myRequest.py.在该文件中,执行import external.requests as reqs. 这对我有用,并且还会通过 Travis CI

When I run python3 main.py the file myRequest.py is imported. Inside that file, I do import external.requests as reqs. This works for me, and also passes on Travis CI

但是,当我将上述文件放在我的项目的文件夹test中时, Travis CI作业找不到模块:

However, when I put the above files in the folder test of my project, the Travis CI job cannot find the module:

ImportError: No module named external.requests.

当我尝试在在线IDE(c9,Ubuntu 14.04 ,Python 3.4.0 )中运行脚本时,便能够导入该脚本. 在c9处,我尝试执行from .external import requests as reqs,但它会引发一个:

When I tried running the script in an online IDE (c9, Ubuntu 14.04, Python 3.4.0) it was able to import it. At c9, I have tried doing from .external import requests as reqs but it raises a :

SystemError: Parent module '' not loaded, cannot perform relative import.

添加一个空的__init__.py文件或运行python3 -m main.py没有任何作用.

Adding an empty __init__.py file or running python3 -m main.py did nothing.

我应该怎么做才能在Travis CI上成功导入?

What should I do so that the import is successful at Travis CI?

我遇到了相同的问题,因此我在此处发布以希望对他人有所帮助:

I encountered the same issue, so I am posting here in hope to help somebody:

对我来说,快速解决方案是在.travis.yml中添加此行导出PYTHONPATH=$PYTHONPATH:$(pwd):

The quick fix for me was to add this line export PYTHONPATH=$PYTHONPATH:$(pwd) in the .travis.yml:

before_install:
  - "pip install -U pip"
  - "export PYTHONPATH=$PYTHONPATH:$(pwd)"

具有setup.py

具有setup.py,这应该是默认选项,因为它是最优雅的. 这样一来,您就可以解决相对的导入问题,请尝试配置如下:

Have a setup.py

Having a setup.py which should be the default option as it is the most elegant. With that you would resolve your relative import issue, try one configured like:

from setuptools import setup, find_packages

setup(name='MyPythonProject',
      version='0.0.1',
      description='What it does',
      author='',
      author_email='',
      url='',
      packages=find_packages(),
     )

然后在.travis.yml

before_install:
  - "pip install -U pip"
  - "python setup.py install