- 1 year ago
Python windows task to run with admin
To create a Windows scheduled task that runs a Python script with administrative privileges, you can use the built-in Windows Task Scheduler. Here's a step-by-step guide to setting up the scheduled task:
Create a Python Script:
First, create the Python script that you want to run with administrative privileges. Save the script with a.py
extension in a location where it can be easily accessed.For example, create a Python script named
example_script.py
with the following content:pythonimport os
def main():
print("Hello from the Python script!")
if __name__ == "__main__":
main()
Create the Scheduled Task:
Now, open the Windows Task Scheduler to create the scheduled task:- Press
Win + R
, typetaskschd.msc
, and press Enter to open the Task Scheduler.
- Press
Create Basic Task:
In the Task Scheduler window, click on "Create Basic Task" in the right-hand Actions pane.Name and Description:
Enter a name and optional description for the task, and click "Next."Trigger:
Select the appropriate trigger for when you want the task to run (e.g., daily, weekly, at log on, etc.). Follow the on-screen instructions to set the trigger details, and click "Next."Action:
Choose "Start a program" as the action, and click "Next."Program/Script:
Browse and select the Python executable (usually located inC:\PythonXX\python.exe
, whereXX
is the version number).Add Arguments (Optional):
In the "Add arguments (optional)" field, provide the path to your Python script. For example, if the script is located inC:\path\to\example_script.py
, you would enter:vbnetC:\path\to\example_script.py
Start in (Optional):
In the "Start in (optional)" field, enter the directory where your Python script is located. For example, if the script is inC:\path\to
, enter:vbnetC:\path\to
This step is important as it ensures that the script can access files in its working directory.
Finish:
Review your settings, and click "Finish" to create the scheduled task.Set Task to Run with Highest Privileges:
After the task is created, find it in the Task Scheduler Library, right-click on it, and select "Properties." In the "Properties" window, go to the "General" tab and check the "Run with highest privileges" checkbox. This will ensure that the task runs with administrative privileges.
With these steps, you have set up a Windows scheduled task that will run your Python script with administrative privileges at the specified trigger times. The task will run the Python script, and the output will be visible in the console window if your script generates any output or error messages.