Python import from parent directory

前端 未结 5 1212
渐次进展
渐次进展 2020-12-08 05:02

I have the following:

         ModuleFolder
              |
              |-->. ModuleFile.py .
              |
              \'-->. TestsFolder .
             


        
相关标签:
5条回答
  • 2020-12-08 05:36

    Make your test folder a module (by adding __init__.py).
    Then you can use run python -m tests.test_name or use the following Makefile in your project home:

    TEST_FILES = $(wildcard tests/test_*.py)
    TESTS = $(subst .py,,$(subst /,.,$(TEST_FILES)))
    all.PHONY: test
    test:
        @- $(foreach TEST,$(TESTS), \
            echo === Running test: $(TEST); \
            python -m $(TEST); \
            )
    
    0 讨论(0)
  • 2020-12-08 05:48

    You can also make symlink of the module path which you want to import and then use that symlink to import. Create a symlink in the python dist-packages.

    To create a symlink:

    ln -s "/path/to/ModuleFolder" "/path/to/python/dist/packages/module_symlink_name"

    To import module in the script:

    from module_symlink_name import ModuleFile
    

    No need to export python path or modifying sys path.

    0 讨论(0)
  • 2020-12-08 05:50

    Don't run the test from the tests folder. Run it from the root of your project, which is the module folder. You should very rarely need to muck with either sys.path or PYTHONPATH, and when you do, you're either causing bugs for other libraries down the road or making life harder on your users.

    python -m TestsFolder.UnitTest1
    

    If you use a test runner like py.test, you can just run py.test from the root of your checkout and it'll find the tests for you. (Assuming you name your tests something more like test_unit1.py. Your current naming scheme is a little unorthodox. ;))

    0 讨论(0)
  • 2020-12-08 05:58

    It's better to insert your relative path at the begening of sys.pathlike this:

    import sys
    sys.path.insert(0, '../')
    
    0 讨论(0)
  • 2020-12-08 05:58

    My suggestion is:

    Don't try to be clever, do what you're supposed to do. I.e. make sure that your modules and packages are somewhere in your Python path.

    The simplest way is to set the environment variable PYTHONPATH in the shell that you use to execute your scripts:

    $ export PYTHONPATH=/the/directory/where/your/modules/and/packages/are
    $ cd /the/directory/where/your/unit/tests/are
    $ python test1.py
    
    0 讨论(0)
提交回复
热议问题