环境:Python\r:没有这个文件或目录。

67

我的Python脚本beak包含以下shebang:

#!/usr/bin/env python

当我运行脚本$ ./beak时,我得到的结果是:

env: python\r: No such file or directory

我之前从仓库中拉取了这个脚本。这可能是什么原因呢?

8个回答

103

vimvi中打开文件,然后执行以下命令:

:set ff=unix

保存并退出:

:wq

完成!

解释

ff代表文件格式,可以接受unix\n)、dos\r\n)和mac\r)的值(仅适用于早期Intel Macs使用unix

要了解更多关于ff命令的信息:

:help ff

:wq代表写入并退出,更快的等效方式是Shift+zz(即按住Shift键,然后连续按两次z键)。

这两个命令必须在命令模式下使用。

离题: 如果你不小心被困在vim中需要退出,这里有一些简单的方法。

多文件使用

实际上不需要在vim中打开文件。可以直接从命令行进行修改:

 vi +':wq ++ff=unix' file_with_dos_linebreaks.py

处理多个*.py文件(在bash中):

for file in *.py ; do
    vi +':w ++ff=unix' +':q' "${file}"
done

虽然看起来无害,但上面的bash语法会在包含空格、引号、破折号等文件名的情况下出现错误。一个更可靠的替代方案是:

find . -iname '*.py' -exec vi +':w ++ff=unix' +':q' {} \;

移除BOM标记

有时候即使设置了Unix换行符,运行文件时仍然可能会出现错误,特别是当文件是可执行的、带有shebang并且在没有用python前缀运行时。脚本可能带有BOM标记(如0xEFBBBF或其他),这会使得shebang无效并导致shell报错。在这些情况下,python myscript.py将正常工作(因为Python 可以处理BOM),但是当执行位被设置时,./myscript.py将失败,因为你的shell(sh、bash、zsh等)无法处理BOM标记。(通常是Windows编辑器,如记事本,创建带有BOM标记的文件。)

可以通过在vim中打开文件并执行以下命令来移除BOM:

:set nobomb

2
在我的Ubuntu机器上,我使用了pip install pdfminer.six命令来安装pdf2txt.pydumppdf.py。现在错误已经消失了,它们可以正常工作了。 - pouya

48

脚本包含CR字符。Shell将这些CR字符解释为参数。

解决方案:使用以下脚本从脚本中删除CR字符。

with open('beak', 'rb+') as f:
    content = f.read()
    f.seek(0)
    f.write(content.replace(b'\r', b''))
    f.truncate()

3
@NiklasR,请查看我刚刚录制的屏幕录像。由于我在Linux机器上录制,因此错误信息略有不同。 - falsetru
非常感谢您的答复和录屏。我现在明白了问题 :) - Niklas R
1
@downvoter,您给这个回答点踩的原因是什么?我该如何改进我的回答呢? - falsetru
2
而“CR”指的是“回车”(ASCII 13)。 - melpomene
2
我刚刚解决了那个问题。 你当前的文件是“CR”类型或其他类型,所以你必须使用Notepad++或任何编辑器打开该文件,并将其转换为“LF”。 Notepad++:编辑菜单-> EOL转换-> Unix(LF),然后保存该图片: https://i.imgur.com/paAPYsK.png希望对大家有用。 - Nam Nguyễn
显示剩余2条评论

26

你可以使用以下方法将行尾转换为*nix友好格式:

dos2unix beak

3
这对我有用。当我尝试运行~/leo-5.0/launchLeo.py打开Leo编辑器时,出现了这个错误。为了使其正常工作,我必须首先使用Homebrew安装dos2unix,命令如下:brew install dos2unix - jdempcy

14
如果您使用PyCharm,您可以通过将行分隔符设置为LF来轻松解决此问题。请查看我的屏幕截图。如您所见,您可以在右下角设置它

没有对我起作用。 - PolarBear10

3
我通过运行Python3,即python3 \path\filename.py来解决了这个错误。

我怀疑这个Python脚本是在Windows上开发的,而Windows与Unix / Linux有不同的行尾符:Windows使用\r\n; Unix和Linux使用\n。如果您编辑文件,请尝试删除第一行末尾的\r,然后“./beak”应该可以正常运行。 - Ben Golding

2

falsetru的答案确实解决了我的问题。我编写了一个小助手,可以将多个文件的行结尾规范化。由于我对多平台等行结尾内容不是很熟悉,因此程序中使用的术语可能不完全正确。

#!/usr/bin/env python
# Copyright (c) 2013  Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
import sys
import glob
import argparse

def process_file(name, lend):
    with open(name, 'rb') as fl:
        data = fl.read()

    data = data.replace('\r\n', '\n').replace('\r', '\n')
    data = data.replace('\n', lend)
    with open(name, 'wb') as fl:
        fl.write(data)

def main():
    parser = argparse.ArgumentParser(description='Convert line-endings of one '
            'or more files.')
    parser.add_argument('-r', '--recursive', action='store_true',
            help='Process all files in a given directory recursively.')
    parser.add_argument('-d', '--dest', default='unix',
            choices=('unix', 'windows'), help='The destination line-ending '
            'type. Default is unix.')
    parser.add_argument('-e', '--is-expr', action='store_true',
            help='Arguments passed for the FILE parameter are treated as '
            'glob expressions.')
    parser.add_argument('-x', '--dont-issue', help='Do not issue missing files.',
            action='store_true')
    parser.add_argument('files', metavar='FILE', nargs='*',
            help='The files or directories to process.')
    args = parser.parse_args()

    # Determine the new line-ending.
    if args.dest == 'unix':
        lend = '\n'
    else:
        lend = '\r\n'

    # Process the files/direcories.
    if not args.is_expr:
        for name in args.files:
            if os.path.isfile(name):
                process_file(name, lend)
            elif os.path.isdir(name) and args.recursive:
                for dirpath, dirnames, files in os.walk(name):
                    for fn in files:
                        fn = os.path.join(dirpath, fn)
                        process_file(fn, fn)
            elif not args.dont_issue:
                parser.error("File '%s' does not exist." % name)
    else:
        if not args.recursive:
            for name in args.files:
                for fn in glob.iglob(name):
                    process_file(fn, lend)
        else:
            for name in args.files:
                for dirpath, dirnames, files in os.walk('.'):
                    for fn in glob.iglob(os.path.join(dirpath, name)):
                        process_file(fn, lend)

if __name__ == "__main__":
    main()

1
如果你正在使用 vscode 或 pycharm,将行尾序列设置为 LF。这样就解决了。

0
我尝试了第一个解决方案,使用vi / set ff=unix,但是没有起作用。后来我找到了一个非常简单的解决方法:
我在文本编辑器Mousepad中打开了Python文件(在R Pi上),选择了Document/Line Ending,将其从"DOS / Windows (CR LF)"更改为"Unix (LF)",然后保存。可能我还重新输入了顶部的shebang,记不清了。现在它可以工作了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接