2015-02-06 251 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"); 
相關問題