DevOps | Cloud | Analytics | Open Source | Programming





How to Check Syntax Errors in Python Code ?



In this post , we will explore - How to Check Syntax Errors in Python Code. You can use various options to check for any syntax errors in Python without executing the script . Try the below options -

Option 1 - Using Compilation Script :

  • Using Python basic compilation . Use the code below and save it as any .py file e.g pythonSyntaxChecker.py


import sys
your\_python\_script\_name = sys.argv\[1\]
source = open(your\_python\_script\_name, 'r').read() + '\\n'
compile(source, your\_python\_script\_name, 'exec')


  • Next run your Python script(say yourPythonScript.py) against the above script


python3 pythonSyntaxChecker.py yourPythonScript.py
OR
python pythonSyntaxChecker.py yourPythonScript.py


Option 2 - Using Direct Compilation :

  • You can directly compile your Python script
  • Note the below poinst -
    • python returns a non-zero exit code if the compilation fails.
    • Also type errors are not detected -- those are only detected at runtime


python -m py\_compile yourPythonScript.py


Option 3 - Using Pychecker :

  • You can use PyChecker to syntax check your python code. Use code below from the command line:


    pychecker \[options\] YOUR\_PYTHON\_SCRIPT.py


 

  • The [options] provides below features -
    • --only  --> only warn about files passed on the command line
    • -#, --limit --> the maximum number of warnings to be displayed
    • --no-shadowbuiltin --> check if a variable shadows a builtin
    • -q, --stdlib --> ignore warnings from files under standard library
    • -T, --argsused --> unused method/function arguments
 

  • If you want to syntax check multiple Python scripts at one go ,


pychecker <YOUR\_DIR>/\*.py


Sample how pychecker shows the syntax errors -



script1.py:5: Imported module (string) not used
script1.py:6: Instantiating an object with arguments, but no constructor
script1.py:7: Object (useless) has no attribute (valeu)
script1.py:8: No local variable (var1)
script1.py:9: self is not first method argument


Option 4 - Using Pyflakes :

  • Another worthy option to try - https://github.com/PyCQA/pyflakes


pyflakes yourPythonScript.py


Option 5 - Using "ast" module

  • The ast module helps to process trees of the Python abstract syntax grammar - basically ast helps to find out the current grammar appearance.
  • More here - https://docs.python.org/3/library/ast.html
  • Using CLI


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


  • Check syntax of any block of code


import ast
tree = ast.parse("print ('This is Great')")
ast.dump(tree)
"Module(body=\[Expr(value=Call(func=Name(id='print', ctx=Load()), args=\[Str(s='This is Great')\], keywords=\[\]))\])"


  • Alternatively use as a python script


import ast, traceback

g = '<YOUR PYTHON SCRIPT NAME>'
with open(g) as f:
  source = f.read()
valid = True

try:
  ast.parse(source)

except SyntaxError:
  valid = False
  traceback.print\_exc()

finally:
  print(valid)
  ast.dump(source)




Hope this write up was helpful.  

Other Interesting Reads -

 



python syntax check, python syntax, invalid syntax python, python for loop syntax, python if syntax, python, pycharm, django, matplotlib, python online, python programming, python list, learn python, python syntax checker,How do I check Python syntax, How do I check Python syntax online, What is Python basic syntax, What Is syntax check,check python script online,python code tester,how to find error in python code ,pep8 checker,python 3.5 syntax checker,python syntax error,python check function,bug checker python, python syntax checker command line, python 3.5 syntax checker, python syntax error fixer,syntaxerror: invalid syntax python 3,invalid syntax python print,how to resolve name error in python,invalid syntax python def,pylint syntax error,how to find error in python code,file <stdin>'', line 1 syntaxerror: invalid syntax,online python compiler, python find syntax error,How to find syntax error in python,How to solve the python syntax error,What is a syntax error in python,How does Python handle syntax errors,python syntax error,how to find error in python code,python compiler invalid syntax python ,check python script online,python code tester,occurs when a syntax error is raised for a module