簡體   English   中英

如何使用 bash 從 groovy 腳本控制台 (Jenkins) 向 python 發送單個流水線命令?

[英]How to send a single pipelined command to python using bash from a groovy script console (Jenkins)?

我正在使用 Jenkins 提供的 groovy 腳本控制台。 我有一個 Jenkins 奴隸(基於 Windows)的這條很好的工作線:

println "cmd /c echo print(\"this is a sample text.\") | python".execute().text

現在我想要 Jenkins slave(基於 Linux)的功能等價物。 所以我開始使用 Linux 命令行並讓這個核心命令為我工作:

bash -c 'echo print\(\"this is a sample text.\"\) | python'

然后我將所有這個控制台命令行包裝成一些更多的轉義碼和調用裝飾 - 但是這樣它就進入了不再起作用的狀態:

println "bash -c \'echo print\\(\\\"this is a sample text.\\\"\\) | python\'".execute().txt

運行時的結果是這樣的:

空的

由於未能解決大量影響轉義字符級別,我覺得我現在被困住了。 怎么了? 如何解決? (也許:為什么?)

PS:如果不清楚 - 我想(如果可能的話)像最初的項目一樣堅持使用單行。

print "bash -c 'echo \"print(\\\"this is a sample text.\\\")\" | python'"

輸出:

bash -c 'echo "print(\"this is a sample text.\")" | python'

如果您不需要將 bash 傳輸到 python 中,也許這適合您的喜好?

['python','-c','print("this is a sample text")'].execute().text

如果您確實需要它,請嘗試

['bash','-c', /echo print\(\"this is a sample text.\"\) | python/].execute().text

使用List.execute()有助於闡明每個參數是什么。 slashy-strings 通過更改轉義字符來提供幫助。

在深入研究之后,我發現了一個平台無關的、錯誤通道 (stderr) 感知和執行錯誤的解決方案,它甚至可以避免操作系統特定的組件,如 bash/cmd.exe:

try {
  def command = ['python', '-c', /print("this is a sample text.")/];
  if (System.properties['os.name'].toLowerCase().contains('windows'))
  {
    command[2] = command[2].replaceAll(/\"/, /\\\"/)
  }
  println "command=" + command
  def proc = command.execute()
  def rc = proc.waitFor()
  println "rc=" + rc

  def err = proc.err.text
  if( err != "" ) { print "stderr=" + err }

  def out = proc.text
  if( out != "" ) { print "stdout=" + out }
} catch(Exception e) {
  println "exception=" + e
}
println ""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM