2

actually, i'm new in python. Here, i want to get an output from class of python. but here, i input String from java.

here's the java code:

    String word;
    Scanner in = new Scanner(System.in);
    System.out.println("input: ");
    word = in.nextLine();

    TryinPythonToJavaAgain ie = new TryinPythonToJavaAgain();
    ie.execfile("~\\hello.py");

    PyInstance hello = ie.createClass("Hello", word);
    hello.invoke("run");

python code:

class Hello:

def __init__(self, abc):
    self.abc  = abc

def run(self):
    print(self.abc)

if i input : "hello" i have an error like this:

input: hello Exception in thread "main" Traceback (most recent call last): File "", line 1, in NameError: name 'hello' is not defined Java Result: 1

and if i input >2 word (e.g "hello world"), i have an error like this:

input: hello world Exception in thread "main" SyntaxError: ("no viable alternative at input 'world'", ('', 1, 12, 'Hello(hello world)\n')) Java Result: 1

what should i fix in this code? thanks

Mrsdiindi
  • 21
  • 1

1 Answers1

0

If the code in your createClass method looks anything like this ...

PyInstance createClass( final String className, final String opts )  
{  
    return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");  
}

... then I think you need to add quotes round the opts variable. The code above is from here which works since "None" gets turned into this.interpreter.eval(className(None)) which is valid whereas yours becomes this.interpreter.eval(className(hello world)) which isn't.

I've not tried it, but this.interpreter.eval(className("hello world")) would seem more likely to work.

Community
  • 1
  • 1
Jeremy Gosling
  • 1,130
  • 10
  • 11