关于jython

[b]如何在jython中调用命令行?[/b]

由于jython和python的底层实现不确定完全相同, os.system在jython.jar中运行时会抛出这样的错误(os的很多方法在Jython中都不能用, 也许跟Jython目前版本低有关系, 我用的是2.5, 所以一旦不能用只能寻找jython的其他替代方法, 如果没有合适的替代方法,就可以使用强大的JDK)

04/06/12 15:54:23.875 INFO: [ContainerScriptSupport] Initializing component scripts
04/06/12 15:54:47.296 SEVERE: [ContainerScriptSupport] Error initializing script test.py javax.script.ScriptException: TypeError: unsupported operand type(s) for +: 'NoneType' and 'list' in <script> at line number 2
at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:191)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:42)
at org.python.jsr223.PyScriptEngine.access$300(PyScriptEngine.java:20)
at org.python.jsr223.PyScriptEngine$PyCompiledScript.eval(PyScriptEngine.java:220)
at javax.script.CompiledScript.eval(CompiledScript.java:89)
at com.datasynapse.fabric.container.ContainerScriptSupport.initScript(ContainerScriptSupport.java:141)
at com.datasynapse.fabric.container.ContainerScriptSupport.init(ContainerScriptSupport.java:81)
at com.datasynapse.fabric.container.AbstractContainer.init(AbstractContainer.java:248)
at com.datasynapse.fabric.engine.domain.GridLibDomainManager.init(GridLibDomainManager.java:277)
at com.datasynapse.fabric.engine.domain.GridLibDomainManager.initDomain(GridLibDomainManager.java:234)
at com.datasynapse.fabric.engine.plugins.DomainManagerPlugin.activate(DomainManagerPlugin.java:444)
at com.datasynapse.fabric.engine.plugins.DomainManagerPlugin.activate(DomainManagerPlugin.java:338)
at com.datasynapse.fabric.engine.plugins.DomainManagerPlugin$ICActivate.run(DomainManagerPlugin.java:1145)
at com.datasynapse.fabric.engine.plugins.DomainManagerPlugin$ICActivationQueueHandler.doRun(DomainManagerPlugin.java:1197)
at com.datasynapse.fabric.util.StoppableRunnable.run(StoppableRunnable.java:21)
at com.datasynapse.commons.sync.threading.ReusableThreadPool$InternalThread.run(ReusableThreadPool.java:335)
Caused by: Traceback (most recent call last):
File "<script>", line 2, in <module>
File "D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py", line 456, in call
File "D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py", line 751, in __init__
File "D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py", line 1236, in _execute_child
TypeError: unsupported operand type(s) for +: 'NoneType' and 'list'

at org.python.core.PyException.fillInStackTrace(PyException.java:70)
at java.lang.Throwable.<init>(Throwable.java:181)
at java.lang.Exception.<init>(Exception.java:29)
at java.lang.RuntimeException.<init>(RuntimeException.java:32)
at org.python.core.PyException.<init>(PyException.java:46)
at org.python.core.PyException.<init>(PyException.java:43)
at org.python.core.PyException.<init>(PyException.java:61)
at org.python.core.Py.TypeError(Py.java:221)
at org.python.core.PyObject._basic_add(PyObject.java:2017)
at org.python.core.PyObject._add(PyObject.java:1995)
at subprocess$py._execute_child$36(D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py:1266)
at subprocess$py.call_function(D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyBaseCode.call(PyBaseCode.java:301)
at org.python.core.PyBaseCode.call(PyBaseCode.java:194)
at org.python.core.PyFunction.__call__(PyFunction.java:387)
at org.python.core.PyMethod.instancemethod___call__(PyMethod.java:220)
at org.python.core.PyMethod.__call__(PyMethod.java:211)
at org.python.core.PyMethod.__call__(PyMethod.java:201)
at subprocess$py.__init__$19(D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py:840)
at subprocess$py.call_function(D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyBaseCode.call(PyBaseCode.java:301)
at org.python.core.PyBaseCode.call(PyBaseCode.java:194)
at org.python.core.PyFunction.__call__(PyFunction.java:387)
at org.python.core.PyMethod.instancemethod___call__(PyMethod.java:220)
at org.python.core.PyMethod.__call__(PyMethod.java:211)
at org.python.core.PyMethod.__call__(PyMethod.java:206)
at org.python.core.Deriveds.dispatch__init__(Deriveds.java:19)
at org.python.core.PyObjectDerived.dispatch__init__(PyObjectDerived.java:1057)
at org.python.core.PyType.type___call__(PyType.java:1565)
at org.python.core.PyType.__call__(PyType.java:1548)
at org.python.core.PyObject._callextra(PyObject.java:527)
at subprocess$py.call$7(D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py:456)
at subprocess$py.call_function(D:\build\fabric\DSEngine\.\cache\expansions\d9b255d4fd2358cf0e7f39446ec314167e20d7a8\lib\jython-standalone-2.5.2.jar\Lib\subprocess.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyBaseCode.call(PyBaseCode.java:301)
at org.python.core.PyBaseCode.call(PyBaseCode.java:194)
at org.python.core.PyFunction.__call__(PyFunction.java:387)
at org.python.core.PyFunction.__call__(PyFunction.java:381)
at org.python.core.PyObject.invoke(PyObject.java:3616)
at org.python.modules.posix.PosixModule.system(PosixModule.java:717)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.python.core.PyReflectedFunction.__call__(PyReflectedFunction.java:186)
at org.python.core.PyReflectedFunction.__call__(PyReflectedFunction.java:204)
at org.python.core.PyObject.__call__(PyObject.java:387)
at org.python.core.PyObject.__call__(PyObject.java:391)
at org.python.pycode._pyx0.f$0(<script>:2)
at org.python.pycode._pyx0.call_function(<script>)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1261)
at org.python.core.__builtin__.eval(__builtin__.java:484)
at org.python.core.__builtin__.eval(__builtin__.java:488)
at org.python.util.PythonInterpreter.eval(PythonInterpreter.java:198)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:40)
... 14 more


于是我们只能求助于java的Runtime.exec()

from java.lang import Runtime
from java.lang import Process
...
...
for line in open(workDir + archiveDir + '/' + directive,'r').readlines():
if not line.startswith("#"):
rt = Runtime.getRuntime()
proc = rt.exec(launch(line))
stdin = proc.getInputStream()
isr = InputStreamReader(stdin)
br = BufferedReader(isr)
while br.readLine() != None:
print br.readLine()


[b]在Jython 2.6以前不支持解压缩方法, 怎么办?[/b]

我们可以借助java来实现


from java.util import ArrayList
from java.util.zip import ZipInputStream
from java.lang import String
from java.io import FileInputStream
from java.io import File

from com.datasynapse.commons.util import FileUtils
from com.datasynapse.commons.util import ZipUtils
...

def doUnzip():
...
sampleDir = File(thc.getStringVariableValue("ENGINE_WORK_DIR") + "/samples/archives")
files = FileUtils.getFileList(sampleDir, ["zip"], 0) #Jython中[""]代表字符串数组, 0代表boolean中的false, true是非零值
for f in files:
zip = ZipInputStream( FileInputStream(f))
try:
ZipUtils.zipStreamToDir(zip, sampleDir)
except IOError:
print 'cannot open', zip
else:
zip.close()
print "zip in doInstall extracted"


[b]python中没有main函数, 想测试怎么办?[/b]

python没提供main函数, 但是可以用__name__属性代替.
#test.py
def foo():
str="foo method"
print(str)

def bar():
foo()

if __name__=="__main__":
print("main")
bar()


其中if __name__=="__main__":这个程序块类似与Java或C语言的中main函数

在cmd中运行结果
>python test.py
main
foo method

在Python Shell中运行结果
>>> import test
>>> test.foo()
foo method
>>> hello.__name__
'test'
>>>

这时内置属性__name__自动的发生了变化。当我们以单个文件运行时,__name__便是__main__, 当我们以模块导入使用时,这个__name__属性便是这个模块的名字。


[b]Python没有Java中的Properties类, 如何生成?[/b]

当然在Jython中可以导入Properties类来用, 那么在Python中如何生成Propertie文件呢, 我们可以借用dictionary来完成

container = proxy.getContainer()
thInstanceName = File(container.getStringVariableValue("ENGINE_WORK_DIR")).getName()
amxAdminMachineIp = container.getStringVariableValue("AMX_ADMIN_MACHINE_IP")
adminConnPort = container.getStringVariableValue("admin_external_http_port_base")
adminURL = "http\://" + amxAdminMachineIp + "\:" + adminConnPort
username = container.getStringVariableValue("username")
password = container.getStringVariableValue("password")
httpConnectionTimeout = "360000"
properties = open(container.getStringVariableValue("ENGINE_WORK_DIR") +'/samples/archives/remote_props.properties', 'w')
lines = {
'adminURL':adminURL,
'hostname':thInstanceName,
'username':username,
'password':password,
'httpConnectionTimeout':httpConnectionTimeout}

serverHttpsEnabled = container.getStringVariableValue("secure_admin_http").lower()
emsSslEnabled = container.getStringVariableValue("secure_ems_channel").lower()
if serverHttpsEnabled == 'true' or emsSslEnabled == 'true':
truststoreDir = container.getStringVariableValue("ENGINE_WORK_DIR") + '/fabric/truststore'
if os.path.exists(truststoreDir) and os.path.isdir(truststoreDir) and len(os.listdir(truststoreDir)) > 0:
for file in os.listdir(truststoreDir):
truststoreFile = os.path.join(truststoreDir, file)
print truststoreFile
else:
raise Exception,'An available truststore must be provided.'
truststoreType = container.getStringVariableValue("truststore_type")
truststorePassword = container.getStringVariableValue("truststore_password")

lines['truststoreFile'] = truststoreFile
lines['truststoreType'] = truststoreType
lines['truststorePassword'] = truststorePassword

for key in lines:
properties.write(key + '=' + lines[key] + '\n')
properties.close()


运行结果会在D:\build\fabric\DSEngine\work\yangxiaoming-lt-3\samples\archives下生成remote_props.properties, 在没有设置ssl的情况, 内容如下:

username=root2
httpConnectionTimeout=360000
hostname=yangxiaoming-lt-3
adminURL=http\://192.168.67.169\:8122
password=#!xNKGafZyNDZjYmeENRKiaw==


[b]如何读取java properties文件?[/b]

path是properties文件的路径, key是要加载的key, return a[1]就是这个key对应的值.

def getVal(path, key):
file = open(path + '/build.properties')
keyPair = "nonempty"
while (keyPair != ""):
keyPair = file.readline()
if (keyPair.startswith(key)):
a = keyPair.split("=")
print a[1]
file.close()
return a[1]



[b]在Jython调用java, 但Jython中没有很多java支持的特性, 很多java的语法没办法移植到Jython中, 怎么办?[/b]

如果完全把java代码转换为Jython, 首先是两者语法有很大的区别, 如果只要求在jython中调用java, 其实完全可以重构一下java代码, 把jython不支持的语法封装在.java内部, 对Jython公开一些以整性, 字符串,为参数的方法. 这样可以完美的共同运行.

更多Jython和Java的语法对应表, 可以参考这里[url]http://www.ibm.com/developerworks/cn/education/java/j-jython2/section13.html[/url]

[url]http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html[/url]


[b]如何在Jython中构造java数组?[/b]

需要求助一个jython对象jarray,


from jarray import array

...
...

params = GovObjFilterQueryParams();
inputProperties = GovObjInputProps();

props01 = GovObjInputProp();
props = array([props01], GovObjInputProp);

aggregates01 = GovObjAggregates();

aggregatesInputs01 = GovObjAggregateInput();
aggregatesInputs = array([aggregatesInputs01], GovObjAggregateInput);

qNameDesc01 = QNameDesc();
qNameDesc01.setLocalPart("Total");
qNameDesc01.setNamespace(TNS);
aggregatesInputs01.setName(qNameDesc01);

props01.setPropertyName("requestsProcessed");
aggregates01.setAggregates(aggregatesInputs);
props01.setAggregates(aggregates01);

inputProperties.setProps(props);

params.setInputProperties(inputProperties);



[b]如何在jython中发soap request?[/b]

jython目前没有web service framework, 如果想写jython客户端来调web service, 不得不先用java的framework, 像axis2, CXF生成的代理类, 把这些代理类封装成输入输出简单的方法供jython调用.

如果不想依赖java的web service framework,只能用httplib这用原始方法来设置http header, body.拿到response后把soap当成string来解析. 当然这用方式有一定局限性.只适用于解析简单的resposne, request里的参数也不能经常变化.

下面是一个例子,

import httplib
from java.lang import Double


def getStatistic(statName):

global hostname
global port
global url

hostname = "192.168.67.169"
port = 8120
url ="/mcr.httpbasic/services/GovObjStatsService"

requestBody = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.stats.mcr.governance.tibco.com" xmlns:xsd="http://query.api.stats.mcr.governance.tibco.com/xsd" xmlns:xsd1="http://desc.api.govobj.common.governance.tibco.com/xsd" xmlns:xsd2="http://types.core.api.admin.amf.tibco.com/xsd" xmlns:xsd3="http://query.api.filter.govobj.common.governance.tibco.com/xsd"><soapenv:Header/><soapenv:Body><api:getGovernedObjectStatsByFilters><api:govObjFilterQueryParams><xsd:inputProperties><xsd:props><xsd:aggregates><xsd:aggregates><xsd:name><xsd1:localPart>Total</xsd1:localPart><xsd1:namespace>http://tns.tibco.com/governance/common/govdomain/tibco/amx3</xsd1:namespace></xsd:name></xsd:aggregates></xsd:aggregates><xsd:isProperty>false</xsd:isProperty><xsd:propertyName>responsesOut</xsd:propertyName></xsd:props></xsd:inputProperties><xsd:timeframe><xsd:name>1 Hour Sliding Window</xsd:name></xsd:timeframe><xsd:type><xsd1:localPart>Application</xsd1:localPart><xsd1:namespace>http://tns.tibco.com/governance/common/govdomain/tibco/amx3</xsd1:namespace></xsd:type><xsd:typeFilter><xsd3:nameFilters><xsd3:name>jv.helloworld1.soa</xsd3:name></xsd3:nameFilters><xsd3:type><xsd1:localPart>Application</xsd1:localPart><xsd1:namespace>http://tns.tibco.com/governance/common/govdomain/tibco/amx3</xsd1:namespace></xsd3:type></xsd:typeFilter></api:govObjFilterQueryParams></api:getGovernedObjectStatsByFilters></soapenv:Body></soapenv:Envelope>'

hcon = httplib.HTTPConnection(hostname,port)
hcon.request("POST",url, requestBody, {"SOAPAction":"urn:getGovernedObjectStatsByFilter","Authorization":"Basic cm9vdDp0"})
resp = hcon.getresponse()
responseBody = resp.read()

statRegion = responseBody.split("<ax21025:name>jv.helloworld1.soa</ax21025:name>")[1].split("</ax21025:outputProperties>")[0]

statVal = statRegion.split("<ax21025:propertyValue>")[1].rsplit("</ax21025:propertyValue>")[0]
if statVal !="":
statVald = Double.parseDouble(statVal)
else:
statVald = 0
print statVald
hcon.close()

return statVald
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值