【问题标题】:Shebang line for python does not work at allpython的Shebang线根本不起作用
【发布时间】:2019-03-28 21:24:21
【问题描述】:

这是一个棘手的问题。它有几个主题。但他们都没有帮助我。

我添加了#!/usr/bin/env python3(或python),然后运行test.py,它报告了zsh: command not found: test.py。我很困惑。我尝试过多种形式的shebang。你能帮帮我吗?

在下面的错误报告中,您可以看到在 HOME 路径和 test.py 的父路径下运行时报告不同

[Scripts] test.py                                                     20:51:04
zsh: command not found: test.py
[Scripts] cd ~                                                        20:51:33
[~] Scripts/test.py                                                   20:51:43
env: python\r: No such file or directory

没多久我就明白了shebang线的意思了。我希望它能让我的生活变得轻松,永远不要在test.py之前写python

下面是测试代码。

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser(description='test')
parser.add_argument('-o', dest='what', action='store', default='hello', metavar='WHAT')

args = parser.parse_args()
print(args.what)

以下是配置。

PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:$PATH"

在终端中,

[~] which python                                                      20:36:55
python: aliased to python3
[~] which python3                                                     20:36:57
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
ls -l
-rwxrwxrwx@ 1 william  staff   273 10 24 20:51 test.py

【问题讨论】:

  • 试试python3 test.py 而不是test.py?
  • @cryptnome:shebang 应该翻译成这样
  • ./test.py怎么样
  • 确保脚本有执行权限并使用命令./test.py运行
  • 听起来test.py 不在您的路径中。按照其他人的建议,尝试使用相对(或绝对)路径。

标签: python zsh shebang


【解决方案1】:

假设test.py的目录不在你的PATH中,你需要使用相对路径或绝对路径,并确保脚本有执行权限。

$ chmod u+x test.py
$ ./test.py

应该正确执行。


出现错误env: python3\r: No such file or directory:文件使用“CRLF”换行符:\r\n,而应使用单个\n。所以zsh 在第一个\n 上分裂,留下shebang 行#!/usr/bin/env python3\rpython3\r 显然不在你的PATH 中。如果您更改以unix2dos test.py 结尾的行尾,则应该按照this answer 解决问题。

【讨论】:

  • ls -l -rwxrwxrwx@ 1 威廉员工 273 10 24 20:51 test.py
  • @WilliamSong 在没有相对路径的情况下使用./test.py 而不是test.py 的结果是什么?
  • env: python3\r: 没有这样的文件或目录
  • @WilliamSong 看起来像是换行问题:您可以在 *nix 类型系统(包括 macOS)上看到以 file test.py 结尾的那种行尾。确保文件使用 Unix 换行符而不是 CRLF 换行符
  • @WilliamSong 我不能告诉你为什么\r\n 在那里,但这可能是你当前问题的原因。如果你修复你的行尾,它现在应该可以工作了,据我所知。
【解决方案2】:

将shebang添加到您的python文件后:

  • 使文件可执行chmod +x test.py
  • 在文件存在的目录中运行文件./test.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2011-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多