如何使用来自groovy脚本控制台(Jenkins)的bash将单个流水线命令发送到python?

问题描述 投票:0回答:3

我正在使用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:如果不清楚 - 我希望(如果可能的话)坚持使用单线,因为最初的项目是。

python bash jenkins groovy pipe
3个回答
1
投票

如果你不需要将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通过更改转义字符来帮助。


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

输出:

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

0
投票

在挖掘了一些之后,我发现了一个有点独立于平台的错误通道(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 ""
© www.soinside.com 2019 - 2024. All rights reserved.