如何在 Windows 啟動時自動執行 Python 指令碼?


將 Python 指令碼追加到 Windows 啟動項基本上表示 Python 指令碼將在 Windows 啟動時執行。這可以透過兩個步驟完成 -

步驟 1:將指令碼追加或新增到 Windows 啟動資料夾中

在 Windows 啟動後,它將執行(相當於雙擊)其啟動資料夾或目錄中存在的所有應用程式。

地址

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

預設情況下,current_user 下的 AppData 目錄或資料夾處於隱藏狀態,以便啟用隱藏檔案並將其獲取,然後將指令碼快捷方式貼上到給定地址或指令碼本身。除此之外,.PY 檔案的預設值必須設定為 Python IDE,否則指令碼可能最終以文字形式開啟,而不是執行。

步驟 2:將指令碼追加或新增到 Windows 登錄檔中

如果不正確完成,此過程可能會很危險,包括從 Python 指令碼本身編輯 Windows 登錄檔項 HKEY_CURRENT_USER。此登錄檔包含使用者登入後必須執行的程式列表。登錄檔路徑

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

以下是 Python 程式碼

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

更新於: 2020 年 1 月 29 日

1K+ 瀏覽量

開啟你的 職業 生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.