pythonDylib function

String pythonDylib()

Implementation

String pythonDylib() {
  final platformSuffix = io.Platform.isWindows
      ? '.dll'
      : io.Platform.isMacOS
          ? '.dylib'
          : '.so';
  final options = ['--ldflags', '--embed'];
  var result = Process.runSync('python3.10-config', options);
  if (result.exitCode != 0) {
    result = Process.runSync('python3.9-config', options);
    if (result.exitCode != 0) {
      result = Process.runSync('python3.8-config', options);
      if (result.exitCode != 0) {
        throw Exception('Failed to get python location');
      }
    }
  }
  final output = result.stdout.toString().trim();
  // TODO: Windows paths can have spaces
  // print(output);
  final parser = ArgParser()
    ..addMultiOption('L', abbr: 'L')
    ..addMultiOption('l', abbr: 'l');
  final results = parser.parse(output.split(' '));
  // print(results);
  for (final dylibDir in (results['L'] as List<String>)) {
    // print('Got dylib dir: $dylibDir');
    final dir = Directory(dylibDir);
    final files = dir
        .listSync()
        .whereType<File>()
        .where((e) => e.uri.pathSegments.last.endsWith(platformSuffix))
        .toList();
    for (final file in files) {
      final fname = file.uri.pathSegments.last;
      if (fname.startsWith('libpython') || fname.startsWith('python')) {
        // print('Opening dynamic library: ${file.path}');
        // ffi.DynamicLibrary.open(file.path);
        return file.path;
      } else {
        // print('Skipping dynamic library: ${file.path}');
      }
    }
  }
  throw Exception('Failed to find python dylib');
}