如何检查命令是否存在?

时间:2015-02-06 21:20:52

标签: d external-process

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

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

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

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

2 个答案:

答案 0 :(得分:3)

我非常担心简单地运行一个命令。即使你知道它应该做什么,如果系统上有另一个具有相同名称的程序(无论是意外还是恶意),你可能会因为简单地运行命令而产生奇怪的 - 甚至可能非常糟糕的副作用。 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");
}

并且可能在某些系统上,您实际上必须解析命令的输出以查看它是否给出了正确的结果而不是查看状态。不幸的是,这正是那种特定于系统的东西。

答案 1 :(得分:1)

你可以在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");
相关问题