Python imports from subfolders

我怕爱的太早我们不能终老 提交于 2019-12-21 03:42:23

问题


I am attempting to grade some python submissions that are in separate folders for each student. To do this, there is a function, say f() which I want to run. I understand that if my current path is the same as the one where the file is located, I can simply do

import filename
filename.f()

However, are there better ways? For instance, let's say the directory structure is as follows:

main.py
student/run_this.py

I know that if there is a "__init__.py" file in the student folder, I can just type

import student.run_this

However, without that file, it doesn't work.

Some similar questions I found were

  • Import module from subfolder
  • How to do relative imports in Python?
  • http://www.daniweb.com/software-development/python/threads/192000/import-from-a-subdirectory-of-a-directory-on-pythonpath

but none of these gave particularly satisfying answers.


回答1:


create an __init__.py module inside the folder student which should contain

from . import *

You can then call any modules from student folder to its parent folder modules as

import student.module.py

If you post any other errors you are facing, we can help further.



来源:https://stackoverflow.com/questions/15222913/python-imports-from-subfolders

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