haiv icon

path2package.py

haiv | PRO | 07/22/19 09:33:53 PM UTC | 0 ⭐ | 481 👁️ | Never ⏰ | []
Python |

640 B

|

None

|

0 👍

/

0 👎

#!/usr/bin/env python3
"""
Given a directory, find the name of the python package
"""
 
import pathlib
import argparse
 
 
marker = '__init__.py'
 
 
def find_package(path_to_leaf):
    path = pathlib.Path(path_to_leaf).resolve()
    components = []
 
    while (path / marker).exists():
        components.insert(0, path.name)
        path = path.parent
 
    return '.'.join(components)
 
 
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('paths', nargs='*', default=['.'])
    options = parser.parse_args()
    for path in options.paths:
        package = find_package(path)
        if package:
            print(package)

Comments