Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 648
Mike Pennington Avatar asked Jun 27 '12 12:06

Mike Pennington


People also ask

What is while () in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don't know the number of times to iterate beforehand.

Which is better for or while in Python?

The for statement iterates through a collection or iterable object or generator function. The while statement simply loops until a condition is False. It isn't preference. It's a question of what your data structures are.

Can a while loop have two conditions Python?

Python While Loop Multiple Conditions. To combine two conditional expressions into one while loop, you'll need to use logical operators. This tells Python how you want all of your conditional expressions to be evaluated as a whole.


1 Answers

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 bash - I am not sure...

like image 171
glglgl Avatar answered Oct 22 '22 10:10

glglgl