简体   繁体   English

是否可以从 Java 检查给定文件/字符串的正确 python 语法

[英]Is it possible to check for correct python syntax of a given file/string from Java

I am writing a piece of code in java, part of this code deals with handling python code.我正在用java编写一段代码,这段代码的一部分涉及处理python代码。 I was just interested if anyone has come across a way of checking if the python code is syntactically correct during runtime.我只是对是否有人遇到过一种在运行时检查 python 代码在语法上是否正确的方法感兴趣。 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.我实际上并不需要运行 python 代码,因为我正在编写一个程序,该程序生成它的小片段,作为项目的一部分用于教学目的。

Is using a system commands the only way to achieve this?使用系统命令是实现这一目标的唯一方法吗?

For Python 2, this can be done with Jython :对于 Python 2,这可以通过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 )如果发现问题(可能是org.python.core.PySyntaxError ),则会抛出异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM