13

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

4

4 回答 4

11

如果您正在为基于控制台的应用程序(例如在单元测试中)执行此操作并打算使用输出打开文件以进行读取或写入,则使用以下方法更有帮助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对象一起使用并被打开/读取(例如,如果您有一个需要读取/比较示例数据的单元测试,或者需要打开与当前脚本相关的文件的控制台程序)其他原因)。

于 2018-04-20T03:07:30.890 回答
6

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

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下载和链接路径包。

于 2013-10-27T20:43:21.480 回答
3

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

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

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

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

// absolute path including the script name
DartScript.self.pathToScript;

或者

// just the absolute path to the script's directory
DartScript.self.pathToScriptDirectory;

如果脚本通过 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);
于 2021-01-13T11:10:20.673 回答
1

确定当前.dart文件路径的另一种(尽管很老套)方法是从堆栈跟踪中提取路径。

与 不同Platform.script.path,这应该适用于单元测试:

import 'package:stack_trace/stack_trace.dart' as stacktrace;

String currentDartFilePath() => stacktrace.Frame.caller(1).library;

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

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

于 2021-05-25T20:55:26.697 回答