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…
[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 ~]$

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


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


Solution 1:

python -c $'import subprocess\nwhile True:["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):

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)