github.com/grumpyhome/grumpy@v0.3.1-0.20201208125205-7b775405bdf1/grumpy-tools-src/grumpy_tools/pydeps.py (about) 1 #!/usr/bin/env python 2 3 # Copyright 2016 Google Inc. All Rights Reserved. 4 # 5 # Licensed under the Apache License, Version 2.0 (the "License"); 6 # you may not use this file except in compliance with the License. 7 # You may obtain a copy of the License at 8 # 9 # http://www.apache.org/licenses/LICENSE-2.0 10 # 11 # Unless required by applicable law or agreed to in writing, software 12 # distributed under the License is distributed on an "AS IS" BASIS, 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 # See the License for the specific language governing permissions and 15 # limitations under the License. 16 17 """Outputs names of modules imported by a script.""" 18 from __future__ import absolute_import 19 20 import os 21 import sys 22 23 from .compiler import imputil 24 from .compiler import util 25 26 try: 27 xrange # Python 2 28 except NameError: 29 xrange = range # Python 3 30 31 32 def main(script=None, modname=None, package_dir='', with_imports=False): 33 gopath = os.environ['GOPATH'] 34 35 imports = imputil.collect_imports(modname, script, gopath, package_dir=package_dir) 36 37 def _deps(): 38 names = set([modname]) 39 for imp in imports: 40 if imp.is_native and imp.name: 41 yield imp.name 42 else: 43 if not imp.script: 44 continue # Let the ImportError raise on run time 45 46 parts = imp.name.split('.') 47 # Iterate over all packages and the leaf module. 48 for i in xrange(len(parts)): 49 name = '.'.join(parts[:i+1]) 50 if name and name not in names: 51 names.add(name) 52 if name.startswith('.'): 53 name = name[1:] 54 yield name 55 56 if with_imports: 57 return _deps(), imports 58 else: 59 return _deps() 60