python的Shebang行根本不起作用

时间:2018-10-24 12:45:31

标签: python zsh shebang

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

我添加了#!/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线的含义后不久。我希望它可以使我的生活变得轻松,不要在python之前写test.py

以下是测试代码。

#!/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

2 个答案:

答案 0 :(得分:2)

假设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\r,而python3\r显然不在您的PATH中。如果您更改以unix2dos test.py结尾的行,则应该按照this answer来解决此问题。

答案 1 :(得分:0)

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

  • 使文件可执行chmod +x test.py
  • 在目录中存在文件./test.py时运行文件
相关问题