如何知道脚本是从Django还是从CLI运行

Ale*_*r A 2 python django command-line-interface

我有可以从cli python脚本和Django view.py导入的config.py

如何知道config.py-导入了什么进程?Django中可能有一些特殊的变量吗?

我试过了

if sys.stdin.isatty():
    ***
Run Code Online (Sandbox Code Playgroud)

但似乎并没有达到我的预期。

我不能使用

if __name__ == '__main__':
Run Code Online (Sandbox Code Playgroud)

因为config.py导入到cli中的主文件中。

对于Cli,我需要使用argparse解析命令行参数。如果是Django,我需要导入预定义的django-config.py

cwa*_*ole 5

我认为最简单的方法是检查sys.argv

import sys

# sys.argv[0] Should output your script name in a command line environment
# It should output wsgi.py if you're using wsgi, etc.

if sys.argv[0] == 'manage.py':
   print('called with manage.py, I\'m on the command line!')

elif sys.argv[0] == 'mod_wsgi':
   print('called with with ]mod_wsgi, I\'m run by an HTTP server!')

# In the case where you have something other than Apache with mod_wsgi running your server
# you'll need to manually determine the contents of sys.argv[0]
# elif sys.argv[0] == '<your-servers-response-here>':
#   print('called by your HTTP server!')

else:
   print('called with %s, I don\'t know where that is!' % sys.argv[0])
Run Code Online (Sandbox Code Playgroud)


2ps*_*2ps 0

我会尝试使用 django 设置:

try:
    from django.conf import settings
    x = settings.DATABASES['default']['name'] == 'the name of your default database'
    from_django = True
except ImportError, AttributeError, KeyError:
    from_django = False
Run Code Online (Sandbox Code Playgroud)