【问题标题】:How to run a script using "dart pub global run" command?如何使用“dart pub global run”命令运行脚本?
【发布时间】:2021-07-17 16:46:31
【问题描述】:

我的包目录foo:

pubspec.yaml 文件有:

name: foo

executables:
  foo: bar

foo 包是使用dart pub global activate ... 激活的,如果我将目录添加到PATH 环境,则以下命令有效:

foo bar

但如果我删除它并尝试运行dart pub global run 命令,它就不起作用了。

me@mac foo % dart pub global run foo bar
Could not find bin/foo.dart.

那么,我怎样才能运行脚本而不将其添加到 PATH 使用 dart pub global run 建议 here

您可以从命令行直接从激活的包中运行脚本。如果无法直接运行脚本,也可以使用 dart pub global run。

注意dart pub global run foo:bar 有效,但这与pubspec.yaml 文件中定义的可执行文件无关。

【问题讨论】:

  • 请显示完整的activate 命令行
  • @PatrickO'Hara dart pub global activate --source path <path_of_foo>

标签: dart command-line


【解决方案1】:

指定:

executables:
  foo: bar

表示激活包后,命令foo会映射到文件bar.dart。调用时无需指定bar

例如,我有这个包:

name: dictionary
...
executables:
    scrabble:

它定义了一个调用scrabble.dart 的可执行文件scrabble。我这样激活它:

dart pub global activate --source path dictionary

此报告:

...
Installed executable scrabble.
Activated dictionary 1.0.0 at path "[...]\Dart\dictionary".

我可以调用调用scrabble.dartscrabble 命令。我也可以这样调用它:

dart pub global run dictionary:scrabble

如果我的pubspec 有:

executables:
    dictionary: scrabble

然后命令dictionary 调用文件scrabble.dart

(不要忘记在您的PATH 中包含pub 缓存。对于Windows 上的我来说,这是C:\Users\pohara\AppData\Roaming\Pub\Cache\bin

补充:继续dictionary: scrabble 示例,当我激活字典时,我得到:

...
Installed executable dictionary.
Activated dictionary 1.0.0 at path "[...]\Dart\dictionary".

我在 Windows 上的 pub 缓存有这个文件来运行 dictionary 命令:

> cat C:\Users\pohara\AppData\Roaming\Pub\Cache\bin\dictionary.bat
@echo off
rem This file was created by pub v2.12.2.
rem Package: dictionary
rem Version: 1.0.0
rem Executable: dictionary
rem Script: scrabble
pub global run dictionary:scrabble %*

因此dictionary 命令显式运行dictionary 包中的scrabble 文件。

这两个命令都失败了:

> dart pub global run dictionary scrabble
Could not find bin\dictionary.dart.

> dart pub global run dictionary
Could not find bin\dictionary.dart.

当然这个成功了:

> dart pub global run dictionary:scrabble

这一切都与文档https://dart.dev/tools/pub/pubspec#executables一致。

【讨论】:

  • 感谢您的回答,但我不知道这如何回答我的问题。让我换个说法。如果您尚未将 pub-cache 添加到路径中,并且您运行(来自文档链接本身)webdev serve 您会收到错误“zsh:command not found:webdev”,但您可以使用直接运行相同的命令dart pub global run webdev serve 但为什么我不能为我的 foo 包做同样的事情,这就是问题所在。
  • webdev server 正在运行带有参数serve 的包webdev。在您的示例中,包foo 提供了可执行文件foo,它调用文件bar.dart。当您运行dart pub global run foo bar 时,术语bar 只是foo 可执行文件的附加参数。
  • 另请参阅我对答案所做的补充
  • 谢谢,现在更清楚了。所以,如果我猜对了,当我执行 webdev server 时,我实际上是在运行 this file 并将 server 作为参数传递。
  • 表现良好的可执行文件具有帮助文本,告诉您它们期望的命令/参数。我使用https://pub.dev/packages/args 来帮助解决这个问题。
猜你喜欢
  • 2014-12-13
  • 1970-01-01
  • 2021-10-12
  • 2023-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 1970-01-01
相关资源
最近更新 更多