我希望python向txt文件添加一些内容,并希望使用groovy来激活python脚本。
我的groovy脚本:
def cmd = "python E:\\mypython\\hello.py"
def proc = cmd.execute()
我的python脚本:
import os
import sys
f=open("testoutput.txt","a")
f.write("hello")
f.close()
我使用的是groovy的在线编译器。运行它时似乎没有错误,但我的python脚本不工作,也没有向txt文件添加任何内容。出什么问题了?我该怎么解决这个问题?解决这个问题后,我的计划是在jira工作流中创建一个转换按钮,并将我的groovy脚本添加到这个转换的post函数部分,因此只要我按下发行票证中的转换按钮,它就会激活我的python脚本来做一些事情。这个是可能的吗?
发布于 2022-09-29 16:27:45
您的代码看起来很好,如果它没有返回任何错误,这意味着它正在运行命令!
在您的python脚本中,您打开文件时没有像这个f=open("testoutput.txt","a")
那样的任何路径说明符,所以python将使用当前目录。
但是,由于python子进程是从groovy代码中创建的,那么除非您指定它,否则它将只继承当前groovy进程的工作目录。
使用相同的execute命令(在groovy中),您可以检查工作目录:
["sh", "-c", "pwd"].execute().text
或者,如果您想确保您的python脚本正在被调用,只需让它打印它所在的当前目录:
import os
print(f"I am in directory: {os.getcwd()}")
在groovy代码中,您可以使用.text
读取进程的输出。
"python E:\\mypython\\hello.py".execute().text
您可以通过在groovy中提供目录参数(请参阅文档:https://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/ProcessGroovyMethods.html)或在python脚本中指定限定路径来解决这一问题。
至于第二个问题:请每个问题只张贴一个问题!这使得从回答到谷歌搜索的一切变得更容易!
发布于 2022-09-30 07:21:11
这可能不适用于您的场景,但您可以通过以下方式对Jython执行此操作:
groovy.grape.Grape.grab(group:'org.python', module:'jython-standalone', version:'2.7.3')
import org.python.util.PythonInterpreter
import org.python.core.*
class AJythonCall {
static void callJython() throws PyException {
PythonInterpreter jython = new PythonInterpreter()
println "Hello, Jython"
jython.exec("import sys")
jython.exec("print sys")
jython.set("a", new PyInteger(42))
jython.exec("print a")
jython.exec("x = 2 + 2")
PyObject x = jython.get("x")
println "x: " + x
println "Bye, Jython"
}
}
或者,您可以在Groovy中使用这样的脚本:
class AJythonScriptCall {
static void callJythonScript() throws PyException {
PythonInterpreter jython = new PythonInterpreter()
jython.exec("""
|num = 1
|if num >= 0:
| if num == 0:
| print("Zero")
| else:
| print("Positive number")
|else:
| print("Negative number")
""".stripMargin())
}
}
a = new AJythonCall().callJython()
b = new AJythonScriptCall().callJythonScript()
然而,YMMV,因为Jython 3还处于初级阶段。
https://stackoverflow.com/questions/73897341
复制相似问题