How can I check the syntax of Python script withou

2019-01-07 01:54发布

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 script?

5条回答
smile是对你的礼貌
2楼-- · 2019-01-07 02:08
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.

查看更多
甜甜的少女心
3楼-- · 2019-01-07 02:20

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
查看更多
对你真心纯属浪费
4楼-- · 2019-01-07 02:21

You can use these tools:

查看更多
看我几分像从前
5楼-- · 2019-01-07 02:21

Perhaps useful online checker PEP8 : http://pep8online.com/

查看更多
放我归山
6楼-- · 2019-01-07 02:24

You can check the syntax by compiling it:

python -m py_compile script.py
查看更多
登录 后发表回答