Code that only execute once, Python Startup folder - python

Hey and thanks for all of your answers. I try to write a piece of python code that only executes once, (first time the program is installed) and copies the program into the windows startup folders.
(C:\Users\ USER \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup)
That's the code i wrote for this. (Please don't judge me. I know it's
very shitty code. But I'm very new to coding. (this is the second
little program i try to write)
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)
Because i got an error, that there is no such internal, external,
command, program or batch file named Installer. I tried to generate a batch file with
nothing in it that executes when the installation process is finished.(But the error is still there.)
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()
The main idea behind this that there is my main Program, you execute
it it runs the code above and copies itself to the startup folder.
Then the code the whole installer file gets deleted form my main
program.
import Installer
#run Installer File
os.system('Installer')
os.remove('Installer.py')
But maybe there's someone out there who knows the answer to this problem.
And as I said earlier, thanks for all of your answers <3.
BTW I'm currently using Python 3.5.

Okay guys now I finally managed to solve this problem. It's actually not that hard but you need to think from another perspective.
This is now the code i came up with.
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)
This script gets your username, your boot drive, the file location of
your file than creates all the paths needed. Like your personal
startup folder. It than checks if there is already a file in the
startup folder if yes it just does nothing and goes on, if not it
copies the file to the startup folder an than renames it (you can use that if you want but you don't need to).

It is not necessary to do an os.getenv("SystemDrive") or os.getlogin(), because os.getenv("AppData") already gets both. So the most direct way of doing it that I know of is this:
path = os.path.join(os.getenv("appdata"),"Microsoft","Windows","Start Menu","Programs","Startup")

Related

How to make auto-run python file when windows open

from datetime import date
bugun = str(date.today())
if bugun == "2021-04-25":
with open("dosya.py","r+") as dosya:
liste = dosya.readlines()
liste.insert(3,"DenemeBu\n")
del liste[4]
dosya.seek(0)
print(liste)
with open("dosya.py","w") as dosya:
for i in liste:
dosya.write(i)
import os
print("Hello")
sayi1 = int(input("Sayi1: "))
sayi2 = int(input("Sayi2: "))
print("Sonuc {}".format(sayi1+sayi2))
I want to change second file with first file but I want first file to open when my pc opens and takes current date. When date corrects and changes second file.
Open your startup folder by pressing Win + R and typing in shell:startup
Within this folder, create a txt file and rename it to anything.bat and edit it with
#ECHO OFF
python3 C:/path/to/my/script.py
You can remove the "#ECHO OFF" if you want it to have a terminal window popup.
EDIT: As for the error you're facing.
Change
open("dosya.txt", "r")
to
open("C:/full/path/to/dosya.txt", "r")
Do that everywhere you open dosya.txt, like at the dosya.txt write below
You're facing this error because you're running the command for the script from a directory that doesn't contain that file and it tries to find that file in it's running directory and can't find it. Setting the full path to it will make the script work if run from any directory on your computer.
I have written a script that can auto-run any script when PC starts
import os
import winreg
class is_at_startup:
'''Adding the given program path to startup'''
def __init__(self, program_path):
self.program_path = program_path
self.program_basename = os.path.basename(self.program_path)
def main(self):
'''Adding to startup'''
if os.path.exists(self.program_path):
areg = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
try:
akey = winreg.OpenKey(areg, f'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\{self.program_basename}', 0, winreg.KEY_WRITE)
areg.Close()
akey.Close()
print(f'{self.program_path} already at startup')
except WindowsError:
key = winreg.OpenKey(areg, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run', 0, winreg.KEY_SET_VALUE)
winreg.SetValueEx(key, f'{self.program_basename}', 0, winreg.REG_SZ, f'{self.program_basename}')
areg.Close()
key.Close()
print(f'{self.program_path} added to startup')
if __name__ == '__main__':
startup = is_at_startup('your program path')
startup.main()
If you are using python 2.7.x then replace winreg with _winreg
I have tried this way for .bat files, and it worked you can also try. Put your python files that you want to run on windows startup at this location.
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

Compiling a script in. exe that uses InstaPy

I'm writing a bot for IG using the Tkinter and InstaPy libraries. If you run the script with an interpreter, everything works correctly, but after compiling it in .exe using pyinstaller, the console returns this error after starting the browser:
FileNotFoundError: [WinError 3]The system cannot find the specified path: 'C:\Users\DANILG~1\AppData\Local\Temp_MEI12802\instapy\firefox_extension\manifest.json'.
(In the console, the error text is written in Russian, here is the translation)
At first, it seemed to me that this was due to escaping the "/" in the file path. But in addition, the user name changes in the path (it must be DanilGolovzin, while the path specifies DANILG~1). Well, if you still try to go to the desired directory, ignoring the escaping and mismatch of the user name, then _MEI71162 will not have the instapy folder.
console
The problem occures because of pyinstaller. When you build the script, in "browser.py"
ext_path = os.path.abspath(os.path.dirname(__file__) + sep + "firefox_extension")
we have ext_path like that. It works when you run it as a .py but when you build it, I think it runs in Temp folder and try to find it in that folder. So when it doesn't find, an error raise. I've solve with changing "browser.py" like that:
def create_firefox_extension():
ext_path = os.path.abspath(os.path.dirname(__file__) + sep + "firefox_extension")
# safe into assets folder
zip_file = use_assets() + sep + "extension.xpi"
files = ["manifest.json", "content.js", "arrive.js"]
with zipfile.ZipFile(zip_file, "w", zipfile.ZIP_DEFLATED, False) as zipf:
for file in files:
try:
zipf.write(ext_path + sep + file, file)
except :
new_ext_path = os.getcwd()+sep+"firefox_extension"
zipf.write(new_ext_path + sep + file, file)
return zip_file
After making these changes, I've coppied the firefox_extension to .exe folder and it runs without any problem.

Why python code to run a file on startup is not working?

I want my python file to run if Windows is booted up every single time, so I used this simple code:
Background.py (This creates a .bat file which will run my desired .py file on every windows startup)
import getpass
import os
USER_NAME = getpass.getuser()
def add_to_startup():
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'C:\Users\intel\AppData\Local\Programs\Python\Python38\python.exe C:\Users\intel\Desktop\Python programs\testing.py %*')
add_to_startup()
And this is the .py file which I want to run every time:
with open(r"C:\Users\intel\Desktop\hello.txt", "w+") as test_file:
test_file.write(r'start')
But it's not working even if my computer is on :(
Edit 1:
I checked The startup folder also and the open.bat file is successfully created and existing...
(You can even check in the image)
enter code here

Copy a file with Python but not overwrite the file if it's already exists in target directory

I'm having an issue figuring out how can i implement a function to overcome my problem.
My code works fine, but the fault is that sometimes i need more than just one file.
import os
import shutil
target_dir = 'C:\DIST\WR_4.5\Test'
pass_text = 'Test End'
def check_and_copy():
log = open('C:\DIST\WR_4.5\oHistory2.log')
for line in log:
if pass_text in line:
name = '\kp.log'
else:
name = '\kf.log'
if not os.path.exists(target_dir):
os.makedirs(target_dir)
shutil.copy2('C:\DIST\WR_4.5\oHistory2.log', target_dir+name)
else:
os.chdir(target_dir)
shutil.copy2('C:\DIST\WR_4.5\oHistory2.log', target_dir+name)
What i'd like to accomplish is to be able to copy multiple instances of files with or without shutil. The filename is determined by the code itself as you can see.
Thanks for the help in advance.

opening same file on dropbox of two different computers(usernames)

i work on python. I have written some codes that i could run via dropbox on different computers( having their various usernames). like this
computer 1:
file=open("/User/james/Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
computer 2:
file = open("/User/oyebodmas/Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
each time i have to switch between computers. i always have to change the usename from james to oyebodmas and vice versa. how could i program the computer to ignore the username and read the file. i have tried
file = open("~/Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
but it does not work. thank you.
For a multiplatform solution, you can do this, assuming the folders you want to access are user's home folders:
import os
home = os.path.expanduser("~")
file_location = os.path.join(home, "Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
myfile = open(file_location)
In the case they are not, and the path is always the same and differs only in the username, you can build the path as shown in TimPietzcker's answer.
I'm not on a *NIX system, so I can't test this, but could you try
import os
currentuser = os.getusername()
file_location = os.path.join("/User", currentuser)
file_location = os.path.join(file_location, "Dropbox/programming/MATLAB/ViralGOgeneclustering/600_Clusters/complete.csv")
myfile = open(file_location)

Categories