python -c and `while`

python -c and `while`

Is there a way to loop in while if you start the script with python -c? This doesn’t seem to be related to platform or python version…
Linux
[mpenning@Hotcoffee ~]$ python -c “import os;while (True): os.system(‘ls’)”
File ““, line 1
import os;while (True): os.system(‘ls’)
^
SyntaxError: invalid syntax
[mpenning@Hotcoffee ~]$
[mpenning@Hotcoffee ~]$ python -V
Python 2.6.6
[mpenning@Hotcoffee ~]$ uname -a
Linux Hotcoffee 2.6.32-5-amd64 #1 SMP Sun May 6 04:00:17 UTC 2012 x86_64 GNU/Linux
[mpenning@Hotcoffee ~]$

Windows
C:\Users\mike_pennington>python -c “import os;while True: os.system(‘dir’)”
File ““, line 1
import os;while True: os.system(‘dir’)
^
SyntaxError: invalid syntax

C:\Users\mike_pennington>python -V
Python 2.7.2

C:\Users\mike_pennington>

I have tried removing parenthesis in the while statement, but nothing seems to make this run.

Solutions/Answers:

Solution 1:

python -c $'import subprocess\nwhile True: subprocess.call(["ls"])'

would work (note the $'...' and the \n).

But it could be that it only works under – I am not sure…

Solution 2:

Multiline statements may not start after a statement-separating ; in Python – otherwise, there might be ambiguities about the code blocks. Simply use line breaks in stead of ;. This “works” on Linux:

$ python -c "import os
while True: os.system('ls')"

Not sure how to enter this on Windows, but why not simply write the commands to a .py file if it’s more than one line?

Solution 3:

Don’t know about windows, if all you want is to be able to type in one-liners, you could consider line breaks inside quotes:

% python -c "import os;
while (True):
  os.system('ls')"

Solution 4:

If you really must do this in windows, you could use exec:

python -c "exec \"import os;\rwhile True:\r  os.system('dir')\""

(I substituted dir so it works on my windows system)

Related:  Find which assembly instruction caused an Illegal Instruction error without debugging

References