开发者

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

This question already has answers here: How do you properly determine the current script directory? (16 answers) Closed开发者_高级运维 4 years ago.

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__))


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