Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何知道脚本是从django还是从cli运行的_Python_Django_Command Line Interface - Fatal编程技术网

Python 如何知道脚本是从django还是从cli运行的

Python 如何知道脚本是从django还是从cli运行的,python,django,command-line-interface,Python,Django,Command Line Interface,我有config.py,可以从cli python脚本和Django view.py导入 如何知道在config.py中是什么进程导入的? Django可能有一些特别的Var 我试过了 if sys.stdin.isatty(): *** 但它似乎没有做我期望的事情 我不能用 if __name__ == '__main__': 因为config.py已导入cli中的主文件 对于Cli,我需要使用argparse解析命令行参数。 如果是Django,我需要导入预定义的Django c

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

如何知道在config.py中是什么进程导入的? Django可能有一些特别的Var

我试过了

if sys.stdin.isatty():
    ***
但它似乎没有做我期望的事情

我不能用

if __name__ == '__main__':
因为config.py已导入cli中的主文件

对于Cli,我需要使用argparse解析命令行参数。
如果是Django,我需要导入预定义的Django config.py,我会尝试使用piggy退出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

我认为最简单的方法是检查
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])
导入系统 #sys.argv[0]应在命令行环境中输出脚本名称 #如果您正在使用wsgi,它应该输出wsgi.py,等等。 如果sys.argv[0]=“manage.py”: print('使用manage.py调用,我在命令行上!') elif sys.argv[0]=“mod_wsgi”: print('mod_wsgi调用,由HTTP服务器运行!') #如果您的服务器运行的不是Apache,而是mod_wsgi #您需要手动确定sys.argv[0]的内容 #elif系统argv[0]='': #打印('由HTTP服务器调用!') 其他: print('用%s调用,我不知道它在哪里!'%sys.argv[0])
这取决于您所说的“由Apache运行”的含义,但该特定测试对mod_wsgi和我所知道的其他wsgi服务器都不起作用。@GrahamDumpleton您说得很对。我是从另一个虚拟主机复制的,这个虚拟主机是创造性地建立的(翻译:我不知道我在做什么)<当使用
Apache
时,code>mod_wsgi位于
sys.argv[0]
中。如果您想允许模糊匹配,例如允许在当前工作目录中使用
/manage.py
运行python脚本,则在中介绍了我关于是否在Apache下运行mod_wsgi的更可靠的测试(不需要调用
python manage.py
),您可以在sys.argv[0]中使用
if'manage.py'
。比直接字符串比较慢一小部分,但更好的用户体验。您试图解决的真正的根本问题是什么?如果您解释原始需求,而不是询问如何让您感知的解决方案工作,那么我们可能可以提出更好的建议。让模块返回并尝试解析命令行e参数,绕过它正在使用的程序正在进行的任何参数解析和配置系统,听起来不是一个很好的主意