Как добавить файл в автозагрузку windows 10 python

Last Updated :
14 Sep, 2021

Adding a Python script to windows start-up basically means the python script will run as the windows boots up. This can be done by two step process –

Step #1: Adding script to windows Startup folder 
After the windows boots up it runs (equivalent to double-clicking) all the application present in its startup directory. 

Address: 

C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\ 
 

By default the AppData folder under the current_user is hidden so enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Also the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing. 

  Step #2: Adding script to windows Registry 
This process can be risky if not done properly, it involves editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry contains the list of programs that must run once the user Login. just like few application which pops up when windows starts because the cause change in registry and add their application path to it.

Registry Path:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

Below is the Python code : 

Python3

import winreg as reg

import os            

def AddToRegistry():

    pth = os.path.dirname(os.path.realpath(__file__))

    s_name="mYscript.py"    

    address=os.join(pth,s_name)

    key = HKEY_CURRENT_USER

    key_value = "Software\Microsoft\Windows\CurrentVersion\Run"

    open = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS)

    reg.SetValueEx(open,"any_name",0,reg.REG_SZ,address)

    reg.CloseKey(open)

if __name__=="__main__":

    AddToRegistry()

Note: Further codes can be added to this script for the task to be performed at every startup and the script must be run as Administrator for the first time.
 

WINDOWS

Learn to make Python scripts run automatically when starting a Windows computer!

Running Python scripts at Windows startup can be incredibly useful for automating tasks, starting background processes, or initializing applications as soon as your computer boots up. In this article, we will cover several methods to achieve this, including adding your scripts to the Startup folder, using Task Scheduler, and employing batch files. We will also explore how to troubleshoot common issues related to running Python scripts on startup.

Understanding the Basics

Before diving into the practical steps, it’s essential to understand where scripts can be configured to run on startup and the implications of each method.

  1. Startup Folder: This is a simple method where you place a shortcut to your Python script in the Windows Startup folder. When the user logs into Windows, the scripts in this folder run automatically.

  2. Task Scheduler: A built-in tool that allows for more advanced configurations, such as running scripts at specific times, after specific events, or under different user accounts.

  3. Batch Files: A .bat or .cmd file can be created to execute your Python script. This file can be placed in the Startup folder or configured to run in the Task Scheduler.

Method 1: Using the Startup Folder

The most straightforward method to run a Python script on startup is to use the Startup folder. Here’s how to do it:

Step-by-Step Guide

  1. Locate the Startup Folder:

    • Press Win + R, type shell:startup, and hit Enter. This will open the Startup folder for your user account.

  2. Create a Shortcut to Your Script:

    • Right-click in the Startup folder, choose New, and select Shortcut.

    • In the location field, enter the path to the Python executable followed by the path to your script. For example:

     C:\Python39\python.exe C:\path\to\your_script.py
    
    • Click Next, name your shortcut, and click Finish.

  3. Test the Setup:

    • Restart your computer and check if your Python script runs automatically upon login.

Method 2: Using Task Scheduler

For more control over when and how your scripts run, the Windows Task Scheduler is a better option. Here’s how to set it up:

Step-by-Step Guide

  1. Open Task Scheduler:

    • Press Win + S, type Task Scheduler, and open it.

  2. Create a New Task:

    • Click on Create Basic Task… in the Actions pane on the right.

    • Name your task and provide a description. For example, “Run Python Script on Startup”.

  3. Set the Trigger:

    • Choose When I log on from the trigger options, then click Next.

  4. Define the Action:

    • Select Start a program and click Next.

    • In the Program/script box, enter the path to your Python executable, e.g.:

    • In the “Add arguments” box, enter the path to your script:

     C:\path\to\your_script.py
    
  5. Finish and Test:

    • Click Finish to save the task. Restart your computer to see if it works as expected.

Method 3: Using a Batch File

If you want to run multiple commands along with your Python script or simply prefer to work with batch files, this method is suitable.

Step-by-Step Guide

  1. Create a Batch File:

    • Open Notepad or any text editor.

    • Write the following lines and modify the paths as needed:

     @echo off
     C:\Python39\python.exe C:\path\to\your_script.py
    
    • Save the file with a .bat extension, e.g., run_script.bat.

  2. Place in Startup Folder:

    • Move or copy the .bat file to the Startup folder (refer to the Startup Folder method above).

  3. Test:

    • Restart and check if the batch file executes your Python script.

Troubleshooting Common Issues

  1. Script Not Running:

    • Ensure the paths to Python and your script are correct.

    • Verify that your script does not require user input or interactive GUI as it may not work in non-interactive sessions.

  2. Permission Issues:

    • If your script requires admin privileges, consider creating the task in Task Scheduler with the “Run with highest privileges” option.

  3. Logging Output:

    • To log outputs for debugging, modify your Python script to write output to a log file. For example:

     with open('log.txt', 'a') as f:
         f.write('Your output here\n')
    

Conclusion

Running Python scripts at startup on a Windows machine can enhance productivity by automating important tasks. Whether you choose to utilize the Startup folder, Task Scheduler, or a batch file, each method has its benefits. By following this guide, you can ensure your scripts run smoothly every time you log on to your Windows computer. Make sure to test thoroughly and troubleshoot any issues you encounter to maintain a seamless experience. Happy coding!

Suggested Articles

WINDOWS

WINDOWS

WINDOWS

WINDOWS

WINDOWS

WINDOWS

Как создать ярлык программы с «тихим» запуском?
Там есть пример добавления в автозагрузку. Вам потребуется создать отдельный скрипт, который добавит Ваш основной скрипт в автозагрузку.

UPD, Добавление программы в автозагрузки в regedit на python:

import winreg

# Добавляем в автозагрузку
def add_to_startup(program_name, executable_path):
    # Реестр
    registry_path = winreg.HKEY_CURRENT_USER
    key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
    
    try:
        # Открываем ключ реестра для записи
        with winreg.OpenKeyEx(registry_path, key_path, 0, winreg.KEY_WRITE) as registry_key:
            # Создание или обновление реестра
            winreg.SetValueEx(registry_key, program_name, 0, winreg.REG_SZ, executable_path)
        print(f"{program_name} добавлена в автозагрузку.")
        
    except PermissionError:
        print("Нужны админские права.")
        
# Проверка программы в автозагрузке
def check_startup_entry(program_name):
    registry_path = winreg.HKEY_CURRENT_USER
    key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run'
    
    try:
        # Открываем ключ реестра для чтения
        with winreg.OpenKeyEx(registry_path, key_path, 0, winreg.KEY_READ) as registry_key:
            program_path, regtype = winreg.QueryValueEx(registry_key, program_name)
        print(f"{program_name} уже добавлена в автозагрузку с путем: {program_path}")
        
    except FileNotFoundError:
        print(f"{program_name} не найдена в автозагрузке.")

if __name__ == "__main__":
    program_name = "GodzillaSoft"
    program_path = r"C:\path\GodzillaSoft.exe"
    
    check_startup_entry(program_name)
    add_to_startup(program_name, program_path)

Важно! Добавление программы в автозагрузку без явного согласия пользователя может считаться вредоносным действием. А так же, осторожнее с реестром, можно одним запуском скрипта наломать много дров…

Распознавание голоса и речи на C#

UnmanagedCoder 05.05.2025

Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .

Реализация своих итераторов в C++

NullReferenced 05.05.2025

Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .

Разработка собственного фреймворка для тестирования в C#

UnmanagedCoder 04.05.2025

C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .

Распределенная трассировка в Java с помощью OpenTelemetry

Javaican 04.05.2025

Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .

Шаблоны обнаружения сервисов в Kubernetes

Mr. Docker 04.05.2025

Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .

Создаем SPA на C# и Blazor

stackOverflow 04.05.2025

Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .

Реализация шаблонов проектирования GoF на C++

NullReferenced 04.05.2025

«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .

C# и сети: Сокеты, gRPC и SignalR

UnmanagedCoder 04.05.2025

Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .

Создание микросервисов с Domain-Driven Design

ArchitectMsa 04.05.2025

Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .

Многопоточность в C++: Современные техники C++26

bytestream 04.05.2025

C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .

Главная страница » Автозапуск программ на python

Автор Admin На чтение 1 мин Просмотров 853 Опубликовано

Автозапуск программ на python

Автозапуск программ на python. В видео разберём, как добавить программу написанную на python и не только в автозагрузку.

Мой Telegram канал

Admin

Профили автора

Добавить комментарий

Имя *

Email *

Комментарий

Сохранить моё имя, email и адрес сайта в этом браузере для последующих моих комментариев.

Вам также может понравиться

Работа в Word с помощью Python

В видео научимся работать в Word с помощью Python.

0687

Расшифровка хэша md5 с помощью python

В видео научимся расшифровывать хэш md5 с помощью python.

0681

Добавление текста на изображение с помощью python opencv

В видео научимся добавлять текст на изображения с помощью

0505

Определитель лиц на python

В видео научимся получать определять лица на фото с

0592

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Включение службы восстановления системы windows 7
  • Отключить windows 11 insider preview
  • Как отключить отключение монитора windows 10
  • Как дать общий доступ к принтеру в windows xp
  • Создать ftp server windows 2003