Mike
Mike

Reputation: 778

How do I resolve sys.path differences in Python and IronPython

I am running into pathing issues with some scripts that I wrote to test parsers I've written. It would appear that Python (27 and 3) both do not act like IronPython when it comes to using the current working directory as part of sys.path. As a result my inner package pathings do not work.

This is my package layout.

MyPackage
  __init__.py
  _test
      __init__.py
      common.py
  parsers
     __init__.py
     _test
          my_test.py

I am attempting to call the scripts from within the MyPackage directory.

Command Line Statements:

python ./parsers/_test/my_test.py

ipy ./parsers/_test/my_test.py

The import statement located in my my_test.py file is.

from _test.common import TestClass

In the python scenario I get ONLY the MyPackage/parsers/_test directory appended to sys.path so as a result MyPackage cannot be found. In the IronPython scenario both the MyPackage/parsers/_test directory AND MyPackage/ is in sys.path. I could get the same bad reference if I called the test from within the _test directory (it would have no idea about MyPackage). Even if i consolidated the test files into the _test directory I would still have this pathing issue.

I should note, that I just tested and if i did something like

import sys
import os
sys.path.append(os.getcwd())

It will load correctly. But I would have to do this for every single file.

Is there anyway to fix this kind of pathing issue without doing the following.

A. Appending a relative pathing for sys.path in every file.

B. Appending PATH to include MyPackage (I do not want my package as part of the python "global" system pathing)

Thanks alot for any tips!

Upvotes: 1

Views: 1338

Answers (1)

synthesizerpatel
synthesizerpatel

Reputation: 28036

Two options spring to mind:

  • Use the environment variable PYTHONPATH and include .

  • Add it to your sys.path at the beginning of your program

import sys.path
sys.path.append('.')
  • If you need to import a relative path dynamically you can always do something like
import somemodule
import sys
dirname = os.path.dirname(os.path.abspath(somemodule.__file__))
sys.path.append(dirname)

Upvotes: 1

Related Questions