James
James

Reputation: 386

Python can't find module when running in linux

When I go to the file path cd to the file path ~/repo/analysis_tools/fresh_sales/ and then run python3 apicall.py it runs fine but when I try and add it to cron using python3 ~/repo/analysis_tools/fresh_sales/apicall.py the python code returns the error: No module named 'utils'.

My current project structure:

Analysis Tools:
- utils:
   + builders.py
   + load_config.py
- fresh_sales:
   + apicall.py

The start of my code:

import sys
import os

sys.path.append('..')
sys.path.append(os.path.dirname(os.path.realpath("..")))
sys.path.insert(0, '')

from utils.load_config import load_config
import requests
import json
from pandas.io.json import json_normalize
from utils.builders import build_local_db_from_config
from datetime import datetime
from sys import exit

Upvotes: 0

Views: 62

Answers (1)

CodeSamurai777
CodeSamurai777

Reputation: 3355

Your path is never changed you should add the project root to the path:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

You could also try relative imports but this would be easier if you had something like main.py in the project root. Calling scripts higher in the directory tree is a potential sign of incorrect structure, but not always.

Upvotes: 1

Related Questions