Добавление в автозапуск python

Guides Book

Осуществить данную задачу можно двумя путями, первый состоит в том, чтобы записать значение в реестр (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run), здесь подробно описан данный метод. Однако при этом нам будет необходимо разрешение на запись в реестр, и чтобы его получить придется постараться.

Второй путь проще и не требует особых привилегий программе, для этого необходимо создать ярлык программы в C:\Users\UserName\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup (путь для Windows 7).

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

import winshell 
import os
import sys

def set_startup():
try:
# get path and file name for application
startFile = os.path.abspath(sys.argv[0])
# get startup folder
startup=winshell.startup()
# create shortcut in startup folder
winshell.CreateShortcut (
Path=os.path.join (startup, "application.lnk"),
Target=startFile,
Icon=(startFile, 0),
Description="My application",
StartIn=os.path.abspath(None)
)
except :
pass

def remove_startup():
try:
startup=winshell.startup()
# remove shortcut from startup folder
if os.path.isfile(startup + '\\application.lnk'):
os.remove(startup + '\\application.lnk')
except :
pass

В коде использован пакет winshell, позволяющий получать доступ к специальным папкам Windows.

Источник

Autorun a Python script on windows startup?

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

Читайте также:  Javascript display text in div

Address

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

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_USER\Software\Microsoft\Windows\CurrentVersion\Run

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:\users\current_user\desktop 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 Software\Microsoft\Windows\CurrentVersion\Run key1 =HKEY_CURRENT_USER key_value1 ="Software\Microsoft\Windows\CurrentVersion\Run" # 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()

Источник

Как автоматически добавить код пайтон в автозапуск?

Чтобы автоматически добавить скрипт Python в автозапуск, вы можете использовать различные методы в зависимости от операционной системы, которую вы используете. Вот несколько примеров для наиболее распространенных операционных систем:

  1. Создайте ярлык для вашего скрипта Python, щелкнув правой кнопкой мыши на скрипте и выбрав «Создать ярлык».
  2. Переместите созданный ярлык в папку автозапуска Windows, которая находится по следующему пути:

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

  1. Откройте «System Preferences» (Настройки системы) и выберите «Users & Groups» (Пользователи и группы).
  2. Выберите вашего пользователя и перейдите на вкладку «Login Items» (Элементы входа).
  3. Щелкните на «+» внизу окна и выберите ваш скрипт Python для добавления его в автозапуск.
  1. Откройте «Startup Applications» (Приложения для автозапуска). Вы можете найти его, введя в поиске «Startup Applications».
  2. Щелкните на «Add» (Добавить) или «+» и введите необходимую информацию:
    • Name (Имя): Укажите имя для вашего скрипта.
    • Command (Команда): Укажите полный путь к исполняемому файлу вашего скрипта Python.
    • Comment (Комментарий): Опционально, можете указать комментарий о вашем скрипте.
  3. Нажмите «Add» (Добавить) или «Save» (Сохранить) для добавления вашего скрипта в автозапуск.

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

k0nan Varvar Ученик (185) Kirieshkins, Чтобы скрипт Python добавил себя в автозапуск, нужно внести соответствующие изменения в файлы автозапуска операционной системы. Для Windows это будет выглядеть так: import os import shutil import sys # Путь к файлу скрипта Python script_path = os.path.abspath(sys.argv[0]) # Путь к папке автозапуска Windows startup_folder = os.path.join(os.environ[«APPDATA»], «Microsoft\\Windows\\Start Menu\\Programs\\Startup») # Копирование скрипта в папку автозапуска shutil.copy2(script_path, startup_folder)

Источник

Как установить в автозапуск python-скрипт используя systemd

Компьютерное

Иногда требуется какой-то скрипт или программу запускать как системный сервис. Это можно легко провернуть, если в вашем дистрибутиве используется система инициализации и управления демонами — 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-скрипт слушает нужный нам порт:

Иллюстрация 2

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

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

Источник

How to Run Python Script at Startup in Ubuntu

The reputation of Python as a programming language speaks for itself. This programming language is attributed as general-purpose, high level, and interpreted.

Most Linux users are in love with the Python programming language due to its code readability which makes it easy to follow and master even for a beginner in the programming world.

Some advantages of Python Programming language are listed below:

  • Open-source and community development support.
  • Rich in third-party modules.
  • User-friendly data structures.
  • Dynamically typed programming language.
  • Interpreted language.
  • Highly efficient.
  • Portable and interactive.
  • Extensive libraries support.

The above-mentioned features make Python ideal for projects related to software development (desktop, web, gaming, scientific, image processing, and graphic design applications), operating systems, database access, prototyping, and language development.

This article will address the use of Python as a scripting language in an operating system environment (Ubuntu).

Prerequisites

Ensure you meet the following requirements:

  • You are a sudoer/root user on a Linux operating system distribution.
  • You can comfortably interact with the Linux command-line environment, interpret, and execute its associated commands.
  • You have the latest version of Python installed on Ubuntu.

Confirm that you have Python installed by running the command:

$ python3 --version Python 3.8.10

Running a Python Script at Startup in Ubuntu

The following steps will help us achieve the main objective of this article.

Step 1: Create Your Python Script

Create your Python script if it does not already exist. For this article guide purpose, we will create and use the following Python script.

Add the following Python script.

from os.path import expanduser import datetime file = open(expanduser("~") + '/Desktop/i_was_created.txt', 'w') file.write("This LinuxShellTips Tutorial Actually worked!\n" + str(datetime.datetime.now())) file.close()

Upon rebooting our Ubuntu system, the above Python script should be able to create a file called i_was_created.txt on the Ubuntu Desktop (Desktop). Inside this file, we should find the text This LinuxShellTips Tutorial Actually worked! together with the date and time of its creation.

Next, move the Python Script to a directory where it can be executed with root user privileges upon system restart. One such viable directory, in this case, is /bin.

Let us move the script using the mv command.

$ sudo mv python_test_code.py /bin

Now create a cron job scheduler that will periodically handle the execution of the above-created Python script (In this case during system startup).

At the bottom of this file, add the line:

@reboot python3 /bin/python_test_code.py &

Save and close the file and then confirm the creation of the cron job schedule:

Check Cron Job in Linux

The @reboot portion of the above line tells the cron job scheduler to execute the script at system startup. The & parameter informs the cron job scheduler to execute the Python script in the background so as not to interfere with normal system startup.

We are now ready to reboot our system

Let us check if our file was created:

$ cat ~/Desktop/i_was_created.txt && echo ''

Run Python Script at Ubuntu Startup

The existence of the above file confirms the Python script was successfully executed at the Ubuntu system startup.

Источник

Оцените статью