9

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 "<string>", 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 "<string>", 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.

Mike Pennington
  • 41,899
  • 19
  • 136
  • 174

4 Answers4

10
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...

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • 1
    `os.system()` is obviously not canonical, but I've found that shorter questions are better on [so]. `os` is shorter than `subprocess` – Mike Pennington Jun 27 '12 at 12:46
  • If it was just supposed to be an example, `print 1234` (or `print(1234)`) would have been enough as well. But that's not the main pont of this all... – glglgl Jun 27 '12 at 13:10
5

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?

unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • @MikePennington: If it's a one-time use, why don't you launch the interpreter and enter the commands there? – Sven Marnach Jun 27 '12 at 12:46
  • shell redirection and pipes, somewhat easier `bash` up-arrow editing if I make a mistake... and I'm still hooked on `perl -e` syntax from years of perl usage – Mike Pennington Jun 27 '12 at 13:06
2

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')"
unkulunkulu
  • 11,576
  • 2
  • 31
  • 49
2

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)

Gerrat
  • 28,863
  • 9
  • 73
  • 101