我的django项目中的相关文件夹就在这里。
-config(文件夹)
- 设置(文件夹)
---common.py
--- production.py
-core(文件夹)
- 管理(文件夹)
---命令(文件夹)
--- my_command.py
我有一个名为MYVAR的变量。如果我将它放在common.py中并将其导入到my_command.py中,就可以了。它可以正常工作。
from django.conf import settings
class Command(BaseCommand):
def handle(self, *args, **options):
test = settings.MYVAR
但是如果我将MYVAR放在production.py并运行相同的代码片段,它就无法找到变量。
这里发生了什么? common.py和production.py位于同一文件夹(设置)中。为什么不从production.py导入?
答案 0 :(得分:0)
请在此处查看我的答案I can't seem to get --py-files on Spark to work
链接到这里Import a module from a relative path
import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if script is called in different ways on Windows
# __file__ fails if someone does os.chdir() before
# sys.argv[0] also fails because it doesn't not always contains the path