简体   繁体   English

如何将 python 模块中的所有文件放置到同一个顶级命名空间?

[英]How to place all files in python module to the same top level namespace?

I have example python project with multiple files:我有包含多个文件的示例 python 项目:

src/common.py:源代码/common.py:

def toint(x):
    return int(x)

src/foo1.py:源代码/foo1.py:

import common

def add(a,b):
    return common.toint(a) + common.toint(b)

src/foo2.py:源代码/foo2.py:

import common

def sub(a,b):
    return common.toint(a)-common.toint(b)

setup.py:安装程序.py:

from setuptools import setup

setup (name = 'test_py_project',
       version = '1.0',
       author='Vladislav Tsendrovskii',
       description = 'test python modules',
       package_dir = {'': 'src'}
       )

Now I want to install this project.现在我想安装这个项目。 I run python3 setup.py install --user and it installs.我运行python3 setup.py install --user并安装。

But it installs not in a way that I want.但它的安装方式不是我想要的。

When I try to use it, I have problems.当我尝试使用它时,我遇到了问题。

I can not do import test_py_project.foo1我不能import test_py_project.foo1

But I can do import foo1但我可以做import foo1

How should I modify my project, to place all stuff inside test_py_project namespace?我应该如何修改我的项目,以将所有内容放入test_py_project命名空间?

I have tried to google for solution.我试图用谷歌搜索解决方案。 But I've failed(但是我失败了(

Reference the python docs https://docs.python.org/2/tutorial/modules.html#intra-package-references for creating modules and project directory format.参考 python 文档https://docs.python.org/2/tutorial/modules.html#intra-package-references创建模块和项目目录格式。 Eg Modulename/ModuleFiles.py and existence of a __init__.py and __main__.py files.例如 Modulename/ModuleFiles.py 以及__init__.py__main__.py文件的存在。 From __init__ you can import * or use relative/absolute imports.__init__您可以import *或使用相对/绝对导入。

But I can do import foo1但我可以做 import foo1

As it seems, your Python can already find stuff inside the src folder.看起来,您的 Python 已经可以在src文件夹中找到内容。

If you want to make test_py_project.foo1 work, create the necessary directory under src and move foo1.py there, so that you'll have src/test_py_project/foo1.py .如果你想让test_py_project.foo1工作,在src下创建必要的目录并将foo1.py那里,这样你就会有src/test_py_project/foo1.py

Then the import import test_py_project.foo1 should work.然后 import import test_py_project.foo1应该可以工作。

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

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