1import sys 2import subprocess 3import os.path 4 5def has_grpcio_protoc(): 6 # type: () -> bool 7 """ checks if grpcio-tools protoc is installed""" 8 9 try: 10 import grpc_tools.protoc 11 except ImportError: 12 return False 13 return True 14 15 16def invoke_protoc(argv): 17 # type: (list) -> typing.Any 18 """ 19 Invoke protoc. 20 21 This routine will use grpcio-provided protoc if it exists, 22 using system-installed protoc as a fallback. 23 24 Args: 25 argv: protoc CLI invocation, first item must be 'protoc' 26 """ 27 28 # Add current directory to include path if nothing else is specified 29 if not [x for x in argv if x.startswith('-I')]: 30 argv.append("-I.") 31 32 # Add default protoc include paths 33 nanopb_include = os.path.dirname(os.path.abspath(__file__)) 34 argv.append('-I' + nanopb_include) 35 36 if has_grpcio_protoc(): 37 import grpc_tools.protoc as protoc 38 import pkg_resources 39 proto_include = pkg_resources.resource_filename('grpc_tools', '_proto') 40 argv.append('-I' + proto_include) 41 42 return protoc.main(argv) 43 else: 44 return subprocess.call(argv) 45 46def print_versions(): 47 try: 48 if has_grpcio_protoc(): 49 import grpc_tools.protoc 50 sys.stderr.write("Using grpcio-tools protoc from " + grpc_tools.protoc.__file__ + "\n") 51 else: 52 sys.stderr.write("Using protoc from system path\n") 53 54 invoke_protoc(['protoc', '--version']) 55 except Exception as e: 56 sys.stderr.write("Failed to determine protoc version: " + str(e) + "\n") 57 58 try: 59 import google.protobuf 60 sys.stderr.write("Python version " + sys.version + "\n") 61 sys.stderr.write("Using python-protobuf from " + google.protobuf.__file__ + "\n") 62 sys.stderr.write("Python-protobuf version: " + google.protobuf.__version__ + "\n") 63 except Exception as e: 64 sys.stderr.write("Failed to determine python-protobuf version: " + str(e) + "\n") 65 66if __name__ == '__main__': 67 print_versions() 68