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!
Related
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()
I am trying to prepare an application similar to 'Windows Start Menu Search'.
That's why I need each applications own icon.
From the C:\ProgramData\Start Menu\Programs\ file path, I add existing applications to a list (QListWidget) with their names and path.
And I get the icons like this:
https://forum.qt.io/topic/62866/getting-icon-from-external-applications
provider = QFileIconProvider()
info = QFileInfo("program_path")
icon = QIcon(provider.icon(info))
And naturally the result is this:
But I don't want this "shortcut icon" to appear.
Then, I am thinking and I came to this conclusion:
shell = win32com.client.Dispatch("WScript.Shell")
provider = QFileIconProvider()
shortcut = shell.CreateShortCut(programPath)
info = QFileInfo(shortcut.targetPath)
icon = QIcon(provider.icon(info))
This solution worked. But, It has created issue for some applications.
So I am looking for an alternative solution.
You were almost there.
Browsing the menu directory tree is actually the right path, but you also have to ensure that the icon of the link is actually the same of the target, as it might not.
The shortcut.iconlocation is a string representing a "tuple" (sort of) including the icon path and the index (as icon resources might contain more than one icon).
>>> shortcut = shell.createShortCut(linkPath)
>>> print(shortcut.iconlocation)
# most links will return this:
> ",0"
# some might return this:
> ",4"
# or this:
> "C:\SomePath\SomeProgram\SomeExe.exe,5"
As long as the icon index is 0, you can get the icon using QFileIconProvider with the targetPath or iconLocation (if there's something before the comma).
The problem comes when there's a value different from 0 for the icon index, as Qt doesn't handle that.
I've put together a simple function (based on some research here on StackOverflow).
def getIcon(self, shortcut):
iconPath, iconId = shortcut.iconLocation.split(',')
iconId = int(iconId)
if not iconPath:
iconPath = shortcut.targetPath
iconPath = os.path.expandvars(iconPath)
if not iconId:
return QICon(self.iconProvider.icon(QFileInfo(iconPath)))
iconRes = win32gui.ExtractIconEx(iconPath, iconId)
hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
hbmp = win32ui.CreateBitmap()
# I think there's a way to find available icon sizes, I'll leave it up to you
hbmp.CreateCompatibleBitmap(hdc, 32, 32)
hdc = hdc.CreateCompatibleDC()
hdc.SelectObject(hbmp)
hdc.DrawIcon((0, 0), iconRes[0][0])
hdc.DeleteDC()
# the original QtGui.QPixmap.fromWinHBITMAP is now part of the
# QtWin sub-module
return QtGui.QIcon(QtWin.fromWinHBITMAP(hbmp.GetHandle(), 2))
I use custom tags for my AWS instances. I am trying to list all the instances (running and stopped) in CSV file. Not being a programmer, I searched and copied/pasted codes and came with a script which runs well. But I have noticed that if one tag is missing then the script throws an error and stops right there. If the tag is created but is empty, then the script prints a blank space, but if the tag is not created at all then the script just stops. For example if the tag Owner is missing then it throws an error KeyError: 'Owner' and stops there. My script is pasted below. Can somebody let me know what changes I need to make so that if the tag does not exist, the script prints out N/A instead of stopping.
#!/usr/bin/env python
import boto.ec2
from boto.ec2 import EC2Connection
csv_file = open('/home/sbasnet/Scripts/Instances/instances_east.csv','w+')
def process_instance_list(connection):
map(build_instance_list,connection.get_all_instances())
def build_instance_list(reservation):
map(write_instances,reservation.instances)
def write_instances(instance):
if (instance.platform == 'windows'):
platform = 'Windows'
else:
platform = 'Linux'
csv_file.write("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"%(instance.id,instance.private_ip_address,instance.tags['Classification'],instance.tags['FQDN'],instance.tags['Owner'],instance.tags['RunType'],instance.instance_type,instance.subnet_id,instance.key_name,platform,instance.placement))
csv_file.flush()
if __name__=="__main__":
connection = EC2Connection(aws_access_key_id='ACCESS',aws_secret_access_key='SECRET')
process_instance_list(connection)
csv_file.close()
TIA
sbasnet
Maybe something like this will do?
Warning: untested
#!/usr/bin/env python
import boto.ec2
from boto.ec2 import EC2Connection
csv_file = open('/home/sbasnet/Scripts/Instances/instances_east.csv','w+')
def process_instance_list(connection):
map(build_instance_list,connection.get_all_instances())
def build_instance_list(reservation):
map(write_instances,reservation.instances)
def get_tag(tags, tag_name):
if tag_name in tags.keys():
return tags[tag_name]
else:
return "N/A"
def write_instances(instance):
if instance.platform == 'windows':
platform = 'Windows'
else:
platform = 'Linux'
csv_file.write("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"%(instance.id,
instance.private_ip_address,
get_tag(instance.tags, "Classification"),
get_tag(instance.tags, "FQDN"),
get_tag(instance.tags, "Owner"),
get_tag(instance.tags, "RunType"),
instance.instance_type,
instance.subnet_id,
instance.key_name,
platform,
instance.placement))
csv_file.flush()
if __name__=="__main__":
connection = EC2Connection(aws_access_key_id='ACCESS',aws_secret_access_key='SECRET')
process_instance_list(connection)
csv_file.close()
I am getting both the currently active window title and exe filepath with the code below
hwnd = win32gui.GetForegroundWindow()
_, pid = win32process.GetWindowThreadProcessId(hwnd)
if hwnd != 0 or pid != 0:
try:
hndl = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, 0, pid)
self.newExe = win32process.GetModuleFileNameEx(hndl, 0)
self.newWindowTitle = win32gui.GetWindowText(hwnd)
except:
self.newExe = ''
self.newWindowTitle = ''
the issue is that although it often is, the window title is not always the application name (the name the users understand as the main part of an application) and this is what I need. for example from calc.exe get Calculator withiout relying on the window title.
the purpose is to create a script that will log in an xml comparative use of any software on a computer
Is this possible?
Most Windows applications store information such as this inside their resource tables. There are API calls that can be used to extract this.
The following extracts the file description from a given application:
import win32api
def getFileDescription(windows_exe):
try:
language, codepage = win32api.GetFileVersionInfo(windows_exe, '\\VarFileInfo\\Translation')[0]
stringFileInfo = u'\\StringFileInfo\\%04X%04X\\%s' % (language, codepage, "FileDescription")
description = win32api.GetFileVersionInfo(windows_exe, stringFileInfo)
except:
description = "unknown"
return description
print(getFileDescription(r"C:\Program Files\Internet Explorer\iexplore.exe"))
The output is:
Internet Explorer
You could therefore pass the result of your call to win32process.GetModuleFileNameEx() to this function.
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.