Подтвердить что ты не робот

Env: python\r: Нет такого файла или каталога

My Python script beak содержит следующую строку:

#!/usr/bin/env python

Когда я запускаю script $ ./beak, я получаю

env: python\r: No such file or directory

Я ранее вытащил этот script из репозитория. Что может быть причиной этого?

4b9b3361

Ответ 1

script содержит символы CR. Оболочка интерпретирует эти символы CR как аргументы.

Решение: удалите символы CR из script, используя следующий script.

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

Ответ 2

Откройте файл в vim или vi и выполните следующую команду:

:set ff=unix

Сохранить и выйти:

:wq

Готово!

Объяснение

ff обозначает формат файла и может принимать значения unix (\n), dos (\r\n) и mac (\r) (only meant to be used on pre-intel macs, on modern macs use [TG49])..

Чтобы узнать больше о команде ff:

:help ff

:wq означает W обряд и Q время, более быстрый эквивалент - Shift + zz (то есть, удерживая Shift, затем дважды нажмите z).

Обе команды должны использоваться в командном режиме.

Использование нескольких файлов

Нет необходимости фактически открывать файл в vim. Модификация может быть сделана непосредственно из командной строки:

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

Для обработки нескольких файлов *.pybash):

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

Ответ 3

Вы можете преобразовать строку, заканчивающуюся на * nix-friendly с

dos2unix beak

Ответ 4

Ответ 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()

Ответ 5

Если вы используете PyCharm, вы можете легко решить эту проблему, установив разделитель строк в LF. Смотрите мой скриншот. As you can see you can set it at the bottom right corner