我来自R的背景,我正在尝试使用Flask在Python中开发API。我的文件夹看起来像这样:
project
--server.py
--custom_functions
----func1.py
----func2.py
--more_custom_functions
----subfolder1
------func3.py
------func4.py
----subfolder2
------func5.py
------func6.py
我更喜欢根据用途将自定义功能组织到不同的子文件夹中,因此custom_functions可以是例如与清洁等相关的功能。理想情况下,当我使用Windows CMD(如果有帮助)启动server.py时
python server.py
在/ project目录中,我希望能够导入每个函数。函数看起来像
import numpy as np
def func1 (x) :
return(x + 1)
,仅此而已。
我的问题是:服务器初始化时(即在python server.py
上)如何全局导入每个模块(例如 numpy / pandas )这样,所有子功能都可以使用这些模块而无需调用在其中导入(即,在上面的示例中,我们可以删除import numpy as np
),然后导入所有功能func1
,{{1} },...,func2
?我不介意是否必须将它们称为func6
或custom_functions.func1
,例如,如有必要。
我尝试了许多操作,例如将more_custom_functions.subfolder1.func3
放在某些文件夹中,并将__init__.py
添加到此文件中(以及将其保留为空)。我也尝试过
__all__ = ["func1", "func2"]
及其类似形式,例如custom_functions import *,全部无效。
我遇到的一些错误涉及:
import sys, os
sys.path.append(os.getcwd() + '\\custom_functions')
import custom_functions
或
module 'custom_functions' has no attribute func1
。
在R中,我会沿name 'custom_functions' is not defined
的方式使用某些内容,然后在代码一开始就库/要求所有软件包,一切都很好。有一个简单的等效方法吗?还是我必须将每个函数移到一个文件中(例如 functions.py ),然后导入函数?
感谢您的帮助。
答案 0 :(得分:0)
似乎有一种中间解决方案或多或少适合我的需求,即使在使用Python时可能不是最佳实践。
import os
import glob
files_names = glob.glob(os.getcwd() + '\custom_functions\**\*.py')
for f in file_names : exec(open(f).read())
这使我可以使用自定义函数,而无需将其称为模块,即,我可以像
一样使用它们func1()
代替
custom_functions.func1()