Change wallpaper in Python for user while being system - python

what I am trying to do is change the desktop wallpaper in windows.
To do that, I use the following code:
import ctypes
import Image
pathToBmp = "PATH TO BMP FILE"
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, pathToBmp , 0)
this works when I run the .py file, this works when I convert it using py2exe and run the exe under the current user, but when I run the exe as SYSTEM, the current user background does not change.
This ofcourse was to be expected. But I don't know how to solve it.
By the way, it does not matter if any of your solutions changes the current user background or all the users' backgrounds.
Thank you for your time.

How about creating a value key in the registry at:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
This will change the background when ever the user login.
To try it, write this script, name it for example SetDesktopBackground.py, any where you like:
#!python
from ctypes import *
from os import path
SPI_SETDESKWALLPAPER = 0x14
SPIF_UPDATEINIFILE = 0x1
lpszImage = path.join(path.dirname(path.realpath(__file__)), 'your_image.jpg')
SystemParametersInfo = windll.user32.SystemParametersInfoA
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, lpszImage, SPIF_UPDATEINIFILE)
Dont forgot to put some image, your_image.jpg, in the same directory. Then open the registery editor:
Start > Search > type regedit.exe
Then go to the path:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
Right click and choose New > String Value and type any name you like for this value.
Right click on this new value and choose Modify, in the Data Value field write:
"C:\Python26\pythonw.exe" "C:\Path\To\SetDesktopBackground.py"
To test it, logout and login again. The background should change when ever this user login.
That was the manual way to do it, you can use _winreg in your application to create the value during the installation:
#!python
from _winreg import *
from sys import executable
from os import path
subkey = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
script = 'C:\\Path\\To\\SetDesktopBackground.py'
pythonw = path.join(path.dirname(executable), 'pythonw.exe')
hKey = OpenKey(HKEY_CURRENT_USER, subkey, 0, KEY_SET_VALUE)
SetValueEx(hKey, 'MyApp', 0, REG_SZ, '"{0}" "{1}"'.format(pythonw, script))
CloseKey(hKey)

Related

Cannot click on tkinter button more than twice

I am a newbie to tkinter and have know idea what I am doing sometimes:D . I created a python script to get Corona Virus Stats from a GitHub post link The script has over 20 files in it so I thought I should just create one file to run all the other files. So what other better way to do it than creating a UI. And that's what I did I used tkinter to run all the files. If they clicked on x button then I would run abc. And I ended up running these files by importing them in a certain order(Don't know If that was the best way). So here is where I ran into an error. I don't exactly know if this error is because of how I imported my files or my tkinter code is just wrong. I just couldn't seem to click on a button twice. I would run my program and click on a button, it would run properly and then the next time I clicked on that same button It would just not work. There was no error and no output. Nothing would happen. Here is my code:
#Import tkinter
import tkinter as tk
from tkinter import *
from tkinter import simpledialog
tk = tk.Tk()
Max = 190
def RunDeaths():
#If they click on RunDeaths I will run this function
#Check if they have already entered a path
try:
open('/Users/test/Documents/python/Py_Programs/Hackathon/DeathStats/Info.txt','r')
from DeathStats import RunAll
except:
YourPath = simpledialog.askstring('Countries','''Please Enter Your Path To HACKATHON Folder:
Example:
\"/Users/Name/Documents/python/\"
Note: Leave out the HACKATHON folder and you must put a slash at the end''',parent=tk)
#Write this path to a file call Info.txt
file = open('/Users/test/Documents/python/Py_Programs/Hackathon/DeathStats/Info.txt','w')
file.write(str(YourPath)+'\n')
file.write(str(Max))
file.close()
#Run all the files that gather the data for Corona Virus Deaths
from DeathStats import RunAll
def RunRecoveredCases():
#If they click on RecoveredCases Run this
#Check If they had already entered a path
try:
open('/Users/test/Documents/python/Py_Programs/Hackathon/RecoveredCases/Info.txt','r')
from RecoveredCases import RunAll
except:
YourPath = simpledialog.askstring('Countries','''Please Enter Your Path To HACKATHON Folder:
Example:
\"/Users/Name/Documents/python/\"
Note: Leave out the HACKATHON folder and you must put a slash at the end''',parent=tk)
file = open('/Users/test/Documents/python/Py_Programs/Hackathon/RecoveredCases/Info.txt','w')
#Write there path to a file
file.write(str(YourPath)+'\n')
file.write(str(Max))
file.close()
#Run all the files that gather all the Recovered Cases
from RecoveredCases import RunAll
#* * Here is where I think I went wrong But Im not sure
Deaths = Button(tk,height = 20, width = 30, text='Run Deaths',command = RunDeaths,highlightbackground='#000000')
Recovered = Button(tk,height = 20, width = 30, text='Run Recovered Cases',command = RunRecoveredCases,highlightbackground='#000000')
Deaths.pack()
Recovered.pack()
tk.mainloop()
So my question and problem is: Why can I not click on a button more than twice?
This has happened to me before and I could not fix it. Any help would be appreciated.(If you would like to run my program because my explanation was just not good enough here is a git hub repo GitHub)
Thank You
It appears that you are assuming that from RecoveredCases import RunAll will run the code in RecoveredCases.py each time it is imported. That is a false assumption. Python caches code that is imported.
The proper way to use code in a separate file is to put the code in a function or class, import the function or class exactly once, and then call the function or instantiate the class whenever you want to run the code.

