2015-02-06 184 views
3

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

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

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

有没有什么更好的方法来检查是否存在应用,但不抛出异常?

回答

3

我会很担心简单地运行命令。即使你知道它应该做什么,如果在系统上有另一个同名的程序(无论是不小心还是恶意),你可能会有奇怪的 - 也可能是非常糟糕的副作用来简单地运行命令。 AFAIK,正确地做这件事将会是系统特定的,我建议的最好的做法是利用系统上的任何命令行shell。

这两个问题的答案似乎提供了有关如何在Linux上执行此操作的良好信息,并且我预计它也适用于BSD。它甚至可能对Mac OS X有效,但我不知道,因为我不熟悉Mac OS X默认情况下命令行外壳的含义。

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命令来告诉你某个命令是否存在。

无论OS虽然,有什么你将需要做的是一样的东西

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

你可以使用windows下此功能(所以这是的Windows魔法作为该增加在对方的回答......),它会检查是否一个文件中的环境中存在,默认情况下在PATH:

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");