On Fri, 12 Oct 2012 19:04:20 -0400, Etienne Robillard wrote:

> On Fri, 12 Oct 2012 15:51:19 -0700
> Herman <sorsor...@gmail.com> wrote:
> 
>>  python -c "import os; while True: print('hello')" File "<string>",
>>  line 1
>>  import os; while True: print('hello')
>>                       ^
>> SyntaxError: invalid syntax
>> --
>> http://mail.python.org/mailman/listinfo/python-list
> 
> You get a syntax error since you didn't used tabs indents in your string
> which is normal for python AFAIK.

Incorrect. Python lets you use either spaces or tabs for indents, and in 
this case the SyntaxError is BEFORE the missing indent. He gets 
SyntaxError because you can't follow a semicolon with a statement that 
begins a block. It's the `while` that causes the error, not the lack of 
indent. Here's an example with `if` and an indented block that also 
fails:


[steve@ando ~]$ python -c "pass; pass"
[steve@ando ~]$ python -c "pass; if True:        pass"
  File "<string>", line 1
    pass; if True:       pass
           ^
SyntaxError: invalid syntax


Solution: don't use semi-colons, use newlines.

In this example, I use `Ctrl-Q ENTER` to insert a literal newline in the 
string, which shows as ^M. Note that you *cannot* just type ^ M (caret 
M), that won't work, it must be an actual control character.


[steve@ando ~]$ python -c 'import time^Mwhile True:^M    print("hello"); 
time.sleep(2)'
hello
hello
hello
Traceback (most recent call last):
  File "<string>", line 3, in <module>
KeyboardInterrupt


In this example I just hit the Enter key to insert a newline, and let the 
shell deal with it. The ">" marks are part of the shell's prompt.

[steve@ando ~]$ python -c "import time
> while True:
>     print('hello'); time.sleep(2)"
hello
hello
hello
Traceback (most recent call last):
  File "<string>", line 3, in <module>
KeyboardInterrupt




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to