简体   繁体   中英

Correct Structure for Python Project Containing a Package and Scripts?

I'm currently working on a project that has a custom designed Python package, along with a bunch of scripts that use that package. What's the best way of structuring this such that I can run the scripts from anywhere without getting package not found errors? I'd like to build tests for the package as well, so I was thinking of having something like:

project/
|--src
|   |--some_package
|--test
|--scripts

But then I'm not sure how to have the scripts import my custom package such that I can run/reference the scripts from anywhere without "package can't be found" errors. Any help is appreciated!

Hitch Hikers包装指南中有相关文档

One way to install and run these scripts on other machines is to package them up using distutils. See http://docs.python.org/library/distutils.html .

Otherwise, if you put an __init__.py file into a directory on your tree, Python will see the directory as a package and will allow you to import modules from it. For example, if you have this structure:

project/
|some_script.py
    |--some_package 
        |__init__.py
        |some_module.py
|--test
    |__init__.py
|--scripts
    |__init__.py

in some_script.py you could do this:

import some_package.some_module

That will allow you to do imports from subdirectories without an elaborate installation to put your modules somewhere in the Python path. The same thing can be done for the 'test' and 'scripts' directories. (You probably already know this, but __init__.py can just be an empty file.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM