How to Import Multiple Python Modules from Other Directories

家住魔仙堡 提交于 2019-12-24 06:13:27

问题


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

MAIN QUES: How to Import Multiple Python Modules from Other Directories

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. email_modules
  3. gen_modules
  4. mongo_modules

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

What I tried that did not work:

import sys
sys.path.insert(0,'/home/myname/folder_name/email_modules')
sys.path.insert(0,'/home/myname/folder_name/gen_modules')
  • I tried sys.path.append as well.
  • I added to my PYTHONPATH on my local comp (MAC OS) and everything works dandy. However, when I change the PYTHONPATH on my AWS EC2 and attempt to run script_to_run.py, it cannot find email_modules nor 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!


回答1:


__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:



来源:https://stackoverflow.com/questions/43059505/how-to-import-multiple-python-modules-from-other-directories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!