Get location of the .py source file

后端 未结 3 528
轮回少年
轮回少年 2020-12-03 03:54

Say I have a python file in directory e like this:

/a/b/c/d/e/file.py

Under directory e I have a few folders I wan

相关标签:
3条回答
  • 2020-12-03 04:43
    # in /a/b/c/d/e/file.py
    import os
    os.path.dirname(os.path.abspath(__file__)) # /a/b/c/d/e
    
    0 讨论(0)
  • 2020-12-03 04:49

    In Python +3.4 use of pathlib is more handy:

    from pathlib import Path
    
    source_path = Path(__file__).resolve()
    source_dir = source_path.parent
    
    0 讨论(0)
  • 2020-12-03 04:55

    Here is my solution which (a) gets the .py file rather than the .pyc file, and (b) sorts out symlinks.

    Working on Linux, the .py files are often symlinked to another place, and the .pyc files are generated in the directory next to the symlinked py files. To find the real path of the source file, here's part of a script that I use to find the source path.

    try:
        modpath = module.__file__
    except AttributeError:
        sys.exit('Module does not have __file__ defined.')
        # It's a script for me, you probably won't want to wrap it in try..except
    
    # Turn pyc files into py files if we can
    if modpath.endswith('.pyc') and os.path.exists(modpath[:-1]):
        modpath = modpath[:-1]
    
    # Sort out symlinks
    modpath = os.path.realpath(modpath)
    
    0 讨论(0)
提交回复
热议问题