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

Set*_*add 6 dart dart-io

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

Dan*_*eld 8

如果您正在为基于控制台的应用程序(例如在单元测试中)执行此操作并打算使用输出打开文件以进行读取或写入,则使用更有用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'));
}
Run Code Online (Sandbox Code Playgroud)

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


Set*_*add 5

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

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

main() {
  print(dirname(Platform.script.toString()));
}
Run Code Online (Sandbox Code Playgroud)

将路径包放入您的 pubspec.yaml 中:

dependencies:
  path: any
Run Code Online (Sandbox Code Playgroud)

并且一定要运行pub get下载并链接路径包。

  • 我得到的结果以 `file://` 为前缀。对我来说略有改进的是改用`Platform.script.path`。 (5认同)

Bre*_*ton 5

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

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

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

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

// absolute path including the script name
DartScript.self.pathToScript;
Run Code Online (Sandbox Code Playgroud)

或者

// just the absolute path to the script's directory
DartScript.self.pathToScriptDirectory;
Run Code Online (Sandbox Code Playgroud)

如果脚本通过 dart <scriptname.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);
Run Code Online (Sandbox Code Playgroud)