Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

how to run python2.6 module with absolute imports stand alone

26 views
Skip to first unread message

Gelonida N

unread,
Sep 7, 2012, 6:04:28 PM9/7/12
to pytho...@python.org
Hi,

many of my modules contain following section at the end


def main():
do_something()
if __name__ == '__main__':
main()

This allows me to run some basic example code
or some small test in a stand alone mode.


My new modules contain following line at the beginning:

from __future__ import absolute_import


I like this:
- It can reduce import name conflicts
- and second it allows 'relative' imports like
from .othermodule import funcname
from ..mod_one_level_higher import fdfsd


However If I try to run such a script from the command line it will now
complain with

ValueError: Attempted relative import in non-package

Any tricks to work around this ???

The only idea, that I have is to have a script, that would take my
modulename or path name as parameter, and try to import it and then call
the main function of the imported module.


Not very elegant, but probably functional.

Thanks in advance for any other suggestions / ideas.

Mark Lawrence

unread,
Sep 7, 2012, 8:13:02 PM9/7/12
to pytho...@python.org

Gelonida N

unread,
Sep 8, 2012, 10:03:56 PM9/8/12
to pytho...@python.org
It seems the safest bet seems to be to not use relative imports.

What I did in the end however is write a wrapper script, that takes
another script as parameter, converts it's path name to a module name,
imports it, adapts sys.path and calls main of the imported module.

Perhaps a little overkill, but most convenient, as the script can even
adapt sys.path prior to importing other files if required.





>
>


Jean-Michel Pichavant

unread,
Sep 10, 2012, 5:28:23 AM9/10/12
to Gelonida N, pytho...@python.org
Gelonida N wrote:
> On 09/08/2012 02:13 AM, Mark Lawrence wrote:
>> [snip]
>>>
>>
>> I hope this helps
>> http://stackoverflow.com/questions/3616952/how-to-properly-use-relative-or-absolute-imports-in-python-modules
>>
>
> It seems the safest bet seems to be to not use relative imports.
That's what I figured as well. I may have been misusing relative
imports, but I never found the solution for my problems. Absolute
imports just solved everything. I think this is the way to go for anyone
who does not want to spend too much brain on their import directives.

JM
0 new messages