北肙

当你不能够再拥有,唯一可以做的,就是令自己不要忘记。

python文件执行时报错‘No such file or directory’

执行python文件的时候报如下错误: env: python3\r: No such file or directory 查看文件首行: #!/usr/bin/env python3 # -*- coding: utf-8 -*- 在命令行单独执行无任何报错 /usr/bin/env python3 Python 3.10.6 (main, Aug 11 2022, 13:49:25) [Clang 13.1.6 (clang-1316.0.21.2.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> exit() 遂祭出祖师爷谷歌大神,搜到原文如下: what could cause a script to fail to find python when it […]

执行python文件的时候报如下错误:

env: python3\r: No such file or directory

查看文件首行:

#!/usr/bin/env python3  
# -*- coding: utf-8 -*-

在命令行单独执行无任何报错
/usr/bin/env python3

Python 3.10.6 (main, Aug 11 2022, 13:49:25) [Clang 13.1.6 (clang-1316.0.21.2.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

遂祭出祖师爷谷歌大神,搜到原文如下:
what could cause a script to fail to find python when it has #!/usr/bin/env python in the first line?

原因便是,该文件在Windows下修改过,行尾加上了'\r'。
众所周知,unix文件行尾以'\n'结尾,而windows则以'\n\r'结尾,对于多出来的'\r',Unix/Unix-like系统自然是不能识别。

解决方法:

删除多余的'\r'

文章提到使用工具dos2unix和流编辑工具sed
命令如下:
dos2unix /path/to/file
Or
sed -i 's/\r$//' /path/to/file

为了避免被说成无脑抄,附上dos2unix安装命令

For macOS:
brew install dos2unix

For Gentoo:
emerge -avt dos2unix

For Centos:
yum install -y dos2unix[^1]

[^1] 据说Centos 8变成了dnf, 咱是老古董,没用过,自行man一下。

For Debian/Ubuntu:
apt-get update && apt-get install dos2unix

For Others:
不会,去问百度大哥吧。

Leave a Reply

Your email address will not be published. Required fields are marked *