MacOS:带有绝对路径的 Shebang 不起作用

Tob*_*ist 4 python shell shebang python-3.x nix

在某些情况下,使用 shebang 选择 Python 解释器似乎不起作用。

我正在尝试在 MacOS 上的 shebang ( #!/...) 中使用我的 python3.9 解释器。请参阅下面的 Python 文件hello.py

#!/nix/store/i46k148mi830riq4wxh49ki8qmq0731k-python3-3.9.2-env/bin/python3.9
print("Hello world")
Run Code Online (Sandbox Code Playgroud)

现在,我将确保该文件可执行,并尝试执行它:

$ chmod +x ./hello.py
$ ./hello.py

./hello.py: line 2: syntax error near unexpected token `"Hello world"'
./hello.py: line 2: `print("Hello world")'
Run Code Online (Sandbox Code Playgroud)

这很奇怪。我是不是输错了什么?让我尝试直接用我的解释器执行它,看看它是否有效:

$ chmod +x ./hello.py
$ ./hello.py

./hello.py: line 2: syntax error near unexpected token `"Hello world"'
./hello.py: line 2: `print("Hello world")'
Run Code Online (Sandbox Code Playgroud)

这似乎运作良好。舍邦为何失败?让我尝试使用不同的解释器:

$ /nix/store/i46k148mi830riq4wxh49ki8qmq0731k-python3-3.9.2-env/bin/python3.9 ./hello.py

Hello world
Run Code Online (Sandbox Code Playgroud)
$ ./hello.py

Hello world
Run Code Online (Sandbox Code Playgroud)

现在可以了吗?那很有意思。

问题:

  • 为什么 /nix/store-path 在 shebang 中似乎不起作用?
  • MacOS 上的 shebang 表达式是否存在一些我不知道的限制?例如最大长度,或某些字符,如.-是不允许的?

我的系统:

  • MacOS 大苏尔 11.2.1 (20D74)
  • bash --version:GNU bash,版本 4.4.23(1)-release (x86_64-apple-darwin17.7.0)

编辑:./hello.py从 zsh 而不是 bash 执行实际上是有效的(使用 nix-shebang 时)。所以这可能暗示这是 bash 特有的问题。

Cha*_*ffy 5

MacOS 不支持 shebangs 指向脚本——这会导致Exec 格式错误

bash 和 zsh 都尝试解决失败问题,并取得了不同程度的成功execve()。然而,更好的解决方法是使用上游 nixpkgs 的能力(如https://github.com/NixOS/nixpkgs/pull/93757中介绍的那样)来生成不会触发错误的包装器。

这个包装不会看起来像:

#!/nix/store/i46k148mi830riq4wxh49ki8qmq0731k-python3-3.9.2-env/bin/python3.9
Run Code Online (Sandbox Code Playgroud)

...但看起来更像是:

#!/nix/store/74shlfgb18717ixjlpivpxd7iqcyhyn5-bash-4.4-p23/bin/bash /nix/store/i46k148mi830riq4wxh49ki8qmq0731k-python3-3.9.2-env/bin/python3.9
Run Code Online (Sandbox Code Playgroud)

...有点令人惊讶的是,它按预期工作。