QGIS3.14 Resource Sharing symbols are not appearing in atlas export via standalone python script

I created a standalone python script to export my atlas layouts. Everything is working great except that the SVG symbols that I am using from the Resource Sharing plugin are just question marks, assuming that it is having trouble locating them. However, if I run the script via the startup.py in the QGIS3 folder everything works like expected. I would really like to avoid using this method though as it prevents you from using QGIS until the script finishes, which takes about 2 hours. I am hoping that I just need to add a simple environmental variable to my .bat file so that it can locate the Resource Sharing plugin. Thanks in advance for any help!
.bat file
#ECHO off
set OSGEO4W_ROOT=C:\OSGeo4W64
call "%OSGEO4W_ROOT%\bin\o4w_env.bat"
call "%OSGEO4W_ROOT%\bin\qt5_env.bat"
call "%OSGEO4W_ROOT%\bin\py3_env.bat"
path %OSGEO4W_ROOT%\apps\qgis\bin;%PATH%
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis
set GDAL_FILENAME_IS_UTF8=YES
set VSI_CACHE=TRUE
set VSI_CACHE_SIZE=1000000
set QT_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\qgis\qtplugins;%OSGEO4W_ROOT%\apps\qt5\plugins
SET PYCHARM="C:\Program Files\JetBrains\PyCharm 2019.2.3\bin\pycharm64.exe"
set PYTHONPATH=%OSGEO4W_ROOT%\apps\qgis\python
set PYTHONHOME=%OSGEO4W_ROOT%\apps\Python37
set PYTHONPATH=%OSGEO4W_ROOT%\apps\Python37\lib\site-packages;%PYTHONPATH%
set QT_QPA_PLATFORM_PLUGIN_PATH=%OSGEO4W_ROOT%\apps\Qt5\plugins\platforms
set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis
start "PyCharm aware of QGIS" /B %PYCHARM% %*
Python Script
from qgis.core import QgsApplication, QgsProject, QgsLayoutExporter
import os
import sys
def export_atlas(qgs_project_path, layout_name, outputs_folder):
# Open existing project
project = QgsProject.instance()
project.read(qgs_project_path)
print(f'Project in "{project.fileName()} loaded successfully')
# Open prepared layout that as atlas enabled and set
layout = project.layoutManager().layoutByName(layout_name)
# Export atlas
exporter = QgsLayoutExporter(layout)
settings = QgsLayoutExporter.PdfExportSettings()
exporter.exportToPdfs(layout.atlas(), outputs_folder, settings)
def run():
# Start a QGIS application without GUI
QgsApplication.setPrefixPath(r"C:\\OSGeo4W64\\apps\\qgis", True)
qgs = QgsApplication([], False)
qgs.initQgis()
sys.path.append(r'C:\OSGeo4W64\apps\qgis\python\plugins')
project_path = [project_path]
output_folder = [export_location]
layout_name_portrait = [portrait layout name]
layout_name_landscape = [landscape laytout name]
export_atlas(project_path, layout_name_portrait, output_folder)
export_atlas(project_path, layout_name_landscape, output_folder)
# Close the QGIS application
qgs.exitQgis()
run()
I guess that it might have something to do with the setting svg/searchPathsForSVG.
QgsSettings().setValue('svg/searchPathsForSVG', <your path>)

How to get default browser name using python?

Following solutions (actually it is only one) doesn't work to me :
How to get a name of default browser using python
How to get name of the default browser in windows using python?
Solution was:
from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValue
# In Py3, this module is called winreg without the underscore
with OpenKey(HKEY_CURRENT_USER,
r"Software\Classes\http\shell\open\command") as key:
cmd = QueryValue(key, None)
But unfortunately, in Windows 10 Pro I don't have targeted registry value. I've tried to find alternative keys in Regedit, but no luck.
Please take a look, what my registry virtually contains:
The following works for me on Windows 10 pro:
from winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx
reg_path = r'Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice'
with OpenKey(HKEY_CURRENT_USER, reg_path) as key:
print(QueryValueEx(key, 'ProgId'))
Result (first with Chrome set as default, then with IE):
$ python test.py
('ChromeHTML', 1)
$ python test.py
('IE.HTTPS', 1)
Please check for the key in windows 10
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\Shell\Associations\URLAssociations(http|https)\UserChoice
def get_windows_default_browser_launch():
""" On windows, return the default browser for 'https' urls
returns: example '"C:\Program Files\Mozilla Firefox\firefox.exe" -osint -url "%1"'
"""
import winreg
key = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER), r"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice")
prog_id, _ = winreg.QueryValueEx(key, "ProgId")
key = winreg.OpenKey(winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE), r"SOFTWARE\Classes\{}\shell\open\command".format(prog_id))
launch_string, _ = winreg.QueryValueEx(key, "") # read the default value
return launch_string
Windows 10 Python3 , may want to change the key for 'http' not https, but this is my code verbatim as my context is of a secured server. I wanted the browser binary name and path, which is just one more line.

Can't create user site-packages directory for usercustomize.py file

I need to add the win_unicode_console module to my usercustomize.py file, as described by the documentation.
I've discovered my user site packages directory with:
>>> import site
>>> site.getusersitepackages()
'C:\\Users\\my name\\AppData\\Roaming\\Python\\Python35\\site-packages'
I haven't been able to get to this directory using any method. I've tried using pushd instead of cd to emulate a network drive, and I've also tried getting there using run. No matter what I do in python, or in cmd terminal. I get the response The network path was not found.
Here is an example of one I've tried in cmd:
C:\>pushd \\Users\\my name\\AppData\\Roaming\\Python\\Python35\\site-packages
The network path was not found.
What am I doing wrong, or what could be wrong with the path?
DOS style backslashes don't need to be escaped within the Windows console (else they may have used forward slashes way back when!).
Follow these steps to manually create usercustomize.py:
Start->Run:cmd
Make sure you're on the C: drive
c:
Create the directory. mkdir creates the missing parents. Obviously, change "my name" as appropriate.
mkdir C:\Users\my name\AppData\Roaming\Python\Python35\site-packages
Create usercustomize.py:
notepad C:\Users\my name\AppData\Roaming\Python\Python35\site-packages\usercustomize.py
Click "yes" to create your file.
Edit as appropriate
Or use the following script to have Python do it for you:
import site
import os
import os.path
import io
user_site_dir = site.getusersitepackages()
user_customize_filename = os.path.join(user_site_dir, 'usercustomize.py')
win_unicode_console_text = u"""
# win_unicode_console
import win_unicode_console
win_unicode_console.enable()
"""
if os.path.exists(user_site_dir):
print("User site dir already exists")
else:
print("Creating site dir")
os.makedirs(user_site_dir)
if not os.path.exists(user_customize_filename):
print("Creating {filename}".format(filename=user_customize_filename))
file_mode = 'w+t'
else:
print("{filename} already exists".format(filename=user_customize_filename))
file_mode = 'r+t'
with io.open(user_customize_filename, file_mode) as user_customize_file:
existing_text = user_customize_file.read()
if not win_unicode_console_text in existing_text:
# file pointer should already be at the end of the file after read()
user_customize_file.write(win_unicode_console_text)
print("win_unicode_console added to {filename}".format(filename=user_customize_filename))
else:
print("win_unicode_console already enabled")

how to access SHOpenFolderAndSelectItems() by ctypes

I want to build a cross-platform application ,I used a windows API called SHOpenFolderAndSelectItems(). Although I found example called it by pywin32,but pywin32 is not available on Linux , I don't want to call a Windows API on linux,just don't want to make another code version for Linux,so I wonder how to access it by ctypes? yes,this API cannot be called on Linux ,I just want to make it silent in the code so that I can freeze the Python scripts into executables by cx_Freeze without pywin32 module-missing error happend .
from win32com.shell import shell, shellcon
import os
def launch_file_explorer(path, files):
'''
Given a absolute base path and names of its children (no path), open
up one File Explorer window with all the child files selected
'''
folder_pidl = shell.SHILCreateFromPath(path,0)[0]
desktop = shell.SHGetDesktopFolder()
shell_folder = desktop.BindToObject(folder_pidl, None,shell.IID_IShellFolder)
name_to_item_mapping = dict([(desktop.GetDisplayNameOf(item, shellcon.SHGDN_FORPARSING|shellcon.SHGDN_INFOLDER), item) for item in shell_folder])
print(name_to_item_mapping)
to_show = []
for file in files:
if file in name_to_item_mapping:
to_show.append(name_to_item_mapping[file])
# else:
# raise Exception('File: "%s" not found in "%s"' % (file, path))
shell.SHOpenFolderAndSelectItems(folder_pidl, to_show, 0)
p=r'E:\aa'
print(os.listdir(p))
launch_file_explorer(p, os.listdir(p))

Categories

Resources