Is there any way in Python to keep it system active all the time?
-
i think you can use some windows api to send messages like 'activate window' to the process. – Lei Yang Feb 08 '22 at 06:25
-
can you share those api ? – Devil Feb 08 '22 at 06:29
8 Answers
Best way For Windows without Python
copy the below code and save the file as .ps1 extension
After saving file, Right click on it and select Run With PowerShell
Clear-Host
Echo "toggling scroll lock"
$WShell = New-Object -com "Wscript.Shell"
while ($true) {
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Milliseconds 200
$WShell.sendkeys("{SCROLLLOCK}")
Start-Sleep -Seconds 350
}

- 1,054
- 12
- 18
one way worked for me on windows
Python3 Windows
this will keep your windows awake and prevent it from locking/hibernating
#Devil
import ctypes
import sys
#use this to reset the status
def display_reset():
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
sys.exit(0)
def display_on():
print("Always On")
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
display_on()

- 1,054
- 12
- 18
-
Could you please refer below thread: https://stackoverflow.com/questions/2090464/python-window-activation – ChetanSharma-msft Feb 08 '22 at 08:37
-
@Devil - Could you please confirm is your issue resolved or are you still facing the issue? – Nivedipa-MSFT Feb 08 '22 at 10:38
-
@Nivedipa-MSFT : it is solved in windows using above method, still looking for the option to do it in ubuntu18 – Devil Feb 09 '22 at 04:52
-
-
This works for me in Fedora. Just send the main Teams process a SIGUSR1 before the status changes. The script will continue in the background.
#!/bin/bash
signal() {
while sleep 60 ; do
kill ${1} ${2} || exit 0
done
}
PID=$(pgrep -f 'teams.*disable-setuid-sandbox')
[ -z "${PID}" ] && {
echo "${0}: Teams process not found" >&2
exit 1
}
(signal -SIGUSR1 ${PID}&)&

- 1
- 1
Use the Pyautogui library and datetime
Set a loop that will move the mouse and click. Set it to end when an instantiated time variable equals whatever time is applicable. Ctrl/alt/delete when you return to your work station to break the loop
This can effectively keep you active in less than 11 lines of code

- 1
-
Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 04 '22 at 04:00
GUI Application to keep windows active
Python3
install library
pip install pywin32
save below code as alive.pyw
file
from ctypes import windll, wintypes, byref, c_uint, sizeof, Structure
import tkinter as tk
import ctypes
import sys
import threading
import time
import win32api
import win32con
stop_threads = True
SET_IDLE_TIME = 40 #in seconds
tm1 = time.time()
value = 0
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_uint),
]
def get_idle_duration():
global value, tm1
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
windll.user32.GetLastInputInfo(byref(lastInputInfo))
# millis = 4294967 - lastInputInfo.dwTime - windll.kernel32.GetTickCount()
# print(windll.kernel32.GetTickCount(), lastInputInfo.dwTime, sizeof(lastInputInfo), millis)
tm2 = time.time() - tm1
last_idel_time = lastInputInfo.dwTime
# print()
if value != last_idel_time:
value = last_idel_time
tm2 = time.time() - time.time()
tm1 = time.time()
# print("time:", tm1)
return tm2
def press_key_2():
global stop_threads, tm1
while True:
if not stop_threads:
break
idle_time = get_idle_duration() #seconds
# print(idle_time)
g = float("{:.2f}".format(idle_time))
st = str(g) + " / " + str(SET_IDLE_TIME)
var.set(st)
time.sleep(0.1)
if idle_time < SET_IDLE_TIME:
continue
print("in ideal state pressing cltr")
win32api.keybd_event(ord('x'), 0, win32con.KEYEVENTF_EXTENDEDKEY, 0)
tm1 = time.time()
#---------------- Monitor threads ------------------------------
t1 = threading.Thread(target=press_key_2, name='t1')
t1.daemon = True
#----------------- TK functions ----------------------
def display_on():
global tk, t1, stop_threads
stop_threads = True
print("Always On")
ctypes.windll.kernel32.SetThreadExecutionState(0x80000002)
root.iconify()
t1.start()
# t2.start()
def display_reset():
print("quit pressed")
global stop_threads
stop_threads = False
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
sys.exit(0)
root = tk.Tk()
root.geometry("200x110")
root.title("Devil")
frame = tk.Frame(root)
frame.pack()
var = tk.StringVar()
var_idle = tk.StringVar()
label = tk.Label(frame, textvariable = var)#, bd = 5, justify = tk.RIGHT, padx = 10, pady = 10)
label_idle = tk.Label(frame,textvariable = var_idle)
var_idle.set("Idle Time")
var.set("-")
button = tk.Button(frame,
text="Quit",
fg="red",
command=display_reset)
slogan = tk.Button(frame,
text="Always ON",
command=display_on)
label_idle.pack(side=tk.BOTTOM,padx=15, pady=13)
label.pack(side=tk.BOTTOM,padx=15, pady=5)
slogan.pack(side=tk.LEFT,padx=15, pady=5)
button.pack(side=tk.LEFT,padx=15, pady=5)
root.mainloop()
ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)

- 1,054
- 12
- 18
IF you are stepping away from the machine, you can mimic activity with Python, moving your mouse to top left and clicking every n seconds, to cancel simply go to the console, and ctrl + c to exit, you have 5 secs between.
pip3 install pyautogui
import pyautogui, time
def moveToCornerClick(x,y):
"""x,y pixels from top-left"""
pyautogui.moveTo(x, y)
pyautogui.click()
time.sleep(5)
count = 0
while True:
moveToCornerClick(50,150) #y=150 click a little lower on left to avoid hitting other windows toolbar
count+=1
print(f"iteration: {count}")

- 99
- 2
- 6
-
can you suggest something, which don't require continuous mouse movement ? – Devil Nov 16 '22 at 10:16
//Create Windows Form project in Visual Studio using C#
//Make sure this form is in focus while the project is running
using System;
using System.Windows.Forms;
namespace MsTeamsAvailable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(4);
var timer = new System.Threading.Timer((e) =>
{
MyMethod();
}, null, startTimeSpan, periodTimeSpan);
}
private void MyMethod()
{
SendKeys.SendWait("{ENTER}");
}
}
}

- 80
- 6
Just use the latest version free trial of Mouse Jiggle - https://www.mousejiggle.org. It works with Teams & Outlook. Try it out

- 1
-
Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 08 '22 at 13:48
-
That doesn't work in all cases. Teams has to be interacted with for some (i.e., something clicked on in Teams or a key pressed while Teams is the active window). – dsasmblr Sep 08 '22 at 00:00