6

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...

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

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.

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.

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

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

Sylhare
  • 5,907
  • 8
  • 64
  • 80
anestv
  • 543
  • 6
  • 28
  • I found this article useful for getting a Python project set up with tests and TravisCI integration: http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/ – jonrsharpe Jan 23 '15 at 11:37
  • Possible duplicate of [How to add my module to travis-ci pythonpath](https://stackoverflow.com/questions/25756134/how-to-add-my-module-to-travis-ci-pythonpath) – Sylhare Jan 13 '18 at 20:32

1 Answers1

5

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

Quick Fix

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)"

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(),
     )

And then add this line in .travis.yml

before_install:
  - "pip install -U pip"
  - "python setup.py install
Sylhare
  • 5,907
  • 8
  • 64
  • 80
  • I have tried all of the above in my project and none of them seems to be working for me. Could you please take a look and help me out: https://stackoverflow.com/questions/57661399/using-my-package-throws-modulenotfounderror-no-module-named-my-package-in-tra?noredirect=1#comment101771980_57661399 – ahajib Aug 26 '19 at 17:30