View Full Version : [Pyton] Controllo sintassi di uno script Python
Salve ragazzi, c'č un modo per controllare la correttezza sintattica di uno script pyton senza che venga eseguito?
Esempio:
#! /usr/bin/env python
print 39
istruzione sbagliata
print 40
Vorrei che mi segnalasse l'errore "istruzione sbagliata" senza perņ eseguire la print 39.
Grazie a tutti!
cdimauro
04-11-2009, 13:37
Puoi provare con la funzione built-in compile:
compile( string, filename, kind[, flags[, dont_inherit]])
Compile the string into a code object. Code objects can be executed by an exec statement or evaluated by a call to eval(). The filename argument should give the file from which the code was read; pass some recognizable value if it wasn't read from a file ('<string>' is commonly used). The kind argument specifies what kind of code must be compiled; it can be 'exec' if string consists of a sequence of statements, 'eval' if it consists of a single expression, or 'single' if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something else than None will be printed).
When compiling multi-line statements, two caveats apply: line endings must be represented by a single newline character ('\n'), and the input must be terminated by at least one newline character. If line endings are represented by '\r\n', use the string replace() method to change them into '\n'.
The optional arguments flags and dont_inherit (which are new in Python 2.2) control which future statements (see PEP 236) affect the compilation of string. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile. If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it - the future statements in effect around the call to compile are ignored.
Future statements are specified by bits which can be bitwise or-ed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module.
Basta che gli passi la stringa o il nome del file da compilare, e vedere se genera un'eccezione.
vBulletin® v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.