Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent of Perl's FindBin? [duplicate]

Tags:

python

path

perl

In Perl, the FindBin module is used to locate the directory of the original script. What's the canonical way to get this directory in Python?

Some of the options I've seen:

  • os.path.dirname(os.path.realpath(sys.argv[0]))
  • os.path.abspath(os.path.dirname(sys.argv[0]))
  • os.path.abspath(os.path.dirname(__file__))
like image 976
Eugene Yarmash Avatar asked Mar 29 '10 18:03

Eugene Yarmash


3 Answers

To update on the previous answers, with Python 3.4+, you can now do:

import pathlib
bindir = pathlib.Path(__file__).resolve().parent

Which will give you the same, except you'll get a Path object that is way more nice to work with.

like image 185
e-satis Avatar answered Nov 04 '22 00:11

e-satis


You can try this:

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

That will give you the absolute path of the current file's directory.

like image 13
Chris R Avatar answered Nov 04 '22 00:11

Chris R


I don't use Python very often so I do not know if there is package like FindBin but

import os
import sys
bindir = os.path.abspath(os.path.dirname(sys.argv[0]))

should work.

like image 8
Sinan Ünür Avatar answered Nov 04 '22 00:11

Sinan Ünür