避免意外将 python 脚本执行为 bash 脚本

问题描述 投票:0回答:1

我喜欢像这样直接在 bash 中运行我的 python 脚本

$ ./script.py

但有时我会忘记shebang线

#!/usr/bin/env python3
。如何避免像 bash 脚本那样意外执行 python 脚本?有没有办法阻止 bash 执行扩展名为“.py”的脚本作为 bash 脚本?

python bash shebang
1个回答
0
投票

您可以捕获“DEBUG”信号以在执行之前检查命令。然后,简单的扩展检查可以阻止 .py 文件,但不能阻止其他文件。这是概念证明:

shopt -s extdebug; stop_cmd () {
    [ -n "$COMP_LINE" ] && return  # not needed for completion
    [ "$BASH_COMMAND" = "$PROMPT_COMMAND" ] && return # not needed for prompt
    local this_command=$BASH_COMMAND;
    if [[ $this_command == *.py ]]; then
        echo "Blocking execution of Python script as bash script: $this_command"
        return 1
    else
        return 0
    fi
};
trap 'stop_cmd' DEBUG
© www.soinside.com 2019 - 2024. All rights reserved.