简体   繁体   English

区分何时“直接”运行脚本或使用Python可执行文件

[英]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.

相关问题 使用-munittest时,Python测试脚本有效,但由于直接运行时出现ModuleNotFoundError而失败 - Python test script works when using -munittest, but fails due to ModuleNotFoundError when ran directly Pyinstaller 在运行 .exe 时给出“'chromedriver.exe' 可执行文件需要在 PATH 中”,但实际的 python 脚本工作正常 - Pyinstaller gives “ 'chromedriver.exe' executable needs to be in PATH” when the .exe is ran, but the actual python script works fine 从终端运行并从Python运行时,脚本的工作方式不同 - Script works differently when ran from the terminal and ran from Python Python 脚本以 sudo 运行时立即关闭 - Python Script immediately closes when ran as sudo Python中文件和目录的区别 - Distinguishing between files and directories in Python Python作为脚本或模块运行了吗? - Python ran as a script or module? 运行文件时的 cmd 与直接打开 python 时使用的不同 python - Different python used in .cmd when file is ran vs. when python is opened directly 在脚本中运行时,Python字符串格式无法按预期工作 - Python String Format not working as expected when ran in a script Python 脚本仅在 Visual Studio Code 中运行时有效 - Python script only working when ran in Visual Studio Code Python 脚本在 IDE 中工作,但在内置到可执行文件中时不起作用? - Python script works in the IDE but not when built into executable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM