2017-04-18 36 views
1

嘿,謝謝你的所有答案。我嘗試寫一段只能執行一次的python代碼(第一次安裝該程序)並將該程序複製到Windows啓動文件夾中。僅執行一次的代碼,Python啓動文件夾

(C:\用戶\ USER \應用程序數據\漫遊\微軟\的Windows \開始菜單\程序\啓動)

這就是我寫這個代碼。 (請不要評判我,我知道這是很 低劣的代碼。但我很新的編碼。(這是第二 小程序,我試着寫)

import os 
import shutil 


#get username 
user = str(os.getlogin()) 
user.strip() 

file_in = ('C:/Users/') 
file_in_2 = ('/Desktop/Py Sandbox/test/program.py') 
file_in_com = (file_in + user + file_in_2) 

folder_seg_1 = ('C:/Users/') 
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup') 
#create FolderPath 
folder_com = (folder_seg_1 + user + folder_seg_2) 

shutil.copy2(file_in_com, folder_com) 

因爲我得到一個錯誤,沒有這樣的內部的,外部的, 命令,程序或者批處理文件命名爲Installer。我嘗試生成一個批處理文件,其中有 沒有任何內容在安裝過程結束時執行(但錯誤是仍然存在)

save_path = 'C:/Windows/assembly/temp' 
name_of_file = str("Installer") 
completeName = os.path.join(save_path, name_of_file+".bat") 
file1 = open(completeName, "w") 
file1.close() 

這背後的主要思想,有我的主程序,在執行 它運行上面的代碼,並將自身複製到啓動文件夾中。 然後將整個安裝程序文件的代碼從我的主要 程序中刪除。

import Installer 

#run Installer File 
os.system('Installer') 
os.remove('Installer.py') 

但也許還有人在那裏誰知道這個問題的答案的問題。 正如我前面所說,感謝您的所有答案< 3.

順便說一句我正在使用Python 3.5。

+0

您應該發佈錯誤消息與完整的堆棧跟蹤。 –

+0

C:\ Users \ Main \ AppData \ Local \ Programs \ Python \ Python35 \ python.exe「C:/ Users/Main/Desktop/Py Sandbox/Program/Program.py」 「安裝程序」未被識別爲內部或外部命令, 可操作的程序或批處理文件。 – Cvqe

回答

0

好吧,我現在終於設法解決了這個問題。其實並不難,但你需要從另一個角度思考。 這是現在我想出的代碼。

import os 
import sys 
import shutil 

# get system boot drive 
boot_drive = (os.getenv("SystemDrive")) 

# get current Username 
user = str(os.getlogin()) 
user.strip() 

# get script path 
script_path = (sys.argv[0]) 


# create FolderPath (Startup Folder) 
folder_seg_1 = (boot_drive + '/Users/') 
folder_seg_2 = ('/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup') 
folder_startup = (folder_seg_1 + user + folder_seg_2) 


#check if file exits, if yes copy to Startup Folder 
file_name = (ntpath.basename(script_path)) 
startup_file = (folder_startup + ("/") + file_name) 
renamed_file = (folder_startup + ("/") + ("SAMPLE.py")) 


# checkfile in Startup Folder 
check_path = (os.path.isfile(renamed_file)) 

if check_path == True: 
    pass 
else: 
    shutil.copy2(script_path, folder_startup) 
    os.rename(startup_file, renamed_file) 

這個腳本獲取你的用戶名,啓動驅動器, 文件比的文件位置創建所需的所有路徑。像你的個人 啓動文件夾。它比檢查 啓動文件夾中是否已有文件,如果是,它只是沒有任何作用,如果不是, 將文件複製到啓動文件夾並重命名它(如果你想要,但可以使用它不需要)。