2011-11-23 50 views
0

如何將此Perl代碼轉換爲Groovy?如何繞過外部進程的確認提示?

如何繞過外部進程的確認提示?

我想將Perl腳本轉換爲Groovy。該程序自動加載/刪除maestro(作業調度)作業。問題是刪除命令會提示確認(Y/N)它找到的每個作業。我試着在groovy中執行這個過程,但會在提示中停止。 Perl腳本正在寫一堆Y到流中,並將它打印到處理程序(如果我理解正確)以避免停​​止。我想知道如何在Groovy中做同樣的事情?

或者任何其他的方法來執行一個命令,並以某種方式在每個確認提示中寫入Y.

的Perl腳本:

$maestrostring=""; 
while ($x < 1500) { 
    $maestrostring .= "y\n"; 
    $x++; 
} 

    # delete the jobs 
    open(MAESTRO_CMD, "|ssh mserver /bin/composer delete job=pserver#[email protected]") 
    print MAESTRO_CMD $maestrostring; 
    close(MAESTRO_CMD); 

這是我工作的Groovy代碼:

def deleteMaestroJobs(){ 
      ... 
    def commandSched ="ssh $maestro_server /bin/composer delete sched=$primary_server#[email protected]" 
    def commandJobs ="ssh $maestro_server /bin/composer delete job=$primary_server#[email protected]" 

    try { 
     executeCommand commandJobs 
    } 
    catch (Exception ex){ 
     throw new Exception("Error executing the Maestro Composer [DELETE]") 
    } 

    try { 
     executeCommand commandSched 
    } 
    catch (Exception ex){ 
     throw new Exception("Error executing the Maestro Composer [DELETE]") 
    } 
} 


    def executeCommand(command){ 
     def process = command.execute() 
     process.withWriter { writer -> 
      writer.print('y\n' * 1500) 
     } 
     process.consumeProcessOutput(System.out, System.err) 
     process.waitFor() 
} 

回答

2

直接翻譯過來應該是:

'ssh mserver /bin/composer delete job=pserver#[email protected]'.execute().withWriter { writer -> 
    writer.print('y\n' * 1500) 
} 
+0

雖然小心......我想這是攪動輸出,如果你不讀流,它會窒息並阻止 –

+0

好點。我認爲perl版本會遭受同樣的問題。 – ataylor

+0

@ataylor我測試了你的方法,它看起來很有前途,但是,它只在第一個提示符下工作並刪除它,但對於其餘的它不會停止,但不會刪除它們,如果這是有道理的。 – Alidad

0

的另一種選擇是使用yes

system(qq(ssh mserver "yes y | /bin/composer delete job=pserver#APPA\@")); 
0

標準的Unix程序yes是爲這類東西而設計的。

yes | ssh mserver /bin/composer delete job=pserver#[email protected] 

請注意,如果有機會,yes將輸出無限量。但是,當像這樣使用管道時,它只會比管道的另一端先行一步,並等待它讀取,最後在操作系統給它一個SIGPIPE時退出。

+0

當我使用這個方法時,它拋出-java.io.IOException:y | ssh:找不到異常 – Alidad