简体   繁体   中英

how to make script in python run at startup after converting it to exe by py installer

I want to make my script run on startup automatically after converting it to EXE by pyinstaller tool , *once clicking on SPEED.EXE 'name of program' ,It copies itself to particular path on computer then makes a bat file in startup folder 'it contains code to start SPPED.EXE' but my problem that bat file doesnot run on start *

import os
import ftplib
import sys                   
import shutil                   
import getpass                
##################copy script into startup#######################
def copy_script():
    USER_NAME = getpass.getuser()
    src=sys.argv[0]
    dst = r'C:\Users\%s\AppData' % USER_NAME
    shutil.copy2(src,dst)
    dst='C:\Users\\"%s"\AppData\SPEED.exe' % USER_NAME                   ######name of script after making EXE
    add_to_startup(USER_NAME,file_path=dst)
    return None
######################################make a bat file to run on startup######
def add_to_startup(USER_NAME,file_path):
    if file_path == "":
        file_path = os.path.dirname(os.path.realpath(__file__))
    bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME
    with open(bat_path + '\\' + "open.bat", "w") as bat_file:
        bat_file.write(r'@echo off'+ os.linesep)   ## to hide console batch file when it run
        bat_file.write(r'start "" %s' % file_path)

if __name__=='__main__':
    copy_script()
    start()     ##it is  function that i make it

thanks,I could solve my problem.

instead of creating a bat file in startup file " I delete add_to_startup method " ,I used registry method

    import winreg;
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
    r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 0,
    winreg.KEY_SET_VALUE); winreg.SetValueEx(key, 'speed', 0,
    winreg.REG_SZ,'file_path'); # file_path is path of file after coping it

the error "fatal error failed to execute script SPEED " is result of the method shutil.copy2(src,dst) can't copy the same source to same destination at startup so I make exception

        try:
            shutil.copy2(src,dst)
        except:
                pass   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM