user3702643
user3702643

Reputation: 1495

Proper folder structure in python3

Python 3.7.4 (homebrew)

I am trying to run script.py. It works fine in PyCharm when I run it, but when I try to run it from the command line I get an error.

Project structure:

project
  /folder
    /subfolder1
      /subfolder2
        /script.py
  /tools
    /subfolder
      /tool.py

I get this error when I try to run it from command line

from tools.subfolder.tool import *
ModuleNotFoundError: No module named 'tools'

Upvotes: 0

Views: 139

Answers (1)

BOB
BOB

Reputation: 103

Using an editor like PyCharm will temporarily add the project root directory (in your case, directory project/) to the PYTHONPATH. This means that you have the possibility of importing modules by using a path relative to the project root. That's why from tools.subfolder.tool import * works in PyCharm. If you wanted to run it from the command line, you could add your root directory to PYTHONPATH. For example, if you're using bash or zsh, you can append your project root to PYTHONPATH by running export PYTHONPATH="$PYTHONPATH:/path/to/project/root/". You can also do that for just the current script by running:

import sys
sys.path.append('/path/to/project/root/')

You could also relatively specify the path to the project root. Say, your project root is in the directory holding the directory where your python script is located, you could do something like sys.path.append('..') instead.

Cheers.

Upvotes: 1

Related Questions