env: python: No hay tal archivo o directorio


Mi script Python beak contiene el siguiente shebang:

#!/usr/bin/env python

Cuando corro el script $ ./beak, obtengo

env: python\r: No such file or directory

Anteriormente saqué este script de un repositorio. ¿Cuál podría ser la razón de esto?

Author: Niklas R, 2013-10-17

5 answers

El script contiene caracteres CR. La shell interpreta estos caracteres CR como argumentos.

Solución: Elimine los caracteres CR del script utilizando el siguiente script.

with open('beak', 'rb+') as f:
    content = f.read()
    f.seek(0)
    f.write(content.replace(b'\r', b''))
    f.truncate()
 25
Author: falsetru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-20 21:42:26

Abra el archivo en vim o vi, y administre el siguiente comando:

:set ff=unix

Guardar y salir:

:wq

Hecho!

Explicación

ff soportes para formato de archivo, y puede aceptar los valores de unix (\n), dos (\r\n) y mac (\r) (solo está destinado a ser utilizado en macs anteriores a intel, en macs modernas use unix)..

Para leer más sobre el comando ff:

:help ff

:wq significa W rite y Q uit, un equivalente más rápido es Shift+zz (es decir, mantenga presionado Shift y luego presione z dos veces).

Ambos comandos deben usarse en modo de comando.

Uso en varios archivos

No es necesario abrir realmente el archivo en vim. La modificación se puede hacer directamente desde la línea de comandos:

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

Para procesar múltiples archivos *.py:

for file in *.py ; do
    vi +':w ++ff=unix' +':q' ${file}
done
 37
Author: ccpizza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-21 06:55:11

Puede convertir el final de la línea en otros compatibles con * nix con

dos2unix beak
 16
Author: Rondo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-19 04:36:33

La respuesta de falsetru resolvió absolutamente mi problema. Escribí un pequeño ayudante que me permite normalizar los finales de línea de varios archivos. Como no estoy muy familiarizado con las cosas de fin de línea en múltiples plataformas, etc. la terminología utilizada en el programa puede no ser 100% correcta.

#!/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
Author: Niklas R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-18 12:39:15

Si usa PyCharm, puede resolverlo fácilmente estableciendo el separador de líneas en LF. Mira mi captura de pantalla. Como puede ver, puede configurarlo en la esquina inferior derecha

 0
Author: csib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-30 12:43:51