[英]Distinguishing between when a script is ran 'directly', or with Python executable
How can a Python program determine if it was executed as an executable file on a Unix system instead of being called as a script? Python程序如何确定它是否在Unix系统上作为可执行文件执行而不是被称为脚本?
./program.py
instead of 代替
python ./program.py
'/program' in sys.argv[0]
cannot distinguish between the example cases. sys.argv[0]
“ / program”无法区分示例情况。
A somewhat hackish solution would be adding an environment variable indicating this to the shebang line in program.py
: 一个有点骇人听闻的解决方案是在
program.py
的shebang行中添加一个表明此情况的环境变量:
#!/usr/bin/env noscript=True python
import os
if os.getenv('noscript'):
print("called as executable")
else:
print("called as script")
There really is no distinction. 确实没有区别。 If you set the executable bit, the os ultimately does exactly what you do on the command line -- it does
python script.py
. 如果您将可执行位设置为1,则os最终将完全按照您在命令行上的方式进行操作-它执行
python script.py
。 The only difference is that the os looks at the first line beginning with #!
唯一的区别是os会看
#!
开头的第一行#!
to determine precisely what version of python to run. 以确定要运行的python版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.