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.
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With