Pythonnet in jython - java

I am trying to execute class and functions written in python from java via jython.
It runs fine until in python we encountered "import clr" which is pythonnet.
Can anyone tell how to run the python scripts from java using jython or any thing else which use "import clr"
python code: file.py
import clr
java code using jython:
Properties props = new Properties();
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.exec("<absoulute_path//file.py>");
Error:
Exception in thread "main" Traceback (most recent call last):
File "<string>", line 3, in <module>
ImportError: No module named clr

Jython does not provide Python C APIs, so there's no way you could build and use Python.NET with it.

Related

Ensuring files are available to the JVM

I'm trying to install TensorFlow for Java on Windows 10 using this Article
. I followed the steps carefully but the windows commands didn't work with me so I decided to do it manually.
The first command is to make the .jar part of the classpath and I did it manually
but the second step was to ensure that the following two files are available to the JVM: the .jar file and the extracted JNI library
but I don't know how to do that manually
The code:
package securityapplication;
import org.tensorflow.TensorFlow;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
public class SecurityApplication {
public static void main(String[] args) throws Exception {
try (Graph g = new Graph()) {
final String value = "Hello from " + TensorFlow.version();
// Construct the computation graph with a single operation, a constant
// named "MyConst" with a value "value".
try (Tensor t = Tensor.create(value.getBytes("UTF-8"))) {
// The Java API doesn't yet include convenience functions for adding operations.
g.opBuilder("Const", "MyConst").setAttr("dtype", t.dataType()).setAttr("value", t).build();
}
// Execute the "MyConst" operation in a Session.
try (Session s = new Session(g);
Tensor output = s.runner().fetch("MyConst").run().get(0)) {
System.out.println(new String(output.bytesValue(), "UTF-8"));
}
}
}
}
could someone help? cuz my program that uses TensorFlow still have the following error
The text in the image is :
Exception in thread "main" java.lang.UnsatisfiedLinkError: Cannot find TensorFlow native library for OS: windows, architecture: x86. See https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java/README.md for possible solutions (such as building the library from source). Additional information on attempts to find the native library can be obtained by adding org.tensorflow.NativeLibrary.DEBUG=1 to the system properties of the JVM.
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.NativeLibrary.load(NativeLibrary.java:66)
at org.tensorflow.TensorFlow.init(TensorFlow.java:36)
at org.tensorflow.TensorFlow.<clinit>(TensorFlow.java:40)
at org.tensorflow.Graph.<clinit>(Graph.java:194)
at securityapplication.SecurityApplication.main(SecurityApplication.java:15) Java Result: 1 BUILD SUCCESSFUL (total time: 4 seconds)
The result after running the first command in cmd:
The result after running the second command in Windows PowerShell:
Any suggestions?!
Thank you
The first command failure (javac) suggests that the javac command is not in your PATH environment variables. See for example, this StackOverflow question
For the second command failure, I believe the space after -D is what is causing you trouble as Holger suggested.
IDEs like Eclipse and others also provide a means to set the java.library.path property for the JVM (see this StackOverflow answer for example).
Background: TensorFlow for Java consists of a Java library (packaged in a .jar file) and a native library (.dll on Windows, distributed in a .zip file). You need to ensure that the .jar file is in the classpath and the directory containing the .dll is in included in the java.library.path of the JVM when executing a program.
Hope that helps.

reportlab in Jython "import error"

