Как запускать скрипт python при запуске windows

I have a python file and I am running the file. If Windows is shutdown and booted up again, how I can run that file every time Windows starts?
import winreg

def set_autostart_registry(app_name, key_data=None, autostart: bool = True) -> bool:
    """
    Create/update/delete Windows autostart registry key

    ! Windows ONLY
    ! If the function fails, OSError is raised.

    :param app_name:    A string containing the name of the application name
    :param key_data:    A string that specifies the application path.
    :param autostart:   True - create/update autostart key / False - delete autostart key
    :return:            True - Success / False - Error, app name dont exist
    """

    with winreg.OpenKey(
            key=winreg.HKEY_CURRENT_USER,
            sub_key=r'SoftwareMicrosoftWindowsCurrentVersionRun',
            reserved=0,
            access=winreg.KEY_ALL_ACCESS,
    ) as key:
        try:
            if autostart:
                winreg.SetValueEx(key, app_name, 0, winreg.REG_SZ, key_data)
            else:
                winreg.DeleteValue(key, app_name)
        except OSError:
            return False
    return True


def check_autostart_registry(value_name):
    """
    Check Windows autostart registry status

    ! Windows ONLY
    ! If the function fails, OSError is raised.

    :param value_name:  A string containing the name of the application name
    :return: True - Exist / False - Not exist
    """

    with winreg.OpenKey(
            key=winreg.HKEY_CURRENT_USER,
            sub_key=r'SoftwareMicrosoftWindowsCurrentVersionRun',
            reserved=0,
            access=winreg.KEY_ALL_ACCESS,
    ) as key:
        idx = 0
        while idx < 1_000:     # Max 1.000 values
            try:
                key_name, _, _ = winreg.EnumValue(key, idx)
                if key_name == value_name:
                    return True
                idx += 1
            except OSError:
                break
    return False

Create autostart:

set_autostart_registry('App name', r'C:testx.exe')

Update autostart:

set_autostart_registry('App name', r'C:testy.exe')

Delete autostart:

set_autostart_registry('App name', autostart=False)

Check autostart:

if check_autostart_registry('App name'):

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    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:Userscurrent_userAppDataRoamingMicrosoftWindowsStart MenuProgramsStartup 
     

    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_USERSoftwareMicrosoftWindowsCurrentVersionRun

    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 = "SoftwareMicrosoftWindowsCurrentVersionRun"

        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.
     

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    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:Userscurrent_userAppDataRoamingMicrosoftWindowsStart MenuProgramsStartup 
     

    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_USERSoftwareMicrosoftWindowsCurrentVersionRun

    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 = "SoftwareMicrosoftWindowsCurrentVersionRun"

        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.
     

    Rimush

    Как запустить python скрипт при старте Windows?


    • Вопрос задан

      более трёх лет назад

    • 6144 просмотра


    Комментировать

    Пригласить эксперта


    Ответы на вопрос 3

    dimonchik2013

    Dimonchik

    @dimonchik2013

    non progredi est regredi

    Панель управления — администрирование — планировщик заданий

    все пути — абсолютные, в т.ч. к Питону

    Как я понимаю, надо добавить файл (или ярлык) скрипта в эту папку:

    C:Documents and SettingsAll UsersStart MenuProgramsStartup

    Источник инфы


    Комментировать

    pyinstaller`ом в exe, затем в автозапуск или через планировщик


    Похожие вопросы


    • Показать ещё
      Загружается…

    06 февр. 2023, в 07:47

    2000 руб./за проект

    06 февр. 2023, в 06:52

    5000 руб./за проект

    06 февр. 2023, в 06:02

    5000 руб./за проект

    Минуточку внимания

    Добавление скрипта Python при запуске Windows в основном означает, что скрипт Python будет запускаться при загрузке Windows. Это можно сделать с помощью двухэтапного процесса —

    Шаг №1: Добавление скрипта в папку автозагрузки Windows
    После загрузки Windows запускается (эквивалент двойного щелчка) все приложение, находящееся в его стартовом каталоге.
    Адрес:

    C:Userscurrent_userAppDataRoamingMicrosoftWindowsStart MenuProgramsStartup

    По умолчанию папка AppData в текущем_пользователе скрыта, поэтому разрешите скрытым файлам получить ее и вставьте ярлык сценария в указанный адрес или сам сценарий. Также для файлов .PY по умолчанию должна быть установлена среда IDE python, иначе сценарий может открыться как текст вместо выполнения.

    Шаг № 2: Добавление скрипта в реестр Windows
    Этот процесс может быть рискованным, если не будет выполнен должным образом, он включает в себя редактирование ключа реестра Windows HKEY_CURRENT_USER из самого скрипта python. Этот реестр содержит список программ, которые должны запускаться после входа пользователя в систему. точно так же, как некоторые приложения, которые появляются при запуске Windows, потому что вызывают изменение в реестре и добавляют к нему свой путь к приложению.

    Путь к реестру:

    HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionRun

    Ниже приведен код Python:

    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 = "SoftwareMicrosoftWindowsCurrentVersionRun"

    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()

    Примечание. В этот сценарий можно добавить дополнительные коды, чтобы задача выполнялась при каждом запуске, и сценарий должен запускаться от имени администратора в первый раз.

    Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

    Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение — базовый уровень.

    The web is a living, breathing organism – it constantly adapts and changes. In this dynamic environment, gathering time-sensitive data such as E-commerce listings only once is useless as it quickly becomes obsolete. To be competitive, you must keep your data fresh and run your web scraping scripts repeatedly and regularly.

    The easiest way is to run a script in the background. In other words, run it as a service. Fortunately, no matter the operating system in use – Linux or Windows – you have great tools at your disposal. This guide will detail the process in a few simple steps.

    Preparing a Python script for Linux

    In this article, information from a list of book URLs will be scraped. When the process reaches the end of the list, it loops over and refreshes the data again and again.

    First, make a request and retrieve the HTML content of a page. Use the Requests module to do so:

    urls = [
    'https://books.toscrape.com/catalogue/sapiens-a-brief-history-of-humankind_996/index.html',
    'https://books.toscrape.com/catalogue/shakespeares-sonnets_989/index.html',
    'https://books.toscrape.com/catalogue/sharp-objects_997/index.html',
    ]
    
    index = 0
    while True:
        url = urls[index % len(urls)]
        index += 1
    
        print('Scraping url', url)
        response = requests.get(url)

    Once the content is retrieved, parse it using the Beautiful Soup library:

    soup = BeautifulSoup(response.content, 'html.parser')
    book_name = soup.select_one('.product_main').h1.text
    rows = soup.select('.table.table-striped tr')
    product_info = {row.th.text: row.td.text for row in rows}

    Make sure your data directory-to-be already exists, and then save book information there in JSON format.

    Protip: make sure to use the pathlib module to automatically convert Python path separators into a format compatible with both Windows and Linux systems.

    data_folder = Path('./data')
    data_folder.mkdir(parents=True, exist_ok=True)
    
    json_file_name = re.sub('[: ]', '-', book_name)
    json_file_path = data_folder / f'{json_file_name}.json'
    with open(json_file_path, 'w') as book_file:
        json.dump(product_info, book_file)

    Since this script is long-running and never exits, you must also handle any requests from the operating system attempting to shut down the script. This way, you can finish the current iteration before exiting. To do so, you can define a class that handles the operating system signals:

    class SignalHandler:
        shutdown_requested = False
    
        def __init__(self):
            signal.signal(signal.SIGINT, self.request_shutdown)
            signal.signal(signal.SIGTERM, self.request_shutdown)
    
        def request_shutdown(self, *args):
            print('Request to shutdown received, stopping')
            self.shutdown_requested = True
    
        def can_run(self):
            return not self.shutdown_requested

    Instead of having a loop condition that never changes (while True), you can ask the newly built SignalHandler whether any shutdown signals have been received:

    signal_handler = SignalHandler()
    
    # ...
    
    while signal_handler.can_run():
        # run the code only if you don't need to exit

    Here’s the code so far:

    import json
    import re
    import signal
    from pathlib import Path
    
    import requests
    from bs4 import BeautifulSoup
    
           class SignalHandler:
        shutdown_requested = False
    
        def __init__(self):
            signal.signal(signal.SIGINT, self.request_shutdown)
            signal.signal(signal.SIGTERM, self.request_shutdown)
    
        def request_shutdown(self, *args):
            print('Request to shutdown received, stopping')
            self.shutdown_requested = True
    
        def can_run(self):
            return not self.shutdown_requested
    
    
    signal_handler = SignalHandler()
    urls = [
        'https://books.toscrape.com/catalogue/sapiens-a-brief-history-of-humankind_996/index.html',
        'https://books.toscrape.com/catalogue/shakespeares-sonnets_989/index.html',
        'https://books.toscrape.com/catalogue/sharp-objects_997/index.html',
    ]
    
    index = 0
    while signal_handler.can_run():
        url = urls[index % len(urls)]
        index += 1
    
        print('Scraping url', url)
        response = requests.get(url)
    
        soup = BeautifulSoup(response.content, 'html.parser')
        book_name = soup.select_one('.product_main').h1.text
        rows = soup.select('.table.table-striped tr')
        product_info = {row.th.text: row.td.text for row in rows}
    
        data_folder = Path('./data')
        data_folder.mkdir(parents=True, exist_ok=True)
    
        json_file_name = re.sub('[': ]', '-', book_name)
        json_file_path = data_folder / f'{json_file_name}.json'
        with open(json_file_path, 'w') as book_file:
            json.dump(product_info, book_file)

    The script will refresh JSON files with newly collected book information.

    Running a Linux daemon

    If you’re wondering how to run Python script in Linux, there are multiple ways to do it on startup. Many distributions have built-in GUI tools for such purposes.

    Let’s use one of the most popular distributions, Linux Mint, as an example. It uses a desktop environment called Cinnamon that provides a startup application utility.

    It allows you to add your script and specify a startup delay.

    However, this approach doesn’t provide more control over the script. For example, what happens when you need to restart it?

    This is where systemd comes in. Systemd is a service manager that allows you to manage user processes using easy-to-read configuration files.

    To use systemd, let’s first create a file in the /etc/systemd/system directory:

    cd /etc/systemd/system
    touch book-scraper.service

    Add the following content to the book-scraper.service file using your favorite editor:

    [Unit]
    Description=A script for scraping the book information
    After=syslog.target network.target
    
    [Service]
    WorkingDirectory=/home/oxylabs/Scraper
    ExecStart=/home/oxylabs/Scraper/venv/bin/python3 scrape.py
    
    Restart=always
    RestartSec=120
    
    [Install]
    WantedBy=multi-user.target

    Here’s the basic rundown of the parameters used in the configuration file:

    • After – ensures you only start your Python script once the network is up. 

    • RestartSec – sleep time before restarting the service.

    • Restart – describes what to do if a service exits, is killed, or a timeout is reached. 

    • WorkingDirectory – current working directory of the script.

    • ExecStart – the command to execute.

    Now, it’s time to tell systemd about the newly created daemon. Run the daemon-reload command:

    Then, start your service:

    systemctl start book-scraper

    And finally, check whether your service is running:

    $  system systemctl status book-scraper
    book-scraper.service - A script for scraping the book information
         Loaded: loaded (/etc/systemd/system/book-scraper.service; disabled; vendor preset: enabled)
         Active: active (running) since Thu 2022-09-08 15:01:27 EEST; 16min ago
       Main PID: 60803 (python3)
          Tasks: 1 (limit: 18637)
         Memory: 21.3M
         CGroup: /system.slice/book-scraper.service
                 60803 /home/oxylabs/Scraper/venv/bin/python3 scrape.py
    
    Sep 08 15:17:55 laptop python3[60803]: Scraping url https://books.toscrape.com/catalogue/shakespeares-sonnets_989/index.html
    Sep 08 15:17:55 laptop python3[60803]: Scraping url https://books.toscrape.com/catalogue/sharp-objects_997/index.html
    Sep 08 15:17:55 laptop python3[60803]: Scraping url https://books.toscrape.com/catalogue/sapiens-a-brief-history-of-humankind_996/index.html

    Protip: use journalctl -S today -u book-scraper.service to monitor your logs in real-time.

    Congrats! Now you can control your service via systemd.

    Running a Python script as a Windows service

    Running a Python script as a Windows service is not as straightforward as one might expect. Let’s start with the script changes.

    To begin, change how the script is executed based on the number of arguments it receives from the command line.  

    If the script receives a single argument, assume that Windows Service Manager is attempting to start it. It means that you have to run an initialization code. If zero arguments are passed, print some helpful information by using win32serviceutil.HandleCommandLine:

    if __name__ == '__main__':
        if len(sys.argv) == 1:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(BookScraperService)
            servicemanager.StartServiceCtrlDispatcher()
        else:
            win32serviceutil.HandleCommandLine(BookScraperService)

    Next, extend the special utility class and set some properties. The service name, display name, and description will all be visible in the Windows services utility (services.msc) once your service is up and running.

    class BookScraperService(win32serviceutil.ServiceFramework):
        _svc_name_ = 'BookScraperService'
        _svc_display_name_ = 'BookScraperService'
        _svc_description_ = 'Constantly updates the info about books'

    Finally, implement the SvcDoRun and SvcStop methods to start and stop the service. Here’s the script so far:

    import sys
    import servicemanager
    import win32event
    import win32service
    import win32serviceutil
    import json
    import re
    from pathlib import Path
    
    import requests
    from bs4 import BeautifulSoup
    
    
    class BookScraperService(win32serviceutil.ServiceFramework):
        _svc_name_ = 'BookScraperService'
        _svc_display_name_ = 'BookScraperService'
        _svc_description_ = 'Constantly updates the info about books'
    
        def __init__(self, args):
            win32serviceutil.ServiceFramework.__init__(self, args)
            self.event = win32event.CreateEvent(None, 0, 0, None)
    
        def GetAcceptedControls(self):
            result = win32serviceutil.ServiceFramework.GetAcceptedControls(self)
            result |= win32service.SERVICE_ACCEPT_PRESHUTDOWN
            return result
    
        def SvcDoRun(self):
            urls = [
    'https://books.toscrape.com/catalogue/sapiens-a-brief-history-of-humankind_996/index.html',
    'https://books.toscrape.com/catalogue/shakespeares-sonnets_989/index.html',
    'https://books.toscrape.com/catalogue/sharp-objects_997/index.html',
            ]
    
            index = 0
    
            while True:
                result = win32event.WaitForSingleObject(self.event, 5000)
                if result == win32event.WAIT_OBJECT_0:
                    break
    
                url = urls[index % len(urls)]
                index += 1
    
                print('Scraping url', url)
                response = requests.get(url)
    
                soup = BeautifulSoup(response.content, 'html.parser')
                book_name = soup.select_one('.product_main').h1.text
                rows = soup.select('.table.table-striped tr')
                product_info = {row.th.text: row.td.text for row in rows}
    
                data_folder = Path('C:\Users\User\Scraper\dist\scrape\data')
                data_folder.mkdir(parents=True, exist_ok=True)
    
                json_file_name = re.sub('[': ]', '-', book_name)
                json_file_path = data_folder / f'{json_file_name}.json'
                with open(json_file_path, 'w') as book_file:
                    json.dump(product_info, book_file)
    
        def SvcStop(self):
            self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
            win32event.SetEvent(self.event)
    
    
    if __name__ == '__main__':
        if len(sys.argv) == 1:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(BookScraperService)
            servicemanager.StartServiceCtrlDispatcher()
        else:
            win32serviceutil.HandleCommandLine(BookScraperService)

    Now that you have the script, open a Windows terminal of your preference.

    Protip: if you’re using Powershell, make sure to include a .exe extension when running binaries to avoid unexpected errors.

    Once the terminal is open, change the directory to the location of your script with a virtual environment, for example:

    Next, install the experimental Python Windows extensions module, pypiwin32. You’ll also need to run the post-install script:

    .venvScriptspip install pypiwin32
    .venvScriptspywin32_postinstall.py -install

    Unfortunately, if you attempt to install your Python script as a Windows service with the current setup, you’ll get the following error:

    **** WARNING ****
    The executable at "C:UsersUserScrapervenvlibsite-packageswin32PythonService.exe" is being used as a service.
    
    This executable doesn't have pythonXX.dll and/or pywintypesXX.dll in the same
    directory, and they can't be found in the System directory. This is likely to
    fail when used in the context of a service.
    
    The exact environment needed will depend on which user runs the service and
    where Python is installed. If the service fails to run, this will be why.
    
    NOTE: You should consider copying this executable to the directory where these
    DLLs live - "C:UsersUserScrapervenvlibsite-packageswin32" might be a good place.

    However, if you follow the instructions of the error output, you’ll be met with a new issue when trying to launch your script:

    Error starting service: The service did not respond to the start or control request in a timely fashion.

    To solve this issue, you can add the Python libraries and interpreter to the Windows path. Alternatively, bundle your script and all its dependencies into an executable by using pyinstaller:

    venvScriptspyinstaller --hiddenimport win32timezone -F scrape.py

    The —hiddenimport win32timezone option is critical as the win32timezone module is not explicitly imported but is still needed for the script to run.

    Finally, let’s install the script as a service and run it by invoking the executable you’ve built previously:

    PS C:UsersUserScraper> .distscrape.exe install
    Installing service BookScraper
    Changing service configuration
    Service updated
    
    PS C:UsersUserScraper> .distscrape.exe start
    Starting service BookScraper
    PS C:UsersUserScraper>

    And that’s it. Now, you can open the Windows services utility and see your new service running.

    Protip: you can read more about specific Windows API functions here.

    The newly created service is running

    Making your life easier by using NSSM on Windows

    As evident, you can use win32serviceutil to develop a Windows service. But the process is definitely not that simple – you could even say it sucks! Well, this is where the NSSM (Non-Sucking Service Manager) comes into play.

    Let’s simplify the script by only keeping the code that performs web scraping:

    import json
    import re
    from pathlib import Path
    
    import requests
    from bs4 import BeautifulSoup
    
    urls = ['https://books.toscrape.com/catalogue/sapiens-a-brief-history-of-humankind_996/index.html',
            'https://books.toscrape.com/catalogue/shakespeares-sonnets_989/index.html',
            'https://books.toscrape.com/catalogue/sharp-objects_997/index.html', ]
    
    index = 0
    
    while True:
        url = urls[index % len(urls)]
        index += 1
    
        print('Scraping url', url)
        response = requests.get(url)
    
        soup = BeautifulSoup(response.content, 'html.parser')
        book_name = soup.select_one('.product_main').h1.text
        rows = soup.select('.table.table-striped tr')
        product_info = {row.th.text: row.td.text for row in rows}
    
        data_folder = Path('C:\Users\User\Scraper\data')
        data_folder.mkdir(parents=True, exist_ok=True)
    
        json_file_name = re.sub('[': ]', '-', book_name)
        json_file_path = data_folder / f'{json_file_name}.json'
        with open(json_file_path, 'w') as book_file:
            json.dump(product_info, book_file)

    Next, build a binary using pyinstaller:

    venvScriptspyinstaller -F simple_scrape.py

    Now that you have a binary, it’s time to install NSSM by visiting the official website. Extract it to a folder of your choice and add the folder to your PATH environment variable for convenience.

    Then, run the terminal as an admin.

    Once the terminal is open, change the directory to your script location:

    Finally, install the script using NSSM and start the service:

    nssm.exe install SimpleScrape C:UsersUserScraperdistsimple_scrape.exe
    nssm.exe start SimpleScrape

    Protip: if you have issues, redirect the standard error output of your service to a file to see what went wrong:

    nssm set SimpleScrape AppStderr C:UsersUserScraperservice-error.log

    NSSM ensures that a service is running in the background, and if it doesn’t, you at least get to know why.

    Conclusion

    Regardless of the operating system, you have various options for setting up Python scripts for recurring web scraping tasks. Whether you need the configurability of systemd, the flexibility of Windows services, or the simplicity of NSSM, be sure to follow this tried & true guide as you navigate their features.

    If you are interested in more Python automation solutions for web scraping applications or would like to refresh the basics, take a look at our blog for various tutorials on all things web scraping.

    People also ask

    What is systemd?

    Systemd is a powerful tool for managing processes. It also provides logging and dependency management, for example, starting processes only when a network is available or once a previous service has been started.

    What is the difference between systemd and systemctl?

    Systemctl is a utility and is part of systemd. Among other things, it allows you to manage services and check their status.

    Can I use cron instead of systemd?

    You definitely can if it suits your needs. However, if you need more control over the service, systemd is the way to go. It allows you to start services based on certain conditions and is perfect for dealing with long-running scripts. It even allows you to run scripts in a similar way to crontab by using timers.

    What’s the difference between a daemon and a service?

    The word daemon comes from MIT’s Project MAC, which first coined the term in 1963. It is, by definition, an agent that works tirelessly in the background. Later Windows and Linux adopted the term as an alternative name. Therefore, this article uses the words daemon and service interchangeably.

    About the author

    Augustas Pelakauskas

    Senior Copywriter

    Augustas Pelakauskas is a Senior Copywriter at Oxylabs. Coming from an artistic background, he is deeply invested in various creative ventures — the most recent one being writing. After testing his abilities in the field of freelance journalism, he transitioned to tech content creation. When at ease, he enjoys sunny outdoors and active recreation. As it turns out, his bicycle is his fourth best friend.

    All information on Oxylabs Blog is provided on an «as is» basis and for informational purposes only. We make no representation and disclaim all liability with respect to your use of any information contained on Oxylabs Blog or any third-party websites that may be linked therein. Before engaging in scraping activities of any kind you should consult your legal advisors and carefully read the particular website’s terms of service or receive a scraping license.

    Playwright vs Puppeteer: The Differences

    Augustas Pelakauskas

    2023-01-24

    Playwright vs Selenium: Which One to Choose

    Enrika Pavlovskytė

    2023-01-10

    Introducing Real Estate Scraper API: Gather Property Data at Scale

    Danielius Radavicius

    2022-11-24

    IN THIS ARTICLE:


    • Preparing a Python script for Linux


    • Running a Linux daemon


    • Running a Python script as a Windows service


    • Making your life easier by using NSSM on Windows


    • Conclusion

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

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

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

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

    Мой Telegram канал

    Admin

    Admin

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

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

    Имя *

    Email *

    Комментарий

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

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

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

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

    0127

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

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

    0145

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

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

    0132

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

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

    0109

    5 ответов

    В зависимости от того, что делает script, вы можете:

    • упакуйте его в сервис, который затем должен быть установлен
    • добавьте его в реестр Windows (HKCUSoftwareMicrosoftWindowsCurrentVersionRun)
    • добавить ярлык к нему в стартовую папку в меню «Пуск» — его местоположение может измениться с версией ОС, но у установщиков всегда есть инструкция по размещению ярлыка в этой папке
    • использовать планировщик задач Windows, а затем вы можете установить задачу на нескольких типах событий, включая вход в систему и при запуске.

    Фактическое решение зависит от ваших потребностей и того, что действительно делает script.
    Некоторые примечания о различиях:

    • Решение №1 запускает script с компьютером, а решение №2 и №3 запускает его, когда пользователь, который его установил, входит в систему.
    • Также стоит отметить, что # 1 всегда запускает script, а # 2 и # 3 запускает script только для определенного пользователя (я думаю, что если вы используете пользователя по умолчанию, то он начнет на всех, но я не уверен в деталях).
    • Решение №2 немного более «скрыто» для пользователя, в то время как решение №3 оставляет пользователю гораздо больше контроля с точки зрения отключения автоматического запуска.
    • Наконец, для решения # 1 требуются права администратора, а остальные два могут выполняться любым пользователем.
    • Решение №4 — это то, что я обнаружил в последнее время, и это очень просто. Единственная проблема, которую я заметил, это то, что python script приведет к появлению небольшого окна команд.

    Как вы можете видеть, все сводится к тому, что вы хотите сделать; например, если это что-то для ваших целей, я просто перетащил его в папку автозагрузки.

    В любом случае, в последнее время я опираюсь на решение № 4, как самый быстрый и простой подход.

    Roberto Liffredo
    14 дек. 2010, в 14:02

    Поделиться

    В следующем каталоге автозагрузки (по крайней мере, этот путь существует в Windows XP):

    C:Documents and SettingsAll UsersStart MenuProgramsStartup
    

    установите ярлык для вашей программы python. Он должен выполняться каждый раз при запуске вашей системы.

    darioo
    14 дек. 2010, в 10:43

    Поделиться

    Не тестировал это, но я создал пакетный файл, содержащий «python yourfile.py», и поместил его в папку автозапуска.

    LiMuBei
    14 дек. 2010, в 10:39

    Поделиться

    если вы можете просто добавить следующий код к вашему script. Тем не менее, это работает только в окнах!:

    import getpass
    USER_NAME = getpass.getuser()
    
    
    def add_to_startup(file_path=""):
        if file_path == "":
            file_path = os.path.dirname(os.path.realpath(__file__))
        bat_path = r'C:Users%sAppDataRoamingMicrosoftWindowsStart MenuProgramsStartup' % USER_NAME
        with open(bat_path + '\' + "open.bat", "w+") as bat_file:
            bat_file.write(r'start "" %s' % file_path)
    

    эта функция создает файл bat в папке автозагрузки, которая запускает ваш script.

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

    tzadok
    10 авг. 2017, в 15:59

    Поделиться

    попробуйте добавить запись в «HKLM/SOFTWAREMicrosoftWindowsCurrentVersionRunOnce».
    Правый клик → новый → строковое значение → добавить путь к файлу

    RedDeath
    26 фев. 2014, в 09:43

    Поделиться

    Ещё вопросы

    • 0Преимущества подхода jQuery для делегированных событий для Grid
    • 0Сводная таблица с динамическими именами столбцов MySQL
    • 0Удалить идентификатор с помощью Angular
    • 0Автоматически исчезает Div, когда его видно
    • 0установить фоновое изображение из выпадающего меню — JavaScript
    • 0Изменить текст элемента QComboBox в делегате
    • 1Как сфокусироваться на GridView First Image Android?
    • 1Как заставить фигуру двигаться с помощью keyIsDown (p5.js)
    • 1Лучшая практика очистки ViewModelLocator
    • 0Перенаправлять посетителей на основе текущего URL
    • 1Почему постфиксные операторы в Java оцениваются справа налево?
    • 1Нажмите клавишу в любом месте формы
    • 0Лучший анализатор XML с поддержкой запросов / ответов SOAP
    • 0Обновить файл RSS из другого файла XML
    • 0Как добавить диапазон в родительское меню
    • 0Быстрая загрузка эскизов изображений
    • 0Angular & Loopback: User.login не является функцией
    • 1Выравнивание текста символов ASCII
    • 1Отправка намерений от получателя к услуге с задержкой
    • 1Что убивает Android AsyncTask? [Дубликат]
    • 1Обучены ли средства извлечения объектов в API обнаружения объектов Tensorflow?
    • 1как получить и установить параметры в Camel HTTP Proxy
    • 1ProgressDialog не появляется, пока не стало слишком поздно
    • 0Получить имя папки через php запрос URL
    • 0.hover () с jQuery работает только один раз
    • 1Холст был испорчен данными локального происхождения.
    • 0Как считать записи, специально соответствующие другой строке в соединении
    • 1Как сохранить приложение для Android, когда телефон переходит в режим ожидания?
    • 1Исключение из нехватки памяти: добавьте диапазон
    • 1Python / Pandas — помещает список диктов в DataFrame Pandas — Dict Keys должен быть столбцами
    • 1Привязка модели слушателя событий слоя карт Google Ionic + Angular2
    • 0Как установить высоту тела равную длине массива в угловых
    • 1Конвертировать Python для цикла в цикл while со счетчиком
    • 0OpenCV проект не компилируется
    • 0Инициализация колоды с использованием Юникода
    • 1Вырежьте this.index из массива между компонентами в VueJS
    • 0Как справиться со смещением часового пояса с помощью летнего времени?
    • 1WCF WebInvoke POST null для всех параметров
    • 0Передача входных данных между текстовыми полями HTML
    • 1И TSV, и TXT выводят в тессеракт
    • 1Обнаружение вмятин в кузове автомобиля
    • 1Как сделать границу вокруг ттк.OptionMenu
    • 1У Java split () есть место в индексе 0
    • 0Поместите данные JSON в таблицу / DIV
    • 1получение нескольких строк с parse.com в динамические текстовые блоки в приложении Windows Phone 8
    • 0Сбой при инициализации видео opencv
    • 0Отправить HTML-форму данных в файл с помощью Jquery?
    • 0Получение развивающей копии модуля ZF2
    • 0Обновление базы данных с использованием раскрывающегося списка без использования кнопки отправки
    • 0Манипуляции с атрибутом HTML5 <audio> / <source> с помощью JQuery

    Ychenyi

    38 / 39 / 7

    Регистрация: 13.11.2020

    Сообщений: 678

    1

    06.03.2021, 16:35. Показов 13394. Ответов 24

    Метки нет (Все метки)


    У меня есть программа (выводит просто пустое окно), скомпилировал в исполняемый файл с помощью pyinstaller
    вот смотрите, предположим сейчас оно открыто, я перезапущу пк и при повторном включении компьютера, нужно будет заново кликать по нему чтобы открыть
    а как сделать так, чтобы если оно было активно, то при перезапуске пк, автоматически открывалось?
    код в программе такой, если нужно:

    Python
    1
    2
    3
    4
    5
    6
    7
    
    import tkinter
    import time
    time.sleep(10)
    master = tkinter.Tk()
    canvas = tkinter.Canvas(master, bg='blue', height=300, width=600)
    canvas.pack()
    master.mainloop()

    __________________
    Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



    0



    4037 / 2979 / 1074

    Регистрация: 21.03.2016

    Сообщений: 7,505

    06.03.2021, 16:43

    2

    Лучший ответ Сообщение было отмечено Ychenyi как решение

    Решение

    Цитата
    Сообщение от Ychenyi
    Посмотреть сообщение

    а как сделать так, чтобы если оно было активно

    а как оно может быть активно при перезапуске? процесс то будет убит.
    как вариант писать программу проверки которую закидываете в автозапуск. при запуске вашего файла создается текстовый файл где пишется допустим 1 и при закрытии вашей проги в файле перезаписывается 0. тогда программа из автозапуска будет проверять этот файл и если там 1 (был убит процесс а не закрыт вами) то тогда запускать вашу прогу. как это реализовать думайте сами.



    1



    38 / 39 / 7

    Регистрация: 13.11.2020

    Сообщений: 678

    06.03.2021, 16:44

     [ТС]

    3

    Цитата
    Сообщение от Semen-Semenich
    Посмотреть сообщение

    а как оно может быть активно при перезапуске? процесс то будет убит.

    тут я имел ввиду, что если прога активна была ДО перезапуска, то как сделать так, чтобы и после него она включилась самостоятельно



    0



    4037 / 2979 / 1074

    Регистрация: 21.03.2016

    Сообщений: 7,505

    06.03.2021, 16:48

    4

    выше описал алгоритм перезапуска



    0



    38 / 39 / 7

    Регистрация: 13.11.2020

    Сообщений: 678

    06.03.2021, 16:49

     [ТС]

    5

    Semen-Semenich, а можно ли это сделать в коде как нибудь??
    без закидывания в автозапуск?



    0



    Эксперт Python

    5403 / 3827 / 1214

    Регистрация: 28.10.2013

    Сообщений: 9,554

    Записей в блоге: 1

    06.03.2021, 16:52

    6

    Цитата
    Сообщение от Ychenyi
    Посмотреть сообщение

    без закидывания в автозапуск?

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

    Ну а если у тебя не windows, то ты и так знаешь как планируют запуск приложения в линуксе (или не знаешь?).



    1



    38 / 39 / 7

    Регистрация: 13.11.2020

    Сообщений: 678

    06.03.2021, 16:54

     [ТС]

    7

    Garry Galler, Semen-Semenich, то бишь мне просто нужно файл.exe закинуть туда и он будет каждый раз открываться при запуске ПК или только тогда, когда файл.exe будет убит при перезапуске а не закрыт?



    0



    Эксперт Python

    5403 / 3827 / 1214

    Регистрация: 28.10.2013

    Сообщений: 9,554

    Записей в блоге: 1

    06.03.2021, 17:05

    8

    Цитата
    Сообщение от Ychenyi
    Посмотреть сообщение

    то бишь мне просто нужно файл.exe закинуть туда

    Нет Ты должен написать код. Реестр это не папка… и даже не мамка.



    0



    4037 / 2979 / 1074

    Регистрация: 21.03.2016

    Сообщений: 7,505

    06.03.2021, 17:06

    9

    Garry Galler, просто прогу в автозапуск ему не катит. я так понял если прога работала и комп перезапустили то и прога должна запуститься а если не работала то и не должна. автозапуск будет ее запускать постоянно.



    1



    Ychenyi

    38 / 39 / 7

    Регистрация: 13.11.2020

    Сообщений: 678

    06.03.2021, 17:45

     [ТС]

    10

    Garry Galler, код в этом же файле, где и основной код?

    Добавлено через 11 секунд

    Цитата
    Сообщение от Semen-Semenich
    Посмотреть сообщение

    просто прогу в автозапуск ему не катит. я так понял если прога работала и комп перезапустили то и прога должна запуститься а если не работала то и не должна. автозапуск будет ее запускать постоянно.

    все верно

    Добавлено через 16 минут

    Цитата
    Сообщение от Semen-Semenich
    Посмотреть сообщение

    и при закрытии вашей проги

    а как это именно в коде проверить??

    Добавлено через 18 минут
    Semen-Semenich, Garry Galler,
    вообщем , пытаюсь сделать так
    вопрос, как написать закрытие файла в

    Код

    else

    ?

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    import tkinter
    file = open("test.txt", "w")
    firstLine = file.readline()
    if firstLine == 1:
        continue
    else:
        
    file.write(1)
    master = tkinter.Tk()
    canvas = tkinter.Canvas(master, bg='blue', height=300, width=600)
    file.close()
    canvas.pack()
    master.mainloop()



    0



    3680 / 2260 / 490

    Регистрация: 07.11.2019

    Сообщений: 3,815

    06.03.2021, 17:46

    11

    Лучший ответ Сообщение было отмечено Ychenyi как решение

    Решение

    Semen-Semenich, такой вариант:
    программа стартанула, записала себя в автозапуск, перед «нормальным» завершением работы программы она удалила себя из автозапуска.



    1



    38 / 39 / 7

    Регистрация: 13.11.2020

    Сообщений: 678

    06.03.2021, 17:48

     [ТС]

    12

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

    Добавлено через 1 минуту
    u235, а как сделать так чтобы она себя туда записала и удалила?



    0



    Garry Galler

    Эксперт Python

    5403 / 3827 / 1214

    Регистрация: 28.10.2013

    Сообщений: 9,554

    Записей в блоге: 1

    06.03.2021, 17:56

    13

    Цитата
    Сообщение от Ychenyi
    Посмотреть сообщение

    а как сделать так чтобы она себя туда записала и удалила?

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    import atexit
    import time
     
    # эта функция будет вызвана только при нормальном завершении процесса
    def goodbye(name, adjective):
        # удалить себя из ветки автозапуска
        # здесь какой-то код удаления записи из реестра
        print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
     
    # зарегать 
    atexit.register(goodbye, 'Donny', 'nice')
     
     
    # здесь нужно написать код записи проги в autorun реестра
     
     
    # работа программы
    while 1:
        time.sleep(2)



    2



    Semen-Semenich

    4037 / 2979 / 1074

    Регистрация: 21.03.2016

    Сообщений: 7,505

    06.03.2021, 17:57

    14

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    
    import tkinter
    import time
     
    def fun(master = None, flag = '0'):
        with open('file_flag.txt','w') as f:
            f.write(flag)
        if flag == '1' and master:
            master.destroy()
            
    fun()
     
    time.sleep(10)
    master = tkinter.Tk()
    master.protocol('WM_DELETE_WINDOW', lambda : fun(master, '1'))
    canvas = tkinter.Canvas(master, bg='blue', height=300, width=600)
    canvas.pack()
    master.mainloop()

    если окно закрыть крестиком то в файле будет 1 а если убить процесс то в файле будет 0. теперь пишете скрипт который читает этот файл и если там 1 то запускает этот. скрипт прописываете в автозапуск



    1



    Эксперт Python

    5403 / 3827 / 1214

    Регистрация: 28.10.2013

    Сообщений: 9,554

    Записей в блоге: 1

    06.03.2021, 18:05

    15

    Ну или как у Semen-Semenich, что почти тоже самое, только через оконные события.

    Цитата
    Сообщение от Semen-Semenich
    Посмотреть сообщение

    теперь пишете скрипт который читает этот файл и если там 1 то запускает этот. скрипт прописываете в автозапуск

    А зачем такие сложности? Сама прога и должна писать себя в реестр и удалять себя же. Или я не понял?



    0



    4037 / 2979 / 1074

    Регистрация: 21.03.2016

    Сообщений: 7,505

    06.03.2021, 18:09

    16

    Garry Galler, я тоже сразу ваш вариант не понял. получается при запуске прога прописывается в автозапуск если прога завершена корректно то удаляет себя из автозапуска. так конечно проще. просто с таким еще не сталкивался и не в курсе про atexit и написал свой велосипед. пойду изучать этот модуль.



    0



    194 / 160 / 41

    Регистрация: 13.05.2019

    Сообщений: 828

    06.03.2021, 18:11

    17

    Кидай экзешник в папку по этому пути: C:UsersuserAppDataRoamingMicrosoftWindowsSt art MenuProgramsStartup
    user замени на свой



    0



    38 / 39 / 7

    Регистрация: 13.11.2020

    Сообщений: 678

    06.03.2021, 18:15

     [ТС]

    18

    Matrix3007, и все??



    0



    194 / 160 / 41

    Регистрация: 13.05.2019

    Сообщений: 828

    06.03.2021, 18:23

    19

    Ychenyi, Я не пробовал. Попробуй, потом отпишись.



    0



    Garry Galler

    Эксперт Python

    5403 / 3827 / 1214

    Регистрация: 28.10.2013

    Сообщений: 9,554

    Записей в блоге: 1

    06.03.2021, 18:43

    20

    Лучший ответ Сообщение было отмечено Ychenyi как решение

    Решение

    Python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    
    import atexit
    import time
     
    import winreg as reg  
    import os              
     
    def DeleteFromRegistry(value): 
        # key we want to change is HKEY_CURRENT_USER  
        # key value is SoftwareMicrosoftWindowsCurrentVersionRun 
        hive = reg.HKEY_CURRENT_USER 
        subKey = r"SoftwareMicrosoftWindowsCurrentVersionRun"
          
        # open the key to make changes to 
        hKey = reg.OpenKey(hive, subKey, 0,reg.KEY_ALL_ACCESS) 
     
        reg.DeleteValue(hKey, value)
        
        # now close the opened key 
        reg.CloseKey(hKey) 
     
    def AddToRegistry(value): 
      
        # in python __file__ is the instant of 
        # file path where it was executed  
        # so if it was executed from desktop, 
        # then __file__ will be  
        # c:userscurrent_userdesktop 
        script = os.path.realpath(__file__) 
        # joins the file name to end of path address 
        address = f"python.exe {script}"  
          
        # key we want to change is HKEY_CURRENT_USER  
        # key value is SoftwareMicrosoftWindowsCurrentVersionRun 
        hive = reg.HKEY_CURRENT_USER 
        subKey = r"SoftwareMicrosoftWindowsCurrentVersionRun"
          
        # open the key to make changes to 
        hKey = reg.OpenKey(hive, subKey ,0,reg.KEY_ALL_ACCESS) 
          
        # modifiy the opened key 
        reg.SetValueEx(hKey, value, 0,reg.REG_SZ,address) 
          
        # now close the opened key 
        reg.CloseKey(hKey) 
     
     
    def goodbye(name, adjective):
        DeleteFromRegistry("MyScript")
        print('Goodbye, %s, it was %s to meet you.' % (name, adjective))
     
     
    atexit.register(goodbye, "MyScript", 'nice')
    AddToRegistry("MyScript")
     
    #---------------------------------------
    x = 0
     
    # пока прога работает - 30 секунд - она в автозапуске; как только завершается (корректно) - ее там уже нет.
    while x < 30:
        time.sleep(1)
        x+=1

    Добавлено через 2 минуты
    Matrix3007,
    Зачем давать неправильный совет? ТС-у не нужен просто автозапуск. Ему нужен автозапуск по условию.



    1



    IT_Exp

    Эксперт

    87844 / 49110 / 22898

    Регистрация: 17.06.2006

    Сообщений: 92,604

    06.03.2021, 18:43

    20

    Понравилась статья? Поделить с друзьями:
  • Как запускать рабочий стол сразу в windows 8
  • Как запускать программы на python windows
  • Как запустить bluetooth службы в windows 10
  • Как запускать программы для windows на андроид
  • Как запустить bluestacks на windows 10 с включенным hyper v