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

前端 未结 8 1040
长发绾君心
长发绾君心 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 14:56
    import sys
    filename = sys.argv[1]
    source = open(filename, 'r').read() + '\n'
    compile(source, filename, 'exec')
    

    Save this as checker.py and run python checker.py yourpyfile.py.

    0 讨论(0)
  • 2020-11-29 14:57

    You can check the syntax by compiling it:

    python -m py_compile script.py
    
    0 讨论(0)
  • 2020-11-29 14:59

    You can use these tools:

    • PyChecker
    • Pyflakes
    • Pylint
    0 讨论(0)
  • 2020-11-29 15:03

    for some reason ( I am a py newbie ... ) the -m call did not work ...

    so here is a bash wrapper func ...

    # ---------------------------------------------------------
    # check the python synax for all the *.py files under the
    # <<product_version_dir/sfw/python
    # ---------------------------------------------------------
    doCheckPythonSyntax(){
    
        doLog "DEBUG START doCheckPythonSyntax"
    
        test -z "$sleep_interval" || sleep "$sleep_interval"
        cd $product_version_dir/sfw/python
        # python3 -m compileall "$product_version_dir/sfw/python"
    
        # foreach *.py file ...
        while read -r f ; do \
    
            py_name_ext=$(basename $f)
            py_name=${py_name_ext%.*}
    
            doLog "python3 -c \"import $py_name\""
            # doLog "python3 -m py_compile $f"
    
            python3 -c "import $py_name"
            # python3 -m py_compile "$f"
            test $! -ne 0 && sleep 5
    
        done < <(find "$product_version_dir/sfw/python" -type f -name "*.py")
    
        doLog "DEBUG STOP  doCheckPythonSyntax"
    }
    # eof func doCheckPythonSyntax
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-29 15:16

    Pyflakes does what you ask, it just checks the syntax. From the docs:

    Pyflakes makes a simple promise: it will never complain about style, and it will try very, very hard to never emit false positives.

    Pyflakes is also faster than Pylint or Pychecker. This is largely because Pyflakes only examines the syntax tree of each file individually.

    To install and use:

    $ pip install pyflakes
    $ pyflakes yourPyFile.py
    
    0 讨论(0)
提交回复
热议问题