FAQ
Hi!

How can I determine the path of the current module at runtime? (sys.argv[0]
won't work when running it through pythondoc)

Regards
Carsten.

Search Discussions

  • Jürgen Hermann at Jul 20, 2000 at 8:02 am
    "Carsten Gaebler" <cg at schlund.de> schrieb im Newsbeitrag
    news:3976AA30.1C4F62B8 at schlund.de...
    How can I determine the path of the current module at runtime?
    (sys.argv[0]
    won't work when running it through pythondoc)
    ### mypath.py
    import sys
    print sys.modules[__name__].__file__


    [d:\tmp]python -c "import mypath"
    mypath.py

    [d:\tmp]python -c "import mypath"
    mypath.pyc


    Ciao, J?rgen
  • Carsten Gaebler at Jul 20, 2000 at 8:21 am

    "J?rgen Hermann" wrote:

    ### mypath.py
    import sys
    print sys.modules[__name__].__file__

    [d:\tmp]python -c "import mypath"
    mypath.py
    Well, that's just the filename. What I'm looking for is the complete path,
    "d:\tmp\mypath.py" in this case.

    Carsten.
  • Darrell Gallion at Jul 20, 2000 at 6:40 pm
    print sys.modules['stat']
    <module 'stat' from 'D:\Python\Lib\stat.pyc'>

    # sys is a builtin
    sys.__file__
    Traceback (innermost last):
    File "<stdin>", line 1, in ?
    AttributeError: __file__
    import os
    os.__file__
    'D:\\Python\\Lib\\os.pyc'
    >>>


    --Darrell

    ----- Original Message -----
    From: "Carsten Gaebler" <cg at schlund.de>
    Well, that's just the filename. What I'm looking for is the complete path,
    "d:\tmp\mypath.py" in this case.
  • Gordon McMillan at Jul 20, 2000 at 11:34 pm

    Carsten Gaebler wrote:
    "J?rgen Hermann" wrote:
    ### mypath.py
    import sys
    print sys.modules[__name__].__file__

    [d:\tmp]python -c "import mypath"
    mypath.py
    Well, that's just the filename. What I'm looking for is the complete path,
    "d:\tmp\mypath.py" in this case.
    First, you don't need "sys.modules[__name__].__file__", just "__file__".

    Second, it only lacks a path when it was found in '.', so
    os.path.abspath(__file__) will do fine for anything except the top level
    script (which doesn't have a __file__ attribute).

    -Gordon

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedJul 20, '00 at 7:28a
activeJul 20, '00 at 11:34p
posts5
users4
websitepython.org

People

Translate

site design / logo © 2022 Grokbase