是否可以从Java检查给定文件/字符串的正确python语法(Is it possible to check for correct python syntax of a given file/string from Java)

我正在用java编写一段代码,这部分代码处理python代码。 我只是感兴趣,如果有人在运行时检查python代码是否在语法上是正确的。 我实际上并不需要运行python代码,因为我正在编写一个程序,为项目的一部分教学目的生成它的小片段。

使用系统命令是实现这一目的的唯一方法吗?

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?

最满意答案

这可以通过Jython完成:

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

如果发现问题会抛出异常(很可能是org.python.core.PySyntaxError )

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)

是否可以从Java检查给定文件/字符串的正确python语法(Is it possible to check for correct python syntax of a given file/string from Java)

我正在用java编写一段代码,这部分代码处理python代码。 我只是感兴趣,如果有人在运行时检查python代码是否在语法上是正确的。 我实际上并不需要运行python代码,因为我正在编写一个程序,为项目的一部分教学目的生成它的小片段。

使用系统命令是实现这一目的的唯一方法吗?

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?

最满意答案

这可以通过Jython完成:

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

如果发现问题会抛出异常(很可能是org.python.core.PySyntaxError )

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)