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
Related
I found the answer
So it looks like PyInstaller actually runs in a temp directory, not your own, which explains my issue. This is an explanation for that. I guess I will keep this up incase people in the future have problems.
Original question
I am trying to use PyInstaller to create an executable of a simple python script called test.py that just creates a text file and adds numbers to it, as a test of PyInstaller. This file works correctly when run normally.
from os.path import dirname, abspath
def main():
txtfile = dirname(abspath(__file__)) + '/text.txt'
with open(txtfile, 'w') as f:
for num in range(101):
f.write(str(num) + '\n')
if __name__ == '__main__':
main()
print('script executed')
When I use:
pyinstaller test.py --onefile in the same directory as test.py it successfully creates the dist file with the binary file test inside of it.
when I cd dist and do ./test to execute the file inside dist it successfully prints out main called and script executed but it doesn't actually create the file. So, main is being called and the script is being executed, but the file isn't created at all, and I am quite confused about what I'm doing wrong..I must be getting file paths messed up? But I have specified the exact full path with os.path, so it doesn't make sense to me.
The system exit code is 0, and there are no errors raised when I call ./test
I found this that shows that PyInstaller will save to a temp file. I created this script below to check if the script is being executed directly or via PyInstaller.
import os
import sys
def create_file(path):
with open(path + '/test.txt', 'w') as f:
for num in range(101):
f.write(str(num) + '\n')
def check_using_pyinstaller():
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
return application_path
return os.path.dirname(os.path.abspath(__file__))
def main():
path = check_using_pyinstaller()
os.chdir(path)
create_file(path)
if __name__ == '__main__':
main()
Here's the code:
import shutil
import os
import datetime
SETUP_FILE = r'G:\Documents\Python\backup_tools\user.txt'
def setup():
print("dubug 04")
print('Enter your Chrome bookmark directory.')
print(r'Standard one is: C:\Users\<USER>\AppData\Local\Google\Chrome\User Data\Default')
bookmarkfolder = input('> ')
print('Enter the folder you want to save the backup files in.')
print(r'For example: C:\Users\<USER>\Desktop\Chrome Bookmarks')
backupfolder = input('> ')
with open(SETUP_FILE, 'w') as txt:
txt.write(bookmarkfolder + '\n' + backupfolder + '\n')
copy()
def copy():
print("debug 01")
with open(SETUP_FILE, 'r') as txt:
user_list = [line.strip() for line in txt]
shutil.copy(user_list[0] + r'\Bookmarks', user_list[1])
new_name = datetime.date.today().strftime('Bookmarks%Y%m%d')
try:
print("dubug 02")
os.rename(r'G:\Documents\99. Backup\Bookmarks', new_name)
except WindowsError:
print("debug 03")
os.remove(new_name)
os.rename(r'G:\Documents\99. Backup\Bookmarks', new_name)
def checksetup():
try:
with open(SETUP_FILE, 'r') as txt:
txt.seek(0)
line = txt.readline()
if 'C:' in line:
copy()
except FileNotFoundError:
print('file not found')
setup()
if __name__ == "__main__":
checksetup()
Here's the output from console in editor, which works and creates the backupfile with the correct name if it doesn't exist and replaces it if it already exists:
runfile('G:/Documents/Python/backup_tools/chrome_bookmark_backup2.py', wdir='G:/Documents/Python/backup_tools')
debug 01
dubug 02
debug 03
But here's the output when I run from windows explorer, that doesn't create the bookmarks file and seems to end up running checksetup() again, this time going to setup() as the exception appears where this same try/except already brought it to copy() which you can see from debug 01 and debug 02 in the output:
Can anyone give me direction on why this is failing when run from windows explorer using python or from windows terminal?
The error in the code is in the creation of new_name in the middle of the copy() function. It is missing the directory. Here is the corrected line of code:
new_name = os.path.join(user_list[1], datetime.date.today().strftime('Bookmarks%Y%m%d'))
What was happening was when I ran in spyder or sublime text, the rename function assumed I wanted the file in the same directory as my script when I didn't provide the directory within new_name. When run from the terminal os.rename does not accept you have not provided a directory, rather raises the exception: FileNotFoundError.
The issue for me is solved but if anyone has more information on why the errors are handled differently between IDE and external terminal it would be a more valuable answer to the original question.
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
I have compiled my python program with cx_Freeze with the lines
import sys
print(sys.argv[0])
to get the name of the extension file that runs my application.
I want to be able to double click on a file named Foo.bas and then my compiled executable starts and it can open the file and read its contents. So I want to get the extension path and file name and read its contents like this
with open(file, "r") as f:
data = f.read()
# do things with contents
where file would be the extension path and name
So how would I do that?
sys.argv[0] gives you the first entry of the command used to run your script, which is the script name itself. If you double-click on a file whose extension is associated with your script or frozen application, the name of this file becomes the second argument of the command, which is available through sys.argv[1]. See for example sys.argv[1] meaning in script.
So try with the following script:
import os
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
print('Trying with', filename)
if os.path.isfile(filename):
with open(filename, 'r') as f:
data = f.read()
# do things with contents
else:
print('No arguments provided.')
input('Press Enter to end')
This works both as unfrozen script and as executable frozen with cx_Freeze. On Windows you can drag and drop your Foo.bas file onto the icon of your script or executable, or right-click on Foo.bas, chose Open with and select your script or executable as application.
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")