i last did this long ago and forgot how to do it. was it a python command option? i want to compile a script without running it to check for any obvious syntax errors. if it produces a .pyc file, that is OK. if producing a .pyc file, without running, is different, i'd also like to know how to do that. if these are platform specific, i am running on POSIX (Xubuntu 20.04 LTS). i can't find this in the python man page. maybe there was a script that did this.
Interesting. The function
compile
can compile a python source file, but it detects only
SyntaxErrors
.
My test:
from pathlib import Path
for file in Path().rglob("*.py"):
if file.is_file():
try:
compile(file.read_text(), file, "exec")
except SyntaxError:
print(f"[fail] {file.name}")
except Exception as e:
print("Exception {e} were thrown.")
else:
print(f"[ ok ] {file.name}")
Or you can look into the source code of the module compileall, which compiles everything inclusive the Python-Stdlib.
The outcome:
Quote:[ ok ] adc.py
[ ok ] c.py
[ ok ] kk.py
If there was a SyntaxError, it would print fail.
Lesson lerned, compilng code, does not runtime checks.
Content of kk.py:
t = (1,2)
t[0] = 10
Executing the code will raise a
TypeError
. A tuple does not support item assignment.
The tool
ruff check
does not find the error.
With mypy I got this error:
Error:
kk.py:2: error: Unsupported target for indexed assignment ("tuple[int, int]") [index]
Found 1 error in 1 file (checked 1 source file)
You should better use mypy (slow) to do this kind of check. Use ruff check (very fast) to check the Syntax and for some rules.
Do not use mypy, if you're working on a network share. It creates
.mypy_cache
same for ruff, it creates
.ruff_cache
.
Use the standard modules py_compile
and compileall
as scripts to create .pyc files.
You could also use a linter such as ruff of flakes8 but it will also give you warnings about pep8 and your coding style.
As I found this question interesting, I posted a CLI script to check the syntax of Python files. I mostly removed unnecessary parts in the standard library's py_compile module. See
this thread and also
this gist.
i would like to check for every possible error that would have the python command refuse to run the code such as file "kk.py" that DeaD_EyE posted. now i am curious if it would produce .pyc output then refuse to run it. can that code in "kk.py" be represented in .pyc code?