简体   繁体   English

如何从python中bin文件夹中的脚本导入包/模块

[英]How to import your package/modules from a script in bin folder in python

When organising python project, this structure seems to be a standard way of doing it:在组织python项目时,这种结构似乎是一种标准的做法:

myproject\
    bin\
        myscript
    mypackage\
        __init__.py
        core.py
    tests\
        __init__.py
        mypackage_tests.py
setup.py

My question is, how do I import my core.py so I can use it in myscript ?我的问题是,如何导入core.py以便在myscript使用它?

both __init__.py files are empty. __init__.py文件都是空的。

Content of myscript :我的myscript内容:

#!/usr/bin/env python
from mypackage import core
if __name__ == '__main__':
    core.main()

Content of core.py core.py内容

def main():
    print 'hello'

When I run myscript from inside myproject directory, I get the following error:当我从myproject目录中运行myscript ,出现以下错误:

Traceback (most recent call last):
  File "bin/myscript", line 2, in <module>
    from mypackage import core
ImportError: No module named mypackage

What am I missing?我错过了什么?

Usually, setup.py should install the package in a place where the Python interpreter can find it, so after installation import mypackage will work.通常, setup.py应该将包安装在 Python 解释器可以找到的地方,这样安装后import mypackage就可以工作了。 To facilitate running the scripts in bin right from the development tree, I'd usually simply add a simlink to ../mypackage/ to the bin directory.为了方便直接从开发树中运行bin的脚本,我通常只需将 ../mypackage/ 的../mypackage/添加到bin目录。 Of course, this requires a filesystem supporting symlinks…当然,这需要一个支持符号链接的文件系统......

I'm not sure if there is a "best choice", but the following is my normal practice:我不确定是否有“最佳选择”,但以下是我的常规做法:

  1. Put whatever script I wanna run in /bin把我想在 /bin 中运行的任何脚本

  2. do "python -m bin.script" in the dir myproject在目录 myproject 中执行“python -m bin.script”

  3. When importing in script.py, consider the dir in which script.py is sitting as root.在 script.py 中导入时,请考虑 script.py 作为 root 所在的目录。 So所以

    from ..mypackage import core

If the system supports symlink, it's a better choice.如果系统支持符号链接,则是更好的选择。

I usually add my bin path into $PYTHONPATH, that will enable python to look for asked module in bin directory too.我通常将我的 bin 路径添加到 $PYTHONPATH 中,这将使 python 也可以在 bin 目录中查找请求的模块。

export PYTHONPATH=/home/username/bin:$PYTHONPATH
$ python
import module_from_bin

I solved the issue following setuptools specifications .我按照setuptools 规范解决了这个问题。

In setup.py you can specify the modules as an argument for the function setup() :在 setup.py 中,您可以将模块指定as an argument for the function setup()

packages = find_packages() 

This finds all modules.这将找到所有模块。

ps you have to import this function: from setuptools import setup, find_packages ps 你必须导入这个函数: from setuptools import setup, find_packages

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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