On 9/19/2012 8:27 AM, David Smith wrote:
but not:
print('hi');if 1: print('hi')
Chokes on the 'if'. On the surface, this is not consistent.
Yes it is. ; can only be followed by simple statements. The keyword for
compound statememts must be the first non-indent token on a line. That
is why I suggested at the beginning of the thread to insert '\n',
stating correctly that it works for exec().
>>> exec("print('hi');if 1: print('hi')")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
exec("print('hi');if 1: print('hi')")
File "<string>", line 1
print('hi');if 1: print('hi')
^
SyntaxError: invalid syntax
>>> exec("print('hi');\nif 1: print('hi')")
hi
hi
>>> exec("print('hi')\nif 1: print('hi')")
hi
hi
Someone raised the issue of whether the bat interpreter passes along the
quoted string unchanged or if it interprets '\' or '\n' itself and in
the latter case whether one to do anything so that python will see '\n'
after any fiddling by the bat interpreter. It seems that \ is not
interpreted within strngs by bat, but the problem is that the string is
then seen by python as code, not as a string literal, and so python does
not 'cook' it either. Running tem.bat from a command line (which echoes
line from .bat), so I see the output, I get (Win7)
C:\Programs\Python33>python -c "print(1)\nif 1: print(2)"
File "<string>", line 1
print(1)\nif 1: print(2)
^
SyntaxError: unexpected character after line continuation character
One gets the same response interactively from
>>> print('hi')\nif 1: print('hi')
or
>>> exec("print('hi')\\nif 1: print('hi')")
The fix is to quote and pass the exact code that worked above in the
python shell, keeping in mind that the outer quotes must be the double
quote characters recognized by windows.
C:\Programs\Python33>python -c "exec('print(1)\nif 1: print(2)')"
1
2
I did check that windows % interpolation of .bat args works within ''
quoted strings. Change tem.bat to
python -c "exec('print(%1)\nif 1: print(2)')"
and calling 'tem 3' prints
3
2
That said, if you have many multiline statements, putting them in a
separate file or files may be a good idea.
--
Terry Jan Reedy
--
http://mail.python.org/mailman/listinfo/python-list