I am using jdk 1.8 and Jython 2.7.0.jar to execute my python Code.
But It seems Jython does not support Python's 2.7 feature 'reportlab' module.
My Java Code :
package test;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Test{
public Test()
{
System.out.println("Done!");
engine.eval("import sys");
engine.eval("print sys");
engine.eval("import reportlab");
engine.eval("print reportlab");
System.out.println("Done Here");
}
catch (ScriptException ex)
{
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
public static void main(String args[])
{
Test t=new Test();
}
}
Error I got:
run:
Done!
<module 'sys' (built-in)>
javax.script.ScriptException: ImportError: No module named reportlab in <script> at line number 1
Dec 28, 2015 8:57:52 PM test.Test <init>
SEVERE: null
javax.script.ScriptException: ImportError: No module named reportlab in <script> at line number 1
at org.python.jsr223.PyScriptEngine.scriptException(PyScriptEngine.java:202)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:42)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:31)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at test.Test.<init>(Test.java:28)
at test.Test.main(Test.java:40)
Caused by: Traceback (most recent call last):
File "<script>", line 1, in <module>
ImportError: No module named reportlab
at org.python.core.Py.ImportError(Py.java:328)
at org.python.core.imp.import_first(imp.java:877)
at org.python.core.imp.import_module_level(imp.java:972)
at org.python.core.imp.importName(imp.java:1062)
at org.python.core.ImportFunction.__call__(__builtin__.java:1280)
at org.python.core.PyObject.__call__(PyObject.java:431)
at org.python.core.__builtin__.__import__(__builtin__.java:1232)
at org.python.core.imp.importOne(imp.java:1081)
at org.python.pycode._pyx2.f$0(<script>:1)
at org.python.pycode._pyx2.call_function(<script>)
at org.python.core.PyTableCode.call(PyTableCode.java:167)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1386)
at org.python.core.__builtin__.eval(__builtin__.java:497)
at org.python.core.__builtin__.eval(__builtin__.java:501)
at org.python.util.PythonInterpreter.eval(PythonInterpreter.java:259)
at org.python.jsr223.PyScriptEngine.eval(PyScriptEngine.java:40)
... 4 more
BUILD SUCCESSFUL (total time: 2 seconds)
If anyone could suggest me an Alternate way of remotely executing a Python script I'd be thankful to them.
Also I have a large code base in python of which rewriting in java is not feasible in scheduled time.
Jython is a completely different (and independent) Python interpreter than your system's Python. While most libraries from Python's standard library will exist in Jython, third party modules installed in your system's Python simply don't exist for the Jython version.
Jython is compatible enough that you can set a Python virtualenv with the Jython interpreter and install modules that are pure-python code (i.e. no binary modules) in that virtualenv - I don't think repotlab qualifies as such - but you might try. In a Java project setup, probably your project have its own instance of the Jython interpreter installed along other .jar files - it should feature a site-packages folder somewhere where you could try to copy pure Python third-party modules to, but again, I don't think reportlab will be jython compatible.
One option for you is to use Python itself (cPython) in an external process, and call it from Java (or Jython) using xmlrpc code - (A quickly googling didn't find me out a way to call cPython via xmlrpc from pure Java - but I know it works from Jython, if you use Python's stdlib xmlrpc as documented -
https://docs.python.org/3/library/xmlrpc.html?highlight=xmlrpc
I've got a solution on a stackExchange link - Jython embedded in Java -- ImportError: No module named yaml i.e I can simply add the packages I need under my Jython Installation directory E.g jython/Lib/site-packages I've got no Issues on reportlab for Python2.7.
most Important also append them in your program using sys.path.append()

Eclipse can't find my installed Ruby gems (JRuby)

So, I am trying to use my ruby scripts inside my java code with the help of JRuby. But there is a problem, eclipse is not being able to use the gems I have installed. For testing purposes, I've been trying to run a piece of code that requires the "nokogiri" ruby gem, which I have installed. When I try to run the java code, here's what I get:
LoadError: no such file to load -- nokogiri
require at org/jruby/RubyKernel.java:939
<top> at /home/amng/workspace/scripts/xx/x/getMSPatches:4
Exception in thread "main" org.jruby.embed.EvalFailedException: (LoadError) no such file to load -- nokogiri
at org.jruby.embed.internal.EmbedEvalUnitImpl.run(EmbedEvalUnitImpl.java:131)
at org.jruby.embed.ScriptingContainer.runUnit(ScriptingContainer.java:1307)
at org.jruby.embed.ScriptingContainer.runScriptlet(ScriptingContainer.java:1352)
at jobs.Teste.run(Teste.java:17)
at jobs.Teste.main(Teste.java:11)
Caused by: org.jruby.exceptions.RaiseException: (LoadError) no such file to load -- nokogiri
at org.jruby.RubyKernel.require(org/jruby/RubyKernel.java:939)
at RUBY.(/home/amng/workspace/scripts/myPrecious/MSPatches/getMSPatches:4)
I downloaded the jruby.jar from the website and added to the build path of the project. I also pointed the eclipse to the JRuby binary using the Dynamic Languages Toolkit (DLTK) plugin. What do I have to do to make sure that eclipse can use the gems I have installed?
Edit: My java code:
import org.jruby.embed.ScriptingContainer;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.PathType;
public class Main {
public static void main(String[] args) {
ScriptingContainer ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
Object result = ruby.runScriptlet(PathType.ABSOLUTE, "/home/amng/workspace/scripts/myPrecious/MSPatches/getMSPatches");
System.out.println(result);
}
}
The first two lines of my (working) ruby code (getMSPatches) are:
# encoding: UTF-8
require 'nokogiri'
Try setting the jruby home directory
ScriptingContainer ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
ruby.setHomeDirectory("/jruby-9.0.5.0");
This solved the issue for me.

Executing a Ruby script from Java using JRuby results in 'LoadError: no such file to load ...'

I'd like to execute a Ruby script from Java using JRuby (Linux Mint). I can successfully execute the script from the terminal by calling ruby script.rb. However, the script contains a require that causes "no such file to load" exception when trying to execute it from Java using JRuby:
package com.company;
import org.jruby.embed.LocalVariableBehavior;
import org.jruby.embed.PathType;
import org.jruby.embed.ScriptingContainer;
public class Main
{
public static void main(String[] args)
{
ScriptingContainer ruby;
ruby = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
Object result = ruby.runScriptlet(PathType.ABSOLUTE, "/home/user/Scripts/script.rb");
}
}
The problem seems to be in the require ... part of the script.rb, since this code works fine for e.g. a simple script that only displays text.
The script uses WinRb, a Ruby library for Windows Remote Management. script.rb:
require 'winrm'
endpoint = 'http://somehost.domain.org:5985/wsman'
krb5_realm = 'DOMAIN.ORG'
command = 'hostname'
winrm = WinRM::WinRMWebService.new(endpoint, :kerberos, :realm => krb5_realm)
winrm.cmd(command) do |stdout, stderr|
STDOUT.print stdout
STDERR.print stderr
end
When I run the Java code I get this exception:
LoadError: no such file to load -- winrm
require at org/jruby/RubyKernel.java:940
<top> at /home/user/Scripts/script.rb:5
Exception in thread "main" org.jruby.embed.EvalFailedException:
(LoadError) no such file to load -- winrm
Here's what I tried:
adding require 'rubygems' to the top of the script. This only changes the exception to LoadError: no such file to load -- rubygems
specifying full path: require '/var/lib/gems/1.9.1/gems/winrm-1.3.3/lib/winrm'. Instead of the original exception, at runtime I now get: LoadError: no such file to load -- date
require at org/jruby/RubyKernel.java:940
Other:
$ ruby -v
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]
$ jruby -v
jruby 9.0.0.0 (2.2.2) 2015-07-21 e10ec96 Java HotSpot(TM) 64-Bit Server VM 25.45-b02
How can I get JRuby to execute this script successfully?
The solution is:
jruby -S gem install winrm

"No module named _cairo" using Jython 2.7

I am trying to use python's charting library from my java project using jython. In my script I use module cairo.
pythonInterpreter.exec("import sys");
pythonInterpreter.exec("import cairo");
Exception throws on the second line, because cairo's init.py contains string:
from _cairo import *
The exception I get is:
Caused by: Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/cairo/__init__.py", line 1, in <module>
from _cairo import *
ImportError: No module named _cairo
Also, I can use my script from console, so I doubt that it has an error in it. I suppose something is wrong with the way I'm importing cairo in Java.
I got it now. Jython can't execute 'native' libraries, such as cairo (I'm, sure it's native, because _cairo is a .so file, which means it's a C lib)

Categories

Resources