【问题标题】:How to check if command is exists?如何检查命令是否存在?
【发布时间】:2015-04-07 03:21:27
【问题描述】:

我需要检测应用程序是否存在于系统中。 如果可执行命令不存在,我使用它 std.process 下一个代码是 trow 异常:

try
{
    auto ls = execute(["fooapp"]);
    if (ls.status == 0) writeln("fooapp is Exists!\n");
}

catch (Exception e)
{
        writeln("exception");
}

有没有更好的方法来检查应用程序是否存在而不抛出异常?

【问题讨论】:

    标签: d external-process


    【解决方案1】:

    我会非常担心仅仅运行一个命令。即使您知道它应该做什么,如果系统上有另一个同名的程序(无论是意外还是恶意),您可能会在简单地运行命令时产生奇怪的 - 并且可能非常糟糕的副作用。 AFAIK,正确执行此操作将是系统特定的,我可以建议的最好的方法是利用系统上的任何命令行 shell。

    这两个问题的答案似乎为如何在 Linux 上执行此操作提供了很好的信息,我希望它对 BSD 也有效。它甚至可能对 Mac OS X 也有效,但我不知道,因为我不熟悉 Mac OS X 在命令行 shell 方面的默认设置。

    How to check if command exists in a shell script?

    Check if a program exists from a Bash script

    答案似乎可以归结为使用type 命令,但您应该阅读答案中的详细信息。对于 Windows,快速搜索会发现:

    Is there an equivalent of 'which' on the Windows command line?

    它似乎提供了几种不同的方法来解决 Windows 上的问题。所以,从那里,应该可以找出一个在 Windows 上运行的 shell 命令来告诉你某个特定的命令是否存在。

    不过,不管操作系统如何,您需要做的就是类似

    bool commandExists(string command)
    {
        import std.process, std.string;
        version(linux)
            return executeShell(format("type %s", command)).status == 0;
        else version(FreeBSD)
            return executeShell(format("type %s", command)).status == 0;
        else version(Windows)
            static assert(0, "TODO: Add Windows magic here.");
        else version(OSX)
            static assert(0, "TODO: Add Mac OS X magic here.");
        else
            static assert(0, "OS not supported");
    }
    

    可能在某些系统上,您实际上必须解析命令的输出以查看它是否为您提供了正确的结果,而不是查看状态。不幸的是,这正是那种非常特定于系统的事情。

    【讨论】:

      【解决方案2】:

      您可以在 windows 下使用此功能(所以这是 Windows 魔术 添加如在另一个答案中所说...),它检查环境中是否存在文件,默认情况下在路径:

      string envFind(in char[] filename, string envVar = "PATH")
      {  
          import std.process, std.array, std.path, std.file;
          auto env = environment.get(envVar);
          if (!env) return null;
          foreach(string dir; env.split(";")) {
              auto maybe = dir ~ dirSeparator ~ filename; 
              if (maybe.exists) return maybe.idup;
          }
          return null;
      }
      

      基本用法:

      if (envFind("cmd.exe") == "")  assert(0, "cmd is missing");
      if (envFind("explorer.exe") == "")  assert(0, "explorer is missing");
      if (envFind("mspaint.exe") == "") assert(0, "mspaintis missing");
      

      【讨论】:

        猜你喜欢
        • 2011-11-05
        • 1970-01-01
        • 2018-12-25
        • 2016-04-15
        • 1970-01-01
        • 2016-10-20
        • 2012-09-21
        • 1970-01-01
        • 2011-09-07
        相关资源
        最近更新 更多