Extract icon from shortcut (.lnk) file in Python? - python

I'm trying to extract the icons from all of the shortcuts in the Start Menu folder. So far I've managed to walk the directory tree, and I just need something to extract the icon from each shortcut. I've tried a few methods suggested across the internet, but I can't seem to make it work fully.
Method 1: Using a program called ResourcesExtract through os.system() to extract the icon from the .lnk file. I soon discovered that this doesn't work for .lnk files, only .exe or .dlls.
import os
os.system(f"resourcesextract.exe /source {shortcut}")
Method 2: Extracting the icon file from the targets of the shortcuts (which can be obtained quite easily using the pywin32 library) using ResourcesExtract. Unfortunately, this only works for some of the programs, due to some shortcuts pointing to .exes without icons.
import os
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
target = shell.CreateShortCut(shortcut).TargetPath
os.system(f"resourcesextract.exe /source {target}")
Method 3: Using pywin32 to get the icon directory. This only works for around 120 of the 300 shortcuts I need it to work on.
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
icon, status = str(shell.CreateShortCut(shortcut).IconLocation).split(",")
I also came across a way to do it using the .NET framework, but I don't know how to interface that with python or if it will even work.
Is anyone aware of a method to extract icons from .lnk files in Python that works on all shortcuts?

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
ShortCut = shell.CreateShortCut('example.lnk')
icon_location = ShortCut.IconLocation
It work for me.

Related

Simple Windows Popup Window using Python

I am trying to find the easiest (with shortest code) way of displaying a popup dialog window in Windows in my non-GUI Python 3.7 program. Basically, it tries to find and grab control of a window with a particular name. If it finds the window, it does its thing and all is good. If it doesn't find the window I'd like a wee popup message saying "Window not found". I know I can do this using PyQt5 or similar, but it is an awful lot of code just display a dialog!
You could do
import ctypes
mymessage = 'A message'
title = 'Popup window'
ctypes.windll.user32.MessageBoxA(0, mymessage, title, 0)
ctypes is part of the standard library, so this works on Windows without the need to install any packages.
A most simple way I could think of (not necessarily elegant) would be creating a .vbs file and calling MsgBox from there
MsgBox "Window not found!", 65, "Information"
Then call that file from Python using
>>> import os
>>> os.system("call popupmessage.vbs")
However, this is not cross-platform, but I assume you are using Windows.
Also keep in mind the directory in the os.system call is relative to your working directory unless you specify the full (or absolute) directory.
You should refer to https://www.tutorialspoint.com/vbscript/vbscript_dialog_boxes.htm on how to use MsgBox

How do you start a python code using keyboard

Is there a way to start a python code automatically when a set of keyboard presses are made?
context:
I want to be able to hit control v (or any other custom key binds) inside a specific folder and the script will run which will result in the picture that I have stored in my clipboard will be automatically made to a jpg.
this is the script that I am using to convert the picture in my clipboard to a png
from PIL import ImageGrab
from datetime import datetime
import os
im = ImageGrab.grabclipboard()
date_now = datetime.now().strftime('%c')
im.save(f'{os.path.dirname(os.path.abspath(__file__))}/{str(date_now)}.png','PNG')
P.S. this is because I am tired of getting a screenshot and then needing to open paint to just image and saving it.
You can do it using another python script that runs all the time:
$pip install keyboard
import keyboard as k
import os
# function to run your python script after keyboard shortcut
def run_script(path_to_file):
os.system("cmd /k python " + path_to_file)
#add hot key for you shortcut
k.add_hotkey('ctrl+shift+a', run_script, args=["enter your path to file here"])
k.wait()
Or else if you are using Windows, create a shortcut for your python script (right click it and then "Create shortcut"), right click the shortcut file you just created and click "Properties", then go to the "Shortcut" tab and click the "Shortcut key:" box, and finally type the combination that you want. if it seems like its not working, than its probably because the python file has no wait on the end of it, so it executes but then immediately closes.
i think this is related to the operating system or window manager you use. For example: in XFCE you'll find it under applications / settings / keyboard / shortcuts. (or something like that.. my desktop is held in German language..)
under Windows you can make a desktop link to your software. When you edit it you can set a shortcut for running this, too.
try to ask google for something like
[your os] shortcut for program

Automate .exe program with Python

I have a .exe program that is converting an AGS file to an Excel file.
I have a lot of files to convert so I'm wondering can I automate this with Python? The convert-program only requires 2 locations, one for the input and one for the output, see the picture.
With Python I'm albe to start the program with the following code, but is it possible to pass the 2 path's and click Export.
import subprocess
path = r'C:\Program Files (x86)\AGSToExcel.exe'
#Start the programs
subprocess.call([path])
#other locations
path_ags = r'C:\Users\X\Documents\AGS_file1.ags'
path_excel = r'C:\Users\X\Documents\Book1.xls'
I'm fairly new with package subprocess so I have not a clue if this is even possible.
You can probably use pyautogui to click and type if needed.
You can see a simple example here.
PyAutoGUI EXAMPLE

Specify Input File in SPSS Statistics

In older versions of SPSS, one could ask for the path to a file using a syntax similar to this:
filename = GetFilePath("*.txt","txt", ,"Specify input file",0)
How can I achieve the same result using recent versions of SPSS, that rely on Python?
I found the answer. So similarly to how the VBA in .SBS script works, Python can use a library directly from SPSS to show a file input dialog.
BEGIN PROGRAM.
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
print(filename)
END PROGRAM.
sbs/wwd scripts are still supported on Statistics.
As for the prompt, you could create a wwd/sbs dialog to prompt for the file name and then open it, or, without using scripting, you could create a custom dialog box using the Custom Dialog Builder (on Utilities) containing a Browse control and issue a GET command.
If you want this to happen when Statistics is launched, you can create a startup script or use the STATS PROJECT extension command, depending on exactly what you want to do.
I am not aware of SPSS Statistics ever having a function such as GetFilePath, but you can use the Python spssaux.getDatasetInfo function for this, e.g., in a program write
import spssaux
filename = spssaux.getDatasetInfo()

PyQt v4.8.2 + Python 3...Icons only showing on dev-machine

I wrote a little app with a gui to analyze xml files. I have 2 .py files where 1 is the GUI and the second handels the xml.
My Problem is that the Icons i set and also a gif that i show using QMovie are not showing up on any machine but my development machine.
The other machines do not have PyQt or Python installed. They are using my Installation-folder from Python that I've copied onto a network drive. The i just copied the python32.dll in the machines system32 folder and the app works...except for the icons.
That's how i set the icons and reference the gif:
self.setWindowIcon(QtGui.QIcon("grabb.ico"))
--------other code---------
self.movie = QMovie("load.gif", QByteArray(), self)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie.setSpeed(100)
self.movie_screen.setMovie(self.movie)
self.movie.start()
The file is in the same dir as the py so this should work. I've also tried absolute paths but that didn't give me any better results.
Now i have read on stack that this could be resolved by using the ressource-system.
So i used the designer to create a ressource files and then compiled it using pyrcc4 into a .py (using the parameter for python 3). Now I'm reffering to the images like this:
self.setWindowIcon(QtGui.QIcon(":icon/grabber.ico"))
--------other code---------
self.movie = QMovie(":loader/load.gif", QByteArray(), self)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie.setSpeed(100)
self.movie_screen.setMovie(self.movie)
self.movie.start()
This again works fine on my machine but nowhere else.
Any ideas as to why only ma machine shows the icons ?
I'm not using py2exe or alike!
I too came across the same situation.
One approach is to set the paths in qt.config file and place this in the location of your executable.
I tested this with Python 2.6, and its working fine without any issue.
You said that you have shared your python installation which has PyQt4 init.
Lets say you python share path is \\somesystem\Python26
Yo will find a qt.config file in \\somesystem\Python26\PyQt4. Take it and replace the below lines in qt.conf
[Paths]
Prefix = //somesystem/Python26/PyQt4
Binaries = //somesystem/Python26/PyQt4

Categories

Resources