I'm using python and tkinter to create a little program. I'd like to make the program check if the version the user is using is the most recent version. If not, then I'd like a window pop up to prompt the user to update. Then, I'd like my software to automatically install the newest version for the user. How would I go about doing this?
The first part seems pretty self-explanatory. A different stack overflow thread suggests having a text file with the correct version and then checking that against a text file that the user has. I'm not sure how to get the program to update itself though.
Edit:
adding some detail. Is it possible to use Python to download a git repository and deleting the old version the user has downloaded?
Here is the code I made:
Side Note: I dont know if you would want to download multiple or just one, the example I gave just download one
from tkinter import *
import requests
import os
import sys
VERSION = 0
def check_updates():
try:
link = "https://raw.githubusercontent.com/User/Repo/Branch/SpecificFolderForUpdates/version.txt"
check = requests.get(link)
if float(VERSION) < float(check.text):
mb1 = messagebox.askyesno('Update Available', 'There is an update available. Click yes to update.') #confirming update with user
if mb1 is True:
filename = os.path.basename(sys.argv[0]) #gets current name of itself
savedrecordings = "Saved Recordings"
for file in os.listdir():
if file == filename: #Does not delete itself
pass
else:
os.remove(file) #removes all other files from the folder
exename = f'dcbot{float(check.text)}.exe'
code = requests.get("https://raw.githubusercontent.com/User/Repo/Branch/SpecificFolderToUpdate/file.exe", allow_redirects = True)
open(exename, 'wb').write(code.content)
root.destroy()
os.remove(sys.argv[0])
sys.exit()
elif mb1 == 'No':
pass
else:
messagebox.showinfo('Updates Not Available', 'No updates are available')
except Exception as e:
pass
root = tk.Tk()
root.geometry('800x400')
root.resizable(True, True)
root.title('Checking for updates...')
root.mainloop()
Related
My task is to call a function with photoshop through a telegram bot. To do this, I take user information from the telegram chat for the program (for example, some text to change it inside the psd), but when I call this function, my code gives the error "Please check if you have Photoshop installed correctly.", BUT if call the same function not through the bot, then everything works fine. What could be the problem?
What I already tried - reinstall photoshop, install newer version of photoshop, add path in windows environment variables. Running through pywin32 is not profitable for me.
here I take and send the argument to the function
#bot.message_handler(content_types=['text'])
def func(message):
if(message.text == '/ph'):
user_info = {'test' : 'exampletext'}
test_edit_text(user_info)
here is a function, it just changes the text
def test_edit_text(info_from):
try:
psApp = ps.Application()
psApp.Open(r"mypath\first.psd")
doc = psApp.Application.ActiveDocument
print(info_from['test'])
text_from_user = info_from['test']
layer1init = doc.ArtLayers["layer1"]
text_new_layer1 = layer1init.TextItem
text_new_layer1 .contents = f"{text_from_user .upper()}"
options = ps.JPEGSaveOptions(quality=5)
jpg = r'mypath\photo.jpg'
doc.saveAs(jpg, options, True)
except Exception as e:
print(e)
if we call the "test_edit_text()" function separately, not through the bot, everything will work
Can someone tell me how I can get all the selected files on Windowsd desktop in Python? I've been searching for a way to do it and I can't find anyone. The only one I found is for C#, but I don't code in C#, so I don't even know if it works: Get list of selected files from Windows Desktop (if someone understands it and could explain/convert it, that'd be appreciated too). I've found something very near of this, but I can only make it get the number of seleted files, not their path, as I'd like:
import ctypes
from commctrl import LVM_GETITEMCOUNT,LVM_GETSELECTEDCOUNT
#The LVM_GETITEMCOUNT came with the script, I got the other one from Microsoft documentation about SendMessage(), and both are near, but none returns the paths, only numbers
import pywintypes
import win32gui
GetShellWindow = ctypes.windll.user32.GetShellWindow
def get_desktop():
"""Get the window of the icons, the desktop window contains this window"""
shell_window = GetShellWindow()
shell_dll_defview = win32gui.FindWindowEx(shell_window, 0, "SHELLDLL_DefView", "")
if shell_dll_defview == 0:
sys_listview_container = []
try:
win32gui.EnumWindows(_callback, sys_listview_container)
except pywintypes.error as e:
if e.winerror != 0:
raise
sys_listview = sys_listview_container[0]
else:
sys_listview = win32gui.FindWindowEx(shell_dll_defview, 0, "SysListView32", "FolderView")
return sys_listview
def _callback(hwnd, extra):
class_name = win32gui.GetClassName(hwnd)
if class_name == "WorkerW":
child = win32gui.FindWindowEx(hwnd, 0, "SHELLDLL_DefView", "")
if child != 0:
sys_listview = win32gui.FindWindowEx(child, 0, "SysListView32", "FolderView")
extra.append(sys_listview)
return False
return True
def get_item_count(window):
return win32gui.SendMessage(window, LVM_GETSELECTEDCOUNT)
desktop = get_desktop()
print(get_item_count(desktop))
I've searched on the commands that can be sent to a window, but I didn't find anyone to get the path of the selected items (maybe I missed one?).
A way I found of getting the selected files from Windows Explorer windows, but now from the desktop: https://stackoverflow.com/a/21250927/8228163.
Any help (with any Windows, preferably 7) is much appreciated. Thanks in advance!
I'm trying to build a script that checks to see whether or not the password on the currently logged in user's local account has a password that isn't blank in Windows. I need this to run as part of a background check for security compliance; it's going to report to a Nagios server. I need this done in Python, but I'm open to PowerShell if Python won't do it.
So, the script will need to detect:
The username of the currently logged in user.
Whether or not the aforementioned user has a blank password.
Return error code 0 if the password is NOT blank, error code 2 if it is.
I'm stuck on just whichever bit of code will allow me to check if the password of the current user is "". I have a layout which, without too many embellishments, looks something like this:
import os
import Tkinter
import tkMessageBox
from Tkinter import Tk, Toplevel
MyGui.update_idletasks()
MyGui.attributes('-topmost', True)
MyGui.geometry('{}x{}'.format(300, 150))
MyGui.resizable(width=False, height=False)
MyGui.withdraw()
ThisUser = os.getlogin()
ThisPassword = ... # line of code necessary to test for blank password; this is the part where I'm stuck
if ThisPassword = "":
tkMessageBox.showerror("Error For User Here", parent=MyGui)
print "No password set!"
sys.exit(2)
else:
print "Password exists."
sys.exit(0)
I spotted this article, where a WinAPI commend LogonUser is used, but I'm not savvy with C#. Python is more within my comfort zone, I just can't figure out how to check whether or not a password set is blank. I don't want to collect the password, itself.
If a user's password is not blank, then attempting a logon with a blank password will fail with the error code ERROR_LOGON_FAILURE. If it is blank, then the logon will either succeed or, if system policy forbids blank passwords, will fail with the error code ERROR_ACCOUNT_RESTRICTION. For example:
import winerror
import win32security
def is_password_blank(username):
try:
token = win32security.LogonUser(username, None, '',
win32security.LOGON32_LOGON_INTERACTIVE,
win32security.LOGON32_PROVIDER_DEFAULT)
except win32security.error as e:
if e.winerror == winerror.ERROR_ACCOUNT_RESTRICTION:
return True
elif e.winerror == winerror.ERROR_LOGON_FAILURE:
return False
raise
else:
token.Close()
return True
Ok, Hi everyone, this is my code to delete a specified folder, It is cross platform compatible and designed for Kodi. I've had help from the devs there but there is a bit of code missing, more information at the bottom of the code.
import xbmcgui
import xbmc
import os
import shutil
TARGETFOLDER = xbmc.translatePath('special://home/userdata/addon_data/01')
yesnowindow = xbmcgui.Dialog().yesno("This Will Delete a folder","Click yes to delete","Click No to exit")
NOOPTION = xbmc.executebuiltin("ActivateWindow(10000,return)")
if yesnowindow:
os.path.exists(TARGETFOLDER)
if os.path.exists(TARGETFOLDER):
shutil.rmtree(TARGETFOLDER), xbmc.executebuiltin("Notification(Folder has been deleted, All done,()"), xbmc.executebuiltin("ActivateWindow(10000,return)")
else:
NOOPTION
If Yes button is pressed and TARGETFOLDER does not exist, I want it to do this code, I know it must have to do with os.path.exists
and in Lamens terms
if os.path.exists(TARGETFOLDER): shutil.rmtree(TARGETFOLDER), and if os.path.exists(TARGETFOLDER) = false then
xbmc.executebuiltin("Notification(Ok, All done,()")
Thanks for any help you can give me.
based off your example code and what I understand from the xbmcgui docs:
import xbmcgui
import xbmc
import os
import shutil
TARGETFOLDER = xbmc.translatePath(
'special://home/userdata/addon_data/01'
)
YESNOWINDOW = xbmcgui.Dialog().yesno(
"This Will Delete a folder",
"Click yes to delete",
"Click No to exit")
if YESNOWINDOW:
_MSG = None
if os.path.exists(TARGETFOLDER):
try:
shutil.rmtree(TARGETFOLDER, ignore_errors=False)
xbmc.executebuiltin("Notification(Folder has been deleted, All done,()")
xbmc.executebuiltin("ActivateWindow(10000,return)")
except OSError as rmerr:
_MSG = ("Error with delete dir: {}".format(rmerr))
except Exception as err:
_MSG = ("Error with XBMC call: {}".format(err))
else:
_MSG = ("Folder {} does not appear to be a directory"
.format(TARGETFOLDER))
if _MSG:
xbmc.executebuiltin("Notification({},()".format(_MSG)) # ***
xbmc.executebuiltin("ActivateWindow(10000,return)")
try this and report back what is borked. I didn't have a text box that I could get the xbmc libs on to verify this.
I don't know how crossplatform this is, but to me your question screams for try/except. Perhaps you can flesh this out to suit your needs:
import shutil
my_folder = 'foobar'
try:
shutil.rmtree(my_folder)
print 'folder deleted'
except OSError, e:
the_error = str(e)
if '[Errno 20]' in the_error:
print my_folder, 'is not a directory!'
elif '[Errno 2]' in the_error:
print my_folder, 'did not exist!'
else:
print the_error
THANKYOU, yep it works great one thing was a , missing in line 27 after {}
_MSG = ("Folder {} does not appear to be a directory"
to dispaly the notification properly.
I've uploaded the code to pastebin http://pastebin.com/BS3VQLbb
with comments on each line. It would be great if anyone has a chance to take a look to see if I'm understanding the code correctly.
I do have a couple of questions about the code, can I ask them here? as it seems I'm not allowed to ask for help with it. If its ok to ask please let me know. Thanks again,
Hello, my question is regarding a Python script I am trying to get to work. The point of this is that when someone makes a SVN Commit they see a login template with four lines: Branch, Bug_Number, Feature affected and Overview. Now I am trying to write a script to make sure that they wrote something on it to make sure no one enters a empty log to commit.
Here is what I have so far in python its based on a old python script.
print "Importing the items"
import re
import sys
import os
print "Initializing the list."
argsList = []
hndFile = open(sys.argv[1],"r")
for line in hndFile:
argsList.append(line)
hndFile.close()
print "Checking what is blank"
faOK = ovOK = False
for line in argsList:
line = line.strip()
if line.startswith('FEATURE_AFFECTED:'):
faOK = line[17:] != ''
if line.startswith('OVERVIEW:'):
ovOK = line[9:] != ''
if not faOK:
print "You Must Enter the Feature Affected"
ret = -1
elif not ovOK:
print "You Must Enter an Overview of the Fix"
ret = -1
else:
ret = 0
print "Finishing the script"
sys.exit(ret)
Any advice would help. I am using Windows XP and currently nothing is happening. I am also using collabnet svn. Currently nothing is happening when I try to run this script. I know I haven't added svnlook in the script I cant really think of where to add and for the variable for it. Thank you.