How can I check the syntax of Python script without executing it?

前端 未结 8 1067
长发绾君心
长发绾君心 2020-11-29 14:17

I used to use perl -c programfile to check the syntax of a Perl program and then exit without executing it. Is there an equivalent way to do this for a Python s

8条回答
  •  心在旅途
    2020-11-29 15:12

    Here's another solution, using the ast module:

    python -c "import ast; ast.parse(open('programfile').read())"
    

    To do it cleanly from within a Python script:

    import ast, traceback
    
    filename = 'programfile'
    with open(filename) as f:
        source = f.read()
    valid = True
    try:
        ast.parse(source)
    except SyntaxError:
        valid = False
        traceback.print_exc()  # Remove to silence any errros
    print(valid)
    

提交回复
热议问题