1 """Utility to compile possibly incomplete Python source code."""
7 def compile_command(source
, filename
="<input>", symbol
="single"):
8 r
"""Compile a command and determine whether it is incomplete.
12 source -- the source string; may contain \n characters
13 filename -- optional filename from which source was read; default "<input>"
14 symbol -- optional grammar start symbol; "single" (default) or "eval"
16 Return value / exceptions raised:
18 - Return a code object if the command is complete and valid
19 - Return None if the command is incomplete
20 - Raise SyntaxError or OverflowError if the command is a syntax error
21 (OverflowError if the error is in a numeric constant)
25 First, check if the source consists entirely of blank lines and
26 comments; if so, replace it with 'pass', because the built-in
27 parser doesn't always do the right thing for these.
29 Compile three times: as is, with \n, and with \n\n appended. If
30 it compiles as is, it's complete. If it compiles with one \n
31 appended, we expect more. If it doesn't compile either way, we
32 compare the error we get when compiling with \n or \n\n appended.
33 If the errors are the same, the code is broken. But if the errors
34 are different, we expect more. Not intuitive; not even guaranteed
35 to hold in future releases; but this matches the compiler's
36 behavior from Python 1.4 through 1.5.2, at least.
40 It is possible (but not likely) that the parser stops parsing
41 with a successful outcome before reaching the end of the source;
42 in this case, trailing symbols may be ignored instead of causing an
43 error. For example, a backslash followed by two newlines may be
44 followed by arbitrary garbage. This will be fixed once the API
45 for the parser is better.
49 # Check for source consisting of only blank lines and comments
50 for line
in string
.split(source
, "\n"):
51 line
= string
.strip(line
)
52 if line
and line
[0] != '#':
53 break # Leave it alone
55 source
= "pass" # Replace it with a 'pass' statement
57 err
= err1
= err2
= None
58 code
= code1
= code2
= None
61 code
= compile(source
, filename
, symbol
)
62 except SyntaxError, err
:
66 code1
= compile(source
+ "\n", filename
, symbol
)
67 except SyntaxError, err1
:
71 code2
= compile(source
+ "\n\n", filename
, symbol
)
72 except SyntaxError, err2
:
79 except AttributeError:
83 except AttributeError:
85 if not code1
and e1
== e2
:
86 raise SyntaxError, err1