2

I am writing a piece of code in java, part of this code deals with handling python code. I was just interested if anyone has come across a way of checking if the python code is syntactically correct during runtime. I don't actually need to run the python code, as i'm writing a program that generates small snippets of it for teaching purposes as part of a project.

Is using a system commands the only way to achieve this?

2
  • You could perhaps use Jython but I'm not sure that's actually lighter than running Python instance. Commented Jan 12, 2014 at 20:28
  • I think system commands is the way to go either way since it does all the work for you. Syntax checking is heavy work Commented Jan 12, 2014 at 20:31

1 Answer 1

2

For Python 2, this can be done with Jython:

new org.python.util.PythonInterpreter().compile("python code here")

and an exception will be thrown if it finds a problem (likely org.python.core.PySyntaxError)

Sign up to request clarification or add additional context in comments.

6 Comments

This works well, exactly the kind of solution i was hoping exists (didn't want any depencies which couldn't be compiled into the jar), you have my thanks.
This works but sometime Jython throws syntax error for code that already works in Python.
@Neelesh is your code Python 3? Jython only supports Python 2.
No its not python 3 code. It fails in case of dictionary comprehension.
@Neelesh interesting, what was the dictionary comprehension you tried? I just tried d = {x: y for x, y in [(1, 2), (3, 4)]} and it didn't throw a syntax error for me. If yours works in CPython 2 but not Jython, you might also want to ask a question directly about that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.