Import python package from local directory into interpreter

前端 未结 9 1838
野的像风
野的像风 2020-11-29 02:54

I\'m developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type

相关标签:
9条回答
  • 2020-11-29 03:37

    A bit late to the party, but this is what worked for me:

    >>> import sys
    >>> sys.path.insert(0, '')
    

    Apparently, if there is an empty string, Python knows that it should look in the current directory. I did not have the empty string in sys.path, which caused this error.

    0 讨论(0)
  • 2020-11-29 03:40

    If you want to run an unmodified python script so it imports libraries from a specific local directory you can set the PYTHONPATH environment variable - e.g. in bash:

    export PYTHONPATH=/home/user/my_libs
    python myscript.py
    

    If you just want it to import from the current working directory use the . notation:

    export PYTHONPATH=.
    python myscript.py
    
    0 讨论(0)
  • 2020-11-29 03:40

    Using sys.path should include current directory already.

    Try:

    import .
    

    or:

    from . import sth
    

    however it may be not a good practice, so why not just use:

    import mypackage
    
    0 讨论(0)
  • 2020-11-29 03:40

    I used pathlib to add my module directory to my system path as I wanted to avoid installing the module as a package and @maninthecomputer response didn't work for me

    import sys
    from pathlib import Path
    
    cwd = str(Path(__file__).parent)
    sys.path.insert(0, cwd)
    from my_module import my_function
    
    0 讨论(0)
  • 2020-11-29 03:50

    See the documentation for sys.path:

    http://docs.python.org/library/sys.html#sys.path

    To quote:

    If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.

    So, there's no need to monkey with sys.path if you're starting the python interpreter from the directory containing your module.

    Also, to import your package, just do:

    import mypackage
    

    Since the directory containing the package is already in sys.path, it should work fine.

    0 讨论(0)
  • 2020-11-29 03:51

    Keep it simple:

     try:
         from . import mymodule     # "myapp" case
     except:
         import mymodule            # "__main__" case
    
    0 讨论(0)
提交回复
热议问题