Python запуск скрипта при старте windows

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

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.
     

    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'):

    Appending a Python script to windows start-up basically indicates the python script will run as the windows boots up. This can be accomplished by two step processes —

    Step #1: Appending or Adding script to windows Startup folder

    After booting up of the windows, it executes (equivalent to double-clicking) all the application present in its startup folder or directory.

    Address

    C:Userscurrent_userAppDataRoamingMicrosoftWindowsStart MenuProgramsStartup

    By default, the AppData directory or folder under the current_user is hidden that enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Besides this 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: Appending or adding script to windows Registry

    This process may be risky if not accomplished properly, it includes editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry consists of the list of programs that must execute once the user Login. Registry Path

    HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionRun

    Below is the Python code

    # Python code to append or add current script to the registry
    # module to modify or edit the windows registry
    importwinreg as reg1
    importos

    defAddToRegistry() −

       # in python __file__ is denoeted as the instant of
       # file path where it was run or executed
       # so if it was executed from desktop,
       # then __file__ will be
       # c:userscurrent_userdesktop
       pth1 =os.path.dirname(os.path.realpath(__file__))
       # Python file name with extension
       s_name1="mYscript.py"
       # The file name is joined to end of path address
       address1=os.join(pth1,s_name1)
       # key we want to modify or change is HKEY_CURRENT_USER
       # key value is SoftwareMicrosoftWindowsCurrentVersionRun
       key1 =HKEY_CURRENT_USER
       key_value1 ="SoftwareMicrosoftWindowsCurrentVersionRun"
       # open the key to make modifications or changes to
       open=reg1.OpenKey(key1,key_value1,0,reg1.KEY_ALL_ACCESS)
       # change or modifiy the opened key
       reg1.SetValueEx(open,"any_name",0,reg1.REG_SZ,address1)
       # now close the opened key
       reg1.CloseKey(open)
    # Driver Code
    if__name__=="__main__":
    AddToRegistry()

    На чтение 2 мин Просмотров 570 Опубликовано 04.10.2017

    Содержание

    1. 1. Простой python-scrypt
    2. 2. Создание файла сервиса.
    3. 3. Включение нового добавленного сервиса.
    4. 4. Запуск/Остановка/Статус сервиса

    Иногда требуется какой-то скрипт или программу запускать как системный сервис. Это можно легко провернуть, если в вашем дистрибутиве используется система инициализации и управления демонами — systemd.

    Для примера, я создам простейший python-скрипт который будет слушать 9988 порт и добавлю его в автозагрузку при старте операционной системы.

    1. Простой python-scrypt

    sudo nano /usr/bin/dummy_service.py

    Код скрипта:

    #!/usr/bin/python3
     
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("localhost", 9988))
    s.listen(1)
     
    while True:
        conn, addr = s.accept()
        data = conn.recv(1024)
        conn.close()
        my_function_that_handles_data(data)

    2. Создание файла сервиса.

    Теперь создадим файл сервиса для с помощью которого расскажем systemd что нам требуется. Файл должен иметь расширение .service и находиться в директории /lib/systemd/system/

    sudo nano /lib/systemd/system/dummy.service

    Добавим информацию о нашем сервисе (можете изменить местоположение скрипта и описание сервиса):

    [Unit]
    Description=Dummy Service
    After=multi-user.target
    Conflicts=getty@tty1.service
    
    [Service]
    Type=simple
    ExecStart=/usr/bin/python3 /usr/bin/dummy_service.py
    StandardInput=tty-force
    
    [Install]
    WantedBy=multi-user.target

    Мне кажется из содержимого всё и так понятно — какая строка и за что отвечает.

    3. Включение нового добавленного сервиса.

    Вы добавили, наконец-то, ваш сервис в систему. теперь необходимо перезапустить демон systemctl чтобы он прочел новый файл. Каждый раз как вы вносите изменения в .service файлы вам нужно перезапустить демон.

    sudo systemctl daemon-reload

    Теперь включим запуск сервиса при загрузке системы, и запустим сам сервис.

    sudo systemctl enable dummy.service
    sudo systemctl start  dummy.service

    4. Запуск/Остановка/Статус сервиса

    В конце проверим статус нашего нового сервиса:

    sudo systemctl status dummy.service

    Изображение 1Проверим что наш python-скрипт слушает нужный нам порт:

    sudo lsof -i | grep 9988

    Иллюстрация 2Команды для запуска, остановки и перезапуска сервиса:

    sudo systemctl stop dummy.service          #Для остановки сервиса 
    sudo systemctl start dummy.service         #Для запуска сервиса
    sudo systemctl restart dummy.service       #Для перезапуска сервиса

    ( 1 оценка, среднее 5 из 5 )

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

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

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

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

    Мой Telegram канал

    Admin

    Admin

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

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

    Имя *

    Email *

    Комментарий

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

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

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

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

    0126

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

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

    0145

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

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

    0132

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

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

    0108

    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

    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

    Поделиться

    Ещё вопросы

    • 1Как сделать приложение для Android, которое может редактировать файлы MP3?
    • 0Выберите записи, которые соответствуют по крайней мере всем элементам в списке
    • 0Невозможно привязать событие клика к отображаемому элементу
    • 0Как отправить мастер смарт-формы, прежде чем перейти к последнему шагу
    • 0Новый номер с плавающей точкой
    • 0Невозможно сбросить флажки для снятых в угловых js
    • 0php — форма не предоставляет данные
    • 0Использовать пользовательский сервис внутри Custom Event
    • 1Гарантирован ли порядок операций в конструкторе?
    • 0Соедините 3 таблицы с codeigniter и отобразите его
    • 1Как сделать цикл для центрирования строки?
    • 1JSON в CSV в CSV
    • 0Как правильно передать переменную PHP на другую страницу PHP?
    • 1Реагируй родной — вставляй Twitter
    • 0Как скопировать файл с пробелами и полными остановками в имени файла, используя функцию копирования php? [Дубликат]
    • 0Среднее из горизонталей данных MySQL PHP
    • 0Получить все строки, содержащие ЛЮБОЕ ключевое слово из заданной строки в любом столбце
    • 1Python объединяет несколько таблиц Excel в dataframe
    • 0взорвать результаты затем взорвать php
    • 0Удалить все символы, кроме точки, а также удалить все внутри фигурных скобок
    • 1Невозможно получить доступ к функции внутри функции JavaScript
    • 0Моя программа неожиданно завершается, когда я вызываю return в рекурсивной функции
    • 0я не понимаю, почему keycode == 13 не работает в Chrome
    • 0Mysql подзапрос в concat
    • 1Pandas — создает многоиндексные столбцы во время переименования
    • 0сортировка векторного объекта Student по последнему первому идентификатору
    • 0Не могу установить Composer на Mac (Yosemite)
    • 0Fancybox не работает с определенным селектором
    • 1несколько чертежей из одного XML-файла
    • 0SQL-поиск со специальными символами
    • 0MySQL — нет блокировки при выборе строк в таблице
    • 0Мой JavaScript не проверяет радиовходы моей формы правильно
    • 1Не удалось загрузить файл или сборку WPFToolkit
    • 1Как установить имя endpointBehaviors при вызове службы wcf с использованием ClientBase
    • 0Индикатор выполнения JQuery останавливает анимацию при открытии другой вкладки
    • 0Node.js API с Express & MySQL — поиск нескольких значений в параметре поиска
    • 0Перенаправление с локального диска на сервер
    • 0Показывать td как строки — отображать строку таблицы не работает
    • 0. $ ( «# ID») HTML (вар); не печатает значение. Почему?
    • 1Отформатируйте и замените строку регулярным выражением
    • 0Как изменить стиль текста вкладки браузера с помощью Javascript?
    • 0Mysqldb не устанавливается в колбу Приложение использую pycharm
    • 0Установите размер img перед отображением
    • 0Ошибка CUDA cudaMalloc после запуска ядра с огромными статическими массивами
    • 0Исключение в потоке «main» java.sql.SQLException: неправильный формат файла «inter»
    • 1Два JPanels в одном JFrame — второй переопределяет первый
    • 0Как распечатать сетку и текстовые поля в JavaScript
    • 0Как читать текст из текстового поля с C ++
    • 0Настройте пользовательскую дату для использования в качестве отправной точки в устройстве выбора даты

    Понравилась статья? Поделить с друзьями:
  • Python запуск скрипта в фоновом режиме windows
  • Python для системного администратора windows книга
  • Python для windows server 2008 r2
  • Python для windows 7 какие версии
  • Python для windows 7 x32 какая версия нужная