Python -c and `while`

Is there a way to loop in while if you run the script with python -c ? This is not like the 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 ~]$ 

Window

 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 tried to remove the brackets in the while statement, but does nothing to make this run.

+6
source share
4 answers
 python -c $'import subprocess\nwhile True: subprocess.call(["ls"])' 

(pay attention to $'...' and \n ).

But it is possible that it only works under - I'm not sure ...

+8
source

Multi-line statements may not start after splitting statements ; in Python - otherwise there may be ambiguities regarding blocks of code. Just use line breaks instead ; . This "works" on Linux:

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

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

+4
source

I don't know about windows, if all you need to do is enter single-line characters, you can consider line breaks inside quotes:

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

If you really have to do this on Windows, you can use exec:

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

(I replaced dir , so it works on my windows system)

+1
source

Source: https://habr.com/ru/post/919127/


All Articles