4

I have a PyCharm project organized as follows:

---project folder
-----------utilities
-----------------file.py
-----------------file2.py
-----------work
-----------------main.py

in main.py I'm using some functions from the utilities package as follows:

from utilities.file import function, another_function

in PyCharm I can run it and it works.

When I run it on the terminal I hit

Traceback (most recent call last):
  File "work\main.py", line 13, in <module>
    from utilities.file import function
ModuleNotFoundError: No module named 'utilities'

Someone knows why and how to fix it?

3
  • utilities is not in the same folder as main.py Commented Aug 30, 2019 at 7:03
  • 1
    Either put your project folder into your python path or use a try-except clause for your imports. Commented Aug 30, 2019 at 7:03
  • create an empty file called __init__.py in folder utilities and try again see if it works Commented Aug 30, 2019 at 7:06

3 Answers 3

2

When using the terminal, The Python interpreter needs to know to path to your imported module.

Try this

import sys
sys.path.append('my/path/to/myModule/dir')
import myModule

However, a better approach would be setting PYTHONPATH to your project directory like this

set PYTHONPATH=my/path/to/project
Sign up to request clarification or add additional context in comments.

Comments

1

Use from ..utilities.file import function, another_function instead

Explanation: double dots will go up by one directory, and then you will access utilities folder, and then you will import file

Also, create an empty file named __init__.py as recommended by my colleague. Please notice the double underscore.

1 Comment

ValueError: attempted relative import beyond top-level package I get this
0
import sys
import os
mydir = os.getcwd() # directory that your python file
sys.path.append(mydir)
import myModule

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.