gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:44:26 25 4
gpt4 key购买 nike

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

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

我试过了

if sys.stdin.isatty():
***

但它似乎没有做我预期的事情。

我不会用

if __name__ == '__main__':

因为在cli的主文件中导入了config.py

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

最佳答案

我认为最简单的方法是检查 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])

关于python - 如何知道脚本是从 django 还是从 cli 运行的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com