如何检测脚本是否从Django或命令提示符运行? [英] How to detect if script ran from Django or command prompt?
问题描述
我有一个Python脚本,可以暂停用户输入(使用 raw_input
,最近我为此脚本创建了Django Web UI.现在,当我通过Django执行脚本时,它在等待输入时暂停了在后端.
I have a Python script that pauses for user input (using raw_input
, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend.
如何确定脚本是从Django还是terminal/cmd/etc运行的?我不想维护2个代码流,一个用于Web,另一个用于终端.
How can I determine if the script was ran from Django or terminal/cmd/etc? I don't want to maintain 2 streams of code, one for web and another one for terminal.
推荐答案
为什么不使用 __ main __
: https://docs.python.org/3/library/主要 .html
Why not use __main__
: https://docs.python.org/3/library/main.html
if __name__ == '__main__':
print ('running as a script')
else:
print ('running as a web app')
在python 2.7和3.x上均可使用
Works on both python 2.7 and 3.x
这篇关于如何检测脚本是否从Django或命令提示符运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!