2

first post to SO, so if I'm missing some details, please forgive me.

Is there a way to use relative paths from another subfolder without resorting to modifying sys.path via os? Eventually this will be run from a cgi webserver so I'd rather stay away from any -m arguments to python.exe.

I'm using Python 2.7.3 and have a file/directory structure of the following :

|   myprog.py
|
+---functions
|       myfunctions.py
|       __init__.py
|
\---subfolder
        mysub.py

In the root, I have a single .py file, called myprog.py :

#file .\myprog.py

from functions import *
hello("Hi from Main")

In the functions folder I have two files, init.py, myfunctions.py :

#The File: functions\__init__.py :
from myfunctions import *

#The File: functions\myfunctions.py :
def hello(sometext):
   print sometext

And finally, in the subfolder, I have :

#The File: subfolder\mysub.py :

from ..functions import *
hello("Hi From mysubprogram")

The myprog.py executes fine (when running python.exe myprog.py from the parent folder), printing "Hi From Main", however, the mysub.py (when executed from the subfolder) keeps putting the error: ValueError: Attempted relative import in non-package

I have tried varying combinations in mysub.py such as from ..functions.myfunctions import * yet none yields the desired result.

I have read a few relevant articles :
using __init__.py
How to import classes defined in __init__.py
http://docs.python.org/2/tutorial/modules.html#packages-in-multiple-directories

But just can't figure this out. Oh, and once I get this working, I would like to remove the import *'s wherever possible, however, I'd rather not have to put the full paths to the hello function each time it's called, so any advise there or on cleaning up the init.py (using all or in another manner) would be a bonus.

Thanks Blckknght EDIT, I also found the below : Relative imports for the billionth time

Which, if what I'm requesting isn't possible, perhaps I'm asking the wrong thing. If this is just outright bad practice, is the right way to accomplish my goal using sys.path or is there something else someone can recommend (like not calling functions from ../folders) ?

Community
  • 1
  • 1

1 Answers1

1

I think the issue has to do with how you are running the mysub.py script. Python doesn't tend to do well with scripts in packages, since the main script module is always named __main__ rather than its usual name.

I think you can fix this by running mysub with python -m subfolder.mysub, or by manipulating the __package__ variable in mysub.py (as described by PEP 366). It's not neat, unfortunately.

Blckknght
  • 100,903
  • 11
  • 120
  • 169