How to execute a shell command in a loop? - Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to execute a shell command in a loop? - Python

I'm having problem to execute a command via os.system("command") in a While True loop because this command never finish his task, so Python doesn't let the second same command run and etc (it's difficult to explain..) So I tried to do the same with os.startfile("\path\file.bath") and It gives me what I want but It creates new windows countinously! To understand better, that's the command that I use: os.system(r"powershell (Add-Type '[DllImport(\"user32.dll\")]^public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)")

11th Mar 2019, 6:05 PM
Giordano Fratti
Giordano Fratti - avatar
4 Answers
+ 1
Giordano Fratti I don't understand powershell commands very well. Can you explain what is the powershel command supposed to do?
11th Mar 2019, 6:49 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 1
It makes your PC go to spleep mode, so your screen will be turned off until you move the mouse or press a key, but as I said before, It does return nothing and if you run It via cmd you can see that It will not print anything like "Operation Complete": for this reason my loop executes only one command ---> because It seems it doesn't quit after what it does :((( Do I make clear?
11th Mar 2019, 8:05 PM
Giordano Fratti
Giordano Fratti - avatar
+ 1
Ok, now I understood what the powershell command does. But why do you want to run it inside a loop? Does it need to run multiple times?
11th Mar 2019, 8:08 PM
Ulisses Cruz
Ulisses Cruz - avatar
+ 1
I want to create a program that switches off/on my laptop screen when I press f11/f12. But as you know, whit that command, if you just move your mouse, your monitor will be switched on. So I created a script (using thread and pynput) that starts and stops a loop when you press those hotkeys: in fact my screen remains black (also if I'm pressing a key) because the script repeatedly runs that command until I choose.
11th Mar 2019, 10:29 PM
Giordano Fratti
Giordano Fratti - avatar