如何从其他目录导入多个Python模块 [英] How to Import Multiple Python Modules from Other Directories

查看:707
本文介绍了如何从其他目录导入多个Python模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是Python新手.非常感谢python结构的所有帮助!

Python newbie here. Any and all help on python structure would be much appreciated!

主要问题:如何从其他目录导入多个Python模块

我已经重新组装了一个项目的存储库,以便根据任务的类型将特定任务的模块放在单个文件夹中,而不仅仅是一个大文件夹.因为我的模块都在一个文件夹中,所以我过去常常能够以这种方式轻松导入:

I've reassembled the repository for a project so that modules for specific tasks are within individual folders according to type of task instead of just one huge folder. Because my modules were all in one folder, I used to be able to import easily in this fashion:

import sys
sys.path.insert(0,'/home/myname/folder_name/all_modules')

现在,我有四个模块文件夹.

Now, I have four module folders.

  1. aws_boto_modules
  2. 电子邮件模块
  3. gen_modules
  4. mongo_modules

我想将其中两个模块导入 script_to_run.py .

I want to import two of these modules into script_to_run.py.

我尝试过的不起作用:

import sys
sys.path.insert(0,'/home/myname/folder_name/email_modules')
sys.path.insert(0,'/home/myname/folder_name/gen_modules')

  • 我也尝试了sys.path.append.
  • 我在本地计算机(MAC OS)上添加了我的PYTHONPATH,一切正常.但是,当我在AWS EC2上更改PYTHONPATH并尝试运行script_to_run.py时,它找不到email_modules或gen_modules.
  • 在过去的三个小时中,我读了很多书,但对于如何进行仍然很困惑.任何指导,包括我可能还没有遇到过的有用链接,将不胜感激.谢谢!

    I've read a lot in the last three hours, but am still very confused about how to proceed. Any guidance, including useful links that I may not have encountered already, would be greatly appreciated. Thanks!

    推荐答案

    __init__.py文件是使Python将目录视为包含包的必需文件.在下图中,我们正在从second_folder导入customer_info模块:

    __init__.py files are required to make Python treat the directories as containing packages. In the image below we are importing customer_info module from second_folder:

    这篇关于如何从其他目录导入多个Python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