1

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!

4

1 回答 1

1

两个选项浮现在脑海:

  • 使用环境变量 PYTHONPATH 并包含 .

  • 在程序开始时将其添加到您的 sys.path

import sys.path
sys.path.append('.')
  • 如果您需要动态导入相对路径,您可以随时执行类似的操作
import somemodule
import sys
dirname = os.path.dirname(os.path.abspath(somemodule.__file__))
sys.path.append(dirname)
于 2013-07-31T16:51:26.687 回答