Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tự động chạy script Python khi Windows khởi động

Thêm script Python vào khởi động Windows nghĩa là script sẽ chạy khi Windows boot lên. Có thể thực hiện bằng quy trình 2 bước:

Bước 1: Thêm script vào thư mục Startup của Windows

Sau khi Windows boot, nó thực thi (tương đương double-click) tất cả ứng dụng trong thư mục startup.

Địa chỉ

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

Mặc định, thư mục AppData dưới current_user bị ẩn. Bật hiển thị file ẩn để truy cập và dán shortcut của script vào địa chỉ trên hoặc chính script. Ngoài ra, file .PY mặc định phải liên kết với Python IDE, nếu không script có thể mở như văn bản thay vì thực thi.

Bước 2: Thêm script vào Windows Registry

Quy trình này có rủi ro nếu không làm đúng, bao gồm chỉnh sửa registry key HKEY_CURRENT_USER từ chính script Python. Registry này chứa danh sách chương trình phải chạy khi user Login. Registry Path:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

Mã Python

# Python code để thêm script hiện tại vào registry
# Module để sửa đổi registry Windows
import winreg as reg1
import os

def AddToRegistry():
    # Trong python __file__ là đường dẫn file nơi nó chạy
    pth1 = os.path.dirname(os.path.realpath(__file__))
    # Tên file Python với extension
    s_name1 = "myScript.py"
    # Nối tên file vào cuối đường dẫn
    address1 = os.path.join(pth1, s_name1)
    # Key muốn sửa: HKEY_CURRENT_USER
    # Key value: Software\Microsoft\Windows\CurrentVersion\Run
    key1 = reg1.HKEY_CURRENT_USER
    key_value1 = "Software\\Microsoft\\Windows\\CurrentVersion\\Run"
    # Mở key để sửa đổi
    open_key = reg1.OpenKey(key1, key_value1, 0, reg1.KEY_ALL_ACCESS)
    # Sửa đổi key đã mở
    reg1.SetValueEx(open_key, "any_name", 0, reg1.REG_SZ, address1)
    # Đóng key
    reg1.CloseKey(open_key)

# Driver Code
if __name__ == "__main__":
    AddToRegistry()