可能重复:
如何在不执行的情况下检查Python脚本的语法?
如何在不运行的情况下编译Python脚本?我只是想检查脚本的语法错误.我希望有一个简单的命令行开关,但我没有看到任何内容python --help
.我想要Python 2和Python 3的答案.
Python的IDLE有'Check Module'(Alt-X)来检查可以调用的语法而无需运行代码.是否有相同的方法在Emacs中执行此操作而不是运行和执行代码?
转到使用C/Java背景的python,我最近不得不实现相互递归,但python中的某些东西困扰着我:
因为python程序是逐行解释的,如果我在同一个python文件中一个接一个地有两个函数:
def A(n):
B(n-1)
# if I add A(1) here, it gives me an error
def B(n):
if n <= 0:
return
else:
A(n-1)
Run Code Online (Sandbox Code Playgroud)
当解释器正在读取时A
,B
尚未定义,但是此代码不会给我一个错误
TL; DR
我的理解是,当def
被解释,蟒蛇增加了一些本地的名称空间中的条目locals()
有{"function name": function address}
,但作为函数体,它只能做语法检查:
def A():
blabla # this will give an error
def B():
print x # even though x is not defined, this does not give an error
A() # same as above, NameError is only detected during runtime
Run Code Online (Sandbox Code Playgroud) 假设我在Python中有以下代码:
a = "WelcomeToTheMachine"
if a == "DarkSideOfTheMoon":
awersdfvsdvdcvd
print "done!"
Run Code Online (Sandbox Code Playgroud)
为什么不出错?它甚至如何编译?在Java或C#中,这将在编译期间被发现.
我只是想让我的 Python 脚本以最简单的方式询问“我刚刚生成的 Python 代码在语法上是有效的 Python 吗?”
我试过:
try:
import py_compile
x = py_compile.compile(generatedScriptPath, doraise=True)
pass
except py_compile.PyCompileError, e:
print str(e)
pass
Run Code Online (Sandbox Code Playgroud)
但即使文件包含无效的Python,异常也不会抛出,之后x == None
。