Skip to content Skip to sidebar Skip to footer

Reuse Module With Different Scripts (code Organization)

I have a utils package which provides functions for my (crontab) Python scripts. The scripts are organized in different directories on the same path: Eg.: scripts/client1/process-c

Solution 1:

The Q&D solution would be to add the path to the "scripts" directory to your sys.path before you import utils:

# process-client-XXX.py
import os, sys
root = os.path.dirname(os.path.dirname(os.path.abspath(__file)))
if root notin sys.path:
    sys.path.insert(0, root)

from utils import foo

# your code here

This is really ugly but well it should work as long as your directory layout doesn't change.

The clean solution would be to properly package utils so you can deploy it with pip or something similar... A bit more involved at first but much easier to maintain in the long run.

Post a Comment for "Reuse Module With Different Scripts (code Organization)"