繁体   English   中英

python导入根文件夹并使用所有子文件夹

[英]python import root folder and use all subfolders

具有以下目录结构

.
├── setup.py
└── yourpackage
    ├── __init__.py
    ├── some_module.py
    ├── other_module.py
    └── sub_package
        ├── __init__.py
        └── more_modules.py

是否有可能做到这一点:

>> import yourpackage as yp
>> yp.some_module.bar()
>> yp.sub_package.more_modules.foo()

some_module的内容在some_module

def bar(): print('bar')

more_modules的内容是more_modules

def foo(): print('foo')

我似乎无法让这个工作

编辑:我在第一种情况下会得到的错误是

Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: module 'yourpackage' has no attribute 'some_module'

在第二种情况下,它是一个类似的错误,但有more_modules

如果要使用内部模块而不显式导入它们,则必须在__init__.py文件中导入它们:

import some_module
import other_module
import sub_package

并在sub_package/__init__.py

import more_modules

请注意,这可能会使模块的第一次导入变慢。

其他选项是在代码中明确导入它们:

>> import yourpackage.some_module
>> import yourpackage.sub_package.more_modules
>> yourpackage.some_module.bar()
>> yourpackage.sub_package.more_modules.foo()

事实上进口非常棘手......

你可以这样做:

import yourpackage as yp
from yourpackage import some_module  #yp does not work

在ipython中调用:

In [8]: yp.some_module.bar()
bar

然后

import yourpackage.sub_package
from yourpackage.sub_package import more_modules

在ipython中调用:

In [20]: yp.sub_package.more_modules.foo()
foo

你必须导入顶级包然后子包......

这是一个有趣的链接: https//www.codementor.io/sheena/python-path-virtualenv-import-for-beginners-du107r3o1

这个也是:): https//docs.python.org/2/tutorial/modules.html

为了得到@ A.Joly和@slallum的答案:实际上,我发现他们的方法组合实际上是有效的。 我创造了这些:

pycharmprojects
   |_networkxy
       |_ main_run.py  ---- misleading name, it's just an ordinary file
       |_ more_module.py
       |_ __init__.py

__init__.py内容:

from . import main_run
from . import more_module

main_run.py内容:

def some_module():
    print('some module')

more_module.py内容:

def more_module():
    print('more module')

现在,在目录pycharmprojects ,在命令行中:

(C:\Users\Name\.conda\envs\my_root) C:\Users\Name\PycharmProjects>python
Python 3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import networkxy
>>> networkxy.main_run.some_module()
some module
>>> networkxy.more_module.more_module()
more module

注意:由于某些原因,我不能在__init__.py import main_run ,而是from . import * from . import *似乎有效。

暂无
暂无

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

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