如何在Dart中获取当前脚本的目录?

时间:2013-10-27 20:43:21

标签: dart dart-io

我想知道脚本的目录是什么。我有一个命令行Dart脚本。

4 个答案:

答案 0 :(得分:4)

查找脚本目录的最简单方法是使用路径包。

import "package:path/path.dart" show dirname;
import 'dart:io' show Platform;

main() {
  print(dirname(Platform.script.toString()));
}

将路径包放入pubspec.yaml:

dependencies:
  path: any

请务必运行pub get下载并链接路径包。

答案 1 :(得分:2)

如果您正在为基于控制台的应用程序执行此操作(例如在单元测试中)并打算使用输出打开文件进行读取或写入,则使用Platform.script.path更有帮助:

import "package:path/path.dart" show dirname, join;
import 'dart:io' show Platform;

main() {
  print(join(dirname(Platform.script.path), 'test_data_file.dat');
}

该命令的结果可以与File对象一起使用并打开/读取(例如,如果您有需要读取/比较样本数据的单元测试,或者需要打开一个的控制台程序由于某些其他原因,相对于当前脚本的文件。)

答案 2 :(得分:2)

使用 Platform.script.path 并非在所有情况下都有效。

如果您的脚本作为单元测试被编译或运行,您将不会获得预期的结果。

这是来自 dcli 项目 (https://pub.dev/packages/dcli)

如果您使用的是 dcli,您可以调用:

// absolute path including the script name
Script.current.pathToScript;

// just the absolute path to the script's directory
Script.current.pathToScriptDirectory;

如果脚本通过 dart 运行,如果您编译脚本或脚本是单元测试,则此代码有效。

这是内部实现。

static String get _pathToCurrentScript {
    if (_current == null) {
      final script = Platform.script;

      String _pathToScript;
      if (script.isScheme('file')) {
        _pathToScript = Platform.script.toFilePath();

        if (_isCompiled) {
          _pathToScript = Platform.resolvedExecutable;
        }
      } else {
        /// when running in a unit test we can end up with a 'data' scheme
        if (script.isScheme('data')) {
          final start = script.path.indexOf('file:');
          final end = script.path.lastIndexOf('.dart');
          final fileUri = script.path.substring(start, end + 5);

          /// now parse the remaining uri to a path.
          _pathToScript = Uri.parse(fileUri).toFilePath();
        }
      }

      return _pathToScript;
    } else {
      return _current.pathToScript;
    }
  }

  static bool get _isCompiled =>
      basename(Platform.resolvedExecutable) ==
      basename(Platform.script.path);

答案 3 :(得分:0)

确定当前 __global__ void filtering_kernel(float* A, int size_A, float* B, float* size_B) { /*B and size_B are the outputs*/ int b_ptr = 0; int x = blockIdx.x * blockDim.x + threadIdx.x; if (x > size_A) return; for (int i = 0; i < size_A; i++) { if (A[x + 3] != 0) { B[b_ptr] = A[x + 0]; B[b_ptr + 1] = A[x + 1]; B[b_ptr + 2] = A[x + 2]; B[b_ptr + 3] = A[x + 3]; B[b_ptr + 4] = A[x + 4]; B[b_ptr + 5] = A[x + 5]; b_ptr += 6; *size_B = *size_B + 1; } } } 文件路径的另一种(虽然很笨拙)方法是从堆栈跟踪中提取路径。

.dart 不同,这应该适用于单元测试:

Platform.script.path

请注意,这将返回一个相对于(我认为)调用者的包根目录的路径。

如果您只需要目录,则可以对结果执行典型的路径操作。