【问题标题】:env: python\r: No such file or directoryenv: python\r: 没有这样的文件或目录
【发布时间】:2013-10-25 21:24:39
【问题描述】:

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

#!/usr/bin/env python

当我运行脚本 $ ./beak 时,我得到了

env: python\r: No such file or directory

我之前从存储库中提取了这个脚本。这可能是什么原因?

【问题讨论】:

    标签: python macos osx-mountain-lion shebang env


    【解决方案1】:

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

    :set ff=unix
    

    保存并退出:

    :wq
    

    完成!

    说明

    ff代表file format,可以接受unix(\n)、dos(\r\n)和mac(\r)的值) (仅适用于英特尔之前的 Mac,在现代 Mac 上使用 unix

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

    :help ff
    

    :wq 代表 Write 和 Quit,更快的等价物是 Shift+zz (即按住Shift然后按z两次)。

    这两个命令都必须在command mode中使用。

    用于多个文件

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

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

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

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

    ? offtopic:如果你碰巧卡在 vim 中需要退出,here 是一些简单的方法。

    删除BOM 标记

    有时即使在设置了 unix 行结束符之后,运行文件时仍然可能会出错,尤其是当文件是可执行文件并且具有 shebang 时。该脚本可能有一个 BOM 标记(例如 0xEFBBBF 或其他),这会使 shebang 无效并导致 shell 抱怨。在这些情况下,python myscript.py 可以正常工作(因为 python 可以 处理 BOM),但即使设置了执行位,./myscript.py 也会失败,因为你的 shell(sh、bash、zsh 等)无法处理 BOM 标记。 (通常是 Notepad 等 Windows 编辑器创建带有 BOM 标记的文件。)

    可以通过在vim 中打开文件并管理以下命令来删除 BOM:

    :set nobomb
    

    【讨论】:

    • pdf2txt.pydumppdf.py 上都使用了这个,我在我的Ubuntu 机器上由pip install pdfminer.six 安装。现在错误消失了,它们可以正常工作了
    【解决方案2】:

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

    【讨论】:

    • 我怀疑 python 脚本是在 Windows 上开发的,它的行尾与 Unix/Linux 不同:Windows 使用 \r\n; Unix 和 Linux 使用 \n。如果您编辑文件,请尝试删除第一行末尾的 \r,然后“./beak”应该可以工作。
    【解决方案3】:

    如果您使用 PyCharm,您可以通过将行分隔符设置为 LF 轻松解决它。看我的截图。

    【讨论】:

    • 对我没用
    【解决方案4】:

    您可以使用

    将行尾转换为对 *nix 友好的行尾
    dos2unix beak
    

    【讨论】:

    • 这对我有用。尝试运行 ~/leo-5.0/launchLeo.py 以打开 Leo 编辑器时出现此错误。为了让它工作,我必须首先使用 Homebrew 安装 dos2unix,如下所示:brew install dos2unix
    【解决方案5】:

    脚本包含 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()
    

    【讨论】:

    • @NiklasR,见the screencast我刚刚录制。错误信息略有不同,因为我是在Linux机器上记录的。
    • 非常感谢您的回答和截屏视频。我现在明白这个问题了:)
    • @downvoter,有什么理由反对这个吗?如何改进答案?
    • “CR”是指“回车”​​(ASCII 13)。
    • 我刚刚解决了这个问题。您当前的文件是“CR”类型或其他任何东西,因此您必须通过 notepad++ 或任何编辑器打开该文件并将其转换为“LF”。 Notepad++:编辑菜单 -> EOL 转换 -> Unix (LF),然后保存该图片:i.imgur.com/paAPYsK.png希望对你们有用。
    【解决方案6】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-19
      • 2020-05-26
      • 1970-01-01
      • 2011-04-08
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      相关资源
      最近更新 更多