Como posso verificar a sintaxe do script Python sem executá-lo?

costumava usar perl -c programfile para verificar a sintaxe de um programa Perl e depois sair sem o executar. Existe uma maneira equivalente de fazer isso para um script Python?

Author: Eugene Yarmash, 2010-11-26

5 answers

Pode verificar a sintaxe compilando-a:

python -m py_compile script.py
 456
Author: Mark Johnson, 2011-12-08 22:57:30

Pode utilizar estas ferramentas:

 48
Author: user225312, 2016-06-14 04:50:53
import sys
filename = sys.argv[1]
source = open(filename, 'r').read() + '\n'
compile(source, filename, 'exec')

Guarde isto como checker.py e corre.

 14
Author: Rosh Oxymoron, 2014-08-22 21:37:38

Talvez útil checker Online PEP8 : http://pep8online.com/

 6
Author: a_shahmatov, 2015-09-10 09:22:19
Por alguma razão , sou um novato... ) the-M call não funcionou ... Então aqui está um func de embalagem de bash ...
# ---------------------------------------------------------
# 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
 1
Author: Yordan Georgiev, 2016-12-27 11:04:30