Chemin absolu et dossier du script en bash ou Python


En bash

Chemin absolu

CHEMIN_ABSOLU=$(readlink -f '../../chemin/../relative/avec/simlinks')

Dossier du script

DOSSIER=$(dirname $(readlink -f $0));

En Python

Chemin absolu

import os
chemin_absolu = os.path.abspath('../../chemin/../relative/avec/simlinks')

Dossier du script

import os
dossier = os.path.dirname(os.path.abspath(__file__))

2 thoughts on “Chemin absolu et dossier du script en bash ou Python

  • Sam Post author

    Pour le mec qui a cherché python repertoire du script, la solution est le dernier bout de code de l’article.

    Attention, c’est dossier dans lequel est le script, pas le dossier depuis lequel le script est éxécuté, qui lui se trouve en faisant:

    >>> import os
    >>> os.getcwd()
    '/home/sam'
  • jean

    Pour le dossier du script en python :

    La commande :
    import os
    dossier = os.path.dirname(os.path.abspath(__file__))

    marche lorsqu’on execute le script par le terminal (par exemple avec : python nom_script.py) mais elle ne marche pas (en tout cas, pas chez moi) si on execute avec idle (là c’est os.getcwd() qui marche).

    Bref pour avoir quelquechose qui fonctionne sous idle ET dans un terminal j’utilise (ce n’est pas de moi !) :

    import os
    import inspect
    repertoire_script=os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))

Comments are closed.

Des questions Python sans rapport avec l'article ? Posez-les sur IndexError.