def execute(self, *args, env: dict = None) -> bool: if not env: env = os.environ # initialize self._S = api.Session # get publish version of celaction app = "celaction_publish" # get context variables project = self._S["AVALON_PROJECT"] = env["AVALON_PROJECT"] asset = self._S["AVALON_ASSET"] = env["AVALON_ASSET"] task = self._S["AVALON_TASK"] = env["AVALON_TASK"] workdir = self._S["AVALON_WORKDIR"] = env["AVALON_WORKDIR"] # get workfile path anatomy_filled = self.get_anatomy_filled() workfile = anatomy_filled["work"]["file"] version = anatomy_filled["version"] # create workdir if doesn't exist os.makedirs(workdir, exist_ok=True) self.log.info(f"Work dir is: `{workdir}`") # get last version of workfile workfile_last = get_last_version_from_path( workdir, workfile.split(version)) if workfile_last: workfile = workfile_last workfile_path = os.path.join(workdir, workfile) # copy workfile from template if doesnt exist any on path if not os.path.isfile(workfile_path): # try to get path from environment or use default # from `pype.celation` dir template_path = env.get("CELACTION_TEMPLATE") or os.path.join( env.get("PYPE_MODULE_ROOT"), "pype/hosts/celaction/celaction_template_scene.scn" ) self.log.info( f"Creating workfile from template: `{template_path}`") shutil.copy2( os.path.normpath(template_path), os.path.normpath(workfile_path) ) self.log.info(f"Workfile to open: `{workfile_path}`") # adding compulsory environment var for openting file env["PYPE_CELACTION_PROJECT_FILE"] = workfile_path # setting output parameters path = r"Software\CelAction\CelAction2D\User Settings" winreg.CreateKey(winreg.HKEY_CURRENT_USER, path) hKey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\CelAction\\CelAction2D\\User Settings", 0, winreg.KEY_ALL_ACCESS) # TODO: change to root path and pyblish standalone to premiere way pype_root_path = os.getenv("PYPE_SETUP_PATH") path = os.path.join(pype_root_path, "pype.bat") winreg.SetValueEx(hKey, "SubmitAppTitle", 0, winreg.REG_SZ, path) parameters = [ "launch", f"--app {app}", f"--project {project}", f"--asset {asset}", f"--task {task}", "--currentFile \\\"\"*SCENE*\"\\\"", "--chunk *CHUNK*", "--frameStart *START*", "--frameEnd *END*", "--resolutionWidth *X*", "--resolutionHeight *Y*", # "--programDir \"'*PROGPATH*'\"" ] winreg.SetValueEx(hKey, "SubmitParametersTitle", 0, winreg.REG_SZ, " ".join(parameters)) # setting resolution parameters path = r"Software\CelAction\CelAction2D\User Settings\Dialogs" path += r"\SubmitOutput" winreg.CreateKey(winreg.HKEY_CURRENT_USER, path) hKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(hKey, "SaveScene", 0, winreg.REG_DWORD, 1) winreg.SetValueEx(hKey, "CustomX", 0, winreg.REG_DWORD, 1920) winreg.SetValueEx(hKey, "CustomY", 0, winreg.REG_DWORD, 1080) # making sure message dialogs don't appear when overwriting path = r"Software\CelAction\CelAction2D\User Settings\Messages" path += r"\OverwriteScene" winreg.CreateKey(winreg.HKEY_CURRENT_USER, path) hKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(hKey, "Result", 0, winreg.REG_DWORD, 6) winreg.SetValueEx(hKey, "Valid", 0, winreg.REG_DWORD, 1) path = r"Software\CelAction\CelAction2D\User Settings\Messages" path += r"\SceneSaved" winreg.CreateKey(winreg.HKEY_CURRENT_USER, path) hKey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(hKey, "Result", 0, winreg.REG_DWORD, 1) winreg.SetValueEx(hKey, "Valid", 0, winreg.REG_DWORD, 1) return True
def login(steamid, lock=False, _app=False, force=False): eel.info("使用模擬登入", "steamid:" + steamid + "\n強制模式:" + ("是" if force else "否"), "console") acc = call_info(steamid) if (force == False and (steamid in get_client_users())): eel.info("模式切換", "偵測到快取模式\n轉為快取模式", "console") auto_login(steamid, acc["name"], lock) return if (acc == False): eel.info("無帳號", "", "error") if (lock != False): lock.release() return "no_account" key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\Valve\Steam", 0, winreg.KEY_QUERY_VALUE) exe, t = winreg.QueryValueEx(key, "SteamExe") winreg.CloseKey(key) si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW if (_app == False): #如果沒有到拾取app eel.info("關閉steam", "", "console") close_steam(exe, si) # str replace password = str.replace(acc["password"], "{", "{{}") password = str.replace(password, " ", "{SPACE}") password = str.replace(password, "+", "{+}") password = str.replace(password, "^", "{^}") password = str.replace(password, "%", "{%}") # set RememberPassword key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "SOFTWARE\Valve\Steam", 0, winreg.KEY_SET_VALUE) winreg.SetValueEx(key, "RememberPassword", 0, winreg.REG_DWORD, 0x00000001) winreg.SetValueEx(key, "AutoLoginUser", 0, winreg.REG_SZ, "") winreg.CloseKey(key) # auto login if (_app == False): app = APP().start(exe) else: app = _app login_gui = app.window(title_re='Steam [^Guard].*', class_name='vguiPopupWindow') try: login_gui.wait("ready", 30) except timings.TimeoutError: eel.info("等待超時", "", "console") del app if (lock != False): lock.release() return "error" eel.info("自動登入", "登入頁面 已就緒\n開始自動輸入", "console") login_gui.set_focus() sleep(.1) if (_app == False): eel.info("自動輸入名稱 [未輸入名稱]", "", "console") keyboard.send_keys(acc["name"] + """{TAB}""") eel.info("自動輸入密碼", "", "console") keyboard.send_keys(password) keyboard.send_keys("""{TAB}{ENTER}""") if (acc["se"] == False): #guard eel.info("無guard", "跳過guard登入頁面", "console") else: eel.info("等待guard", "已添加guard\n自動輸入guard", "console") sa = guard.SteamAuthenticator(acc["se"]) guard_gui = app.window(title_re='Steam Guard - .*', class_name='vguiPopupWindow') guard_gui.wait("ready") guard_gui.set_focus() sleep(.1) code = sa.get_code() keyboard.send_keys(code + """{ENTER}""") eel.info("等待登入頁面被關閉", "", "console") login_gui.wait_not("visible", 60000) eel.info("登入完成", "", "console") del app if (lock != False): lock.release()
# time because it hasn't been built yet if sys.platform == "win32" and hasattr(sys, "_MEIPASS"): # we update the location of circleguard.exe every time we run, so if the user # ever moves it we'll still correctly redirect the url scheme event to us. # I have no idea how other (professional) applications handle this, nor # what the proper way to update your url scheme registry is (should it # ever be done?). exe_location = str(Path(sys._MEIPASS) / "circleguard.exe") # pylint: disable=no-member # most sources I found said to modify HKEY_CLASSES_ROOT, but that requires # admin perms. Apparently that registry is just a merger of two other # registries, which *don't* require admin persm to write to, so we write # there. See https://www.qtcentre.org/threads/7899-QSettings-HKEY_CLASSES_ROOT-access?s=3c32bd8f5e5300b83765040c2d100fe3&p=42379#post42379 # and https://support.shotgunsoftware.com/hc/en-us/articles/219031308-Launching-applications-using-custom-browser-protocols key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\\Classes\\circleguard") # empty string to set (default) value winreg.SetValueEx(key, "", 0, winreg.REG_SZ, "URL:circleguard Protocol",) winreg.SetValueEx(key, "URL Protocol", 0, winreg.REG_SZ, "") key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\\Classes\\circleguard\\DefaultIcon") winreg.SetValueEx(key, "", 0, winreg.REG_SZ, exe_location) key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\\Classes\\circleguard\\shell\\open\\command") winreg.SetValueEx(key, "", 0, winreg.REG_SZ, exe_location + " \"%1\"") # if we're launching this with arguments, it's almost certainly because it # got called from a circleguard:// url. But if we're not, the user is almost # certainly launching it manually, after already having one instance open. # in the latter case we want to launch normally instead of accessing argv, # which would error. # Addittionally, we don't want to mess with sockets AT ALL if cg is being
def install(self, patch=False, documents=""): try: #print "\n\nInstalling - please wait.." dccItems = self.tw_components.findItems( "DCC integrations", Qt.MatchExactly | Qt.MatchRecursive) if len(dccItems) > 0: dccItem = dccItems[0] else: dccItem = None result = {} if dccItem is not None: for i in range(dccItem.childCount()): childItem = dccItem.child(i) if not childItem.text(0) in self.plugins: continue installPaths = self.plugins[childItem.text( 0)].installerExecute(childItem, result, self.core.installLocPath) if type(installPaths) == list: for k in installPaths: self.core.integrationAdded(childItem.text(0), k) self.core.appPlugin.createWinStartMenu(self) if platform.system() == "Windows": # setting regestry keys for wand module (EXR preview in Blender and Nuke) curkey = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\ImageMagick\Current") _winreg.SetValueEx(curkey, "Version", 0, _winreg.REG_SZ, "6.9.9") key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\ImageMagick\6.9.9\Q:16") _winreg.SetValueEx( key, "LibPath", 0, _winreg.REG_SZ, os.path.join(self.core.prismRoot, "Tools", "ImageMagick-6.9.9-Q16")) _winreg.SetValueEx( key, "CoderModulesPath", 0, _winreg.REG_SZ, os.path.join(self.core.prismRoot, "Tools", "ImageMagick-6.9.9-Q16", "modules", "coders")) _winreg.SetValueEx( key, "FilterModulesPath", 0, _winreg.REG_SZ, os.path.join(self.core.prismRoot, "Tools", "ImageMagick-6.9.9-Q16", "modules", "filters")) key.Close() curkey.Close() #print "Finished" if not False in result.values(): QMessageBox.warning(self.core.messageParent, "Prism Installation", "Prism was installed successfully.") else: msgString = "Some parts failed to install:\n\n" for i in result: msgString += "%s:\t\t%s\t\t\n\n" % (i, result[i]) msgString = msgString.replace("True", "Success").replace( "False", "Error") QMessageBox.warning(self.core.messageParent, "Prism Installation", msgString) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() msg = QMessageBox( QMessageBox.Warning, "Prism Installation", "Errors occurred during the installation.\n The installation is possibly incomplete.\n\n%s\n%s\n%s" % (str(e), exc_type, exc_tb.tb_lineno), QMessageBox.Ok) msg.setFocus() msg.exec_() return False
def addstartup(): # check if it is linux if os_type == 'Linux' or os_type == 'FreeBSD' or os_type == 'OpenBSD': entry = \ '''[Desktop Entry] Name=Persepolis Download Manager Name[fa]=پرسپولیس Comment=Download Manager GenericName=Download Manager GenericName[fa]=نرم افزار مدیریت بارگیری Keywords=Internet;WWW;Web; Terminal=false Type=Application Categories=Qt;Network; StartupNotify=true Exec=persepolis --tray Icon=persepolis StartupWMClass=persepolis-download-Manager ''' # check if the autostart directry exists & create entry if os.path.exists(home_address + "/.config/autostart"): startupfile = open( home_address + "/.config/autostart/persepolis.desktop", 'w+') startupfile.write(entry) os.chmod(home_address + "/.config/autostart/persepolis.desktop", 0o644) if not os.path.exists(home_address + "/.config/autostart"): os.makedirs(home_address + "/.config/autostart", 0o755) startupfile = open( home_address + "/.config/autostart/persepolis.desktop", 'w+') startupfile.write(entry) os.chmod(home_address + "/.config/.autostart/persepolis.desktop", 0o644) # check if it is mac elif os_type == "Darwin": # OS X cwd = sys.argv[0] cwd = os.path.dirname(cwd) entry = '''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.persepolisdm.persepolis</string> <key>Program</key> <string>''' + cwd + '''/Persepolis Download Manager</string> <key>ProgramArguments</key> <array> <string>--tray</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist>\n''' startupfile = open( home_address + '/Library/LaunchAgents/com.persepolisdm.plist', 'w+') startupfile.write(entry) os.system('launchctl load ' + home_address + "/Library/LaunchAgents/com.persepolisdm.plist") # check if it is Windows elif os_type == "Windows": # Connect to the startup path in Registry key = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, winreg.KEY_ALL_ACCESS) # find current persepolis exe path cwd = os.getcwd() persepolisexetray = '"' + cwd + '\Persepolis Download Manager.exe' + '"' + ' --tray' # add persepolis to startup winreg.SetValueEx(key, 'persepolis', 0, winreg.REG_SZ, persepolisexetray) # Close connection winreg.CloseKey(key)
"""隐藏win10资源管理器中视频、图片、文档、下载、音乐、桌面、3D对象七个文件夹 """ import winreg Explorer = winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer') key = winreg.OpenKey(Explorer, r'FolderDescriptions') names = ( '{0ddd015d-b06c-45d5-8c4c-f59713854639}', # 图片 '{35286a68-3c57-41a1-bbb1-0eae73d76c95}', # 视频 '{7d83ee9b-2244-4e70-b1f5-5393042af1e4}', # 下载 '{a0c69a99-21c8-4671-8703-7934162fcf1d}', # 音乐 '{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}', # 桌面 '{f42ee2d3-909f-4907-8871-4c22fc0bf756}', # 文档 ) for name in names: child = winreg.OpenKey(key, name + r'\PropertyBag', 0, winreg.KEY_ALL_ACCESS) # print(winreg.QueryValueEx(child, "ThisPCPolicy")) winreg.SetValueEx(child, "ThisPCPolicy", 0, 1, "Hide") # 3D对象 NameSpace = winreg.OpenKey(Explorer, r'MyComputer\NameSpace') winreg.DeleteKey(NameSpace, '{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}')
# -*- coding: utf-8 -*- import winreg keyVal = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion" valName = 'PythonTest' hKey = 'HKEY_CURRENT_USER\\' try: key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, keyVal, 0, winreg.KEY_ALL_ACCESS) print('Create test key...\n') except: key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, keyVal) winreg.SetValueEx(key, "PythonTest", 0, winreg.REG_DWORD, 0xFFFFFFFF) # Get Value val = winreg.QueryValueEx(key, "PythonTest") print(valName, ':', val[0], '\nType', ':', val[1], '\nPath', ':', hKey + keyVal + '\n') ########## winreg.DeleteValue(key, "PythonTest") print('Remove test key...') winreg.CloseKey(key)
# To Block or Unblock all the usb ports that are unused import winreg try: key = winreg.CreateKeyEx( winreg.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\USBSTOR", reserved=0, access=winreg.KEY_ALL_ACCESS) # Creating a key object ans = input( 'To block all usb ports enter B\n To unblock all usb ports enter U\n To exit the GUI enter Q\n' ) while ans != 'Q': if ans == 'B': winreg.SetValueEx(key, 'Start', 0, winreg.REG_DWORD, 4) # To block all ports print('All usb ports blocked') elif ans == 'U': winreg.SetValueEx(key, 'Start', 0, winreg.REG_DWORD, 3) # To unblock all ports print('All usb ports unblocked') else: print('''You've Entered WRONG value, Please try again''') ans = input('Enter the new decision\n') winreg.CloseKey(key) except: print( '''You've run into some problem,, Please contact the author for further instructions''' )
try: Sub_key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, NETWORK_REG_PATH + '\\' + Enum, 0, winreg.KEY_ALL_ACCESS) except OSError: pass for reg in regex: if re.match(reg, winreg.EnumValue(Sub_key, 0)[1]): try: winreg.DeleteValue(Sub_key, 'NetworkAddress') except: print('Cannot delete sub key.') MAC_VALUE = randbit(12) winreg.SetValueEx(Sub_key, 'NetworkAddress', 0, winreg.REG_SZ, MAC_VALUE) print(f"MAC Address changed. Value : {MAC_VALUE}") winreg.CloseKey(Sub_key) KEYFIND = True break else: KEYFIND = False pass if KEYFIND == True: break print('network will be restart...') subprocess.call('netsh interface set interface name = "이더넷" admin=disabled') subprocess.call('netsh interface set interface name = "이더넷" admin=enable')
def __setitem__(self, name, value): """Item assignment sets key values.""" self.sam |= KEY_SET_VALUE if not isinstance(value, Value): value = Value(value, name) _winreg.SetValueEx(self.hkey, name, 0, value.type, value.data)
import ctypes import random import os import winreg # put script to "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup" # check "D:\Home\Pictures" if there are wp?.jpg image count = 0 for name in os.listdir('D:\Home\Pictures'): a,b = name.split('.') if 'wp' in a and 'jpg' == b: count+=1 regKey = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, winreg.KEY_SET_VALUE) winreg.SetValueEx(regKey, "WallpaperStyle", 0, winreg.REG_SZ, "0") winreg.SetValueEx(regKey, "TileWallpaper", 0, winreg.REG_SZ, "0") ctypes.windll.user32.SystemParametersInfoW(20, 0, "D:\Home\Pictures\wp%d.jpg" % random.randrange(count) , 3)
import winreg import os appdata_dir = r'C:\Users\prana\AppData\Local\Programs\Python\Python39\python.exe" "D:\prana\Programming\My Projects\Pikturit\pikturit.py' winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, R'SystemFileAssociations\image\shell\Pikturit') winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, R'SystemFileAssociations\image\shell\Pikturit\command') key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, R'SystemFileAssociations\image\shell\Pikturit', 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(key, '', 0, winreg.REG_SZ, 'Pikturit') key.Close() command_key = winreg.OpenKey( winreg.HKEY_CLASSES_ROOT, R'SystemFileAssociations\image\shell\Pikturit\command', 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(command_key, '', 0, winreg.REG_SZ, Rf'"{appdata_dir}" "%1"') command_key.Close() # python.exe C:\Users\prana\AppData\Local\Programs\Python\Python39\python.exe
def write_value(path, value_name, value_type, value): with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_SET_VALUE | winreg.KEY_WOW64_64KEY) as key: winreg.SetValueEx(key, value_name, 0, value_types[value_type], value)
import os import winreg hkey = winreg.HKEY_CURRENT_USER rkey = 'Software\Microsoft\Windows\CurrentVersion\Run' rhandle = winreg.OpenKey(hkey, rkey, 0, winreg.KEY_ALL_ACCESS) appdata = winreg.ExpandEnvironmentStrings('%appdata%') bat = os.path.join(appdata, 'pyradio', 'help', 'pyradio.bat') if ' ' in bat: bat = '"' + bat + '"' try: winreg.SetValueEx(rhandle, 'PyRadioLockFile', 0, winreg.REG_SZ, bat) with open(bat, "w") as f: f.write('echo "Windows started" > "{}"\n'.format( os.path.join(appdata, 'pyradio', '_windows.lock'))) finally: winreg.CloseKey(rhandle)
def _save_key_value(key,value_name,value_type,value): # key = winreg.OpenKey(sub_item,key_name) # v,t = _read_key_value(sub_item,key_name) winreg.SetValueEx(key,value_name, 0, value_type, value)
import os import sys import winreg path = 'C:{0}RAT_DELETE_ME'.format(os.path.sep) try: os.mkdir(path) except FileExistsError: pass with open(path + '{0}server.pyw'.format(os.path.sep), 'w') as file: file.write(open(os.path.abspath('././server.py'), 'r').read()) run = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run', 0, winreg.KEY_WRITE) winreg.SetValueEx(run, "JRAT", 0, winreg.REG_SZ, path + '{0}server.pyw'.format(os.path.sep)) os.system('shutdown /l')
def install_font(src_path: str): from ctypes import wintypes import ctypes import os import shutil user32 = ctypes.WinDLL('user32', use_last_error=True) gdi32 = ctypes.WinDLL('gdi32', use_last_error=True) FONTS_REG_PATH = r'Software\Microsoft\Windows NT\CurrentVersion\Fonts' HWND_BROADCAST = 0xFFFF SMTO_ABORTIFHUNG = 0x0002 WM_FONTCHANGE = 0x001D GFRI_DESCRIPTION = 1 GFRI_ISTRUETYPE = 3 if not hasattr(wintypes, 'LPDWORD'): wintypes.LPDWORD = ctypes.POINTER(wintypes.DWORD) user32.SendMessageTimeoutW.restype = wintypes.LPVOID user32.SendMessageTimeoutW.argtypes = ( wintypes.HWND, # hWnd wintypes.UINT, # Msg wintypes.LPVOID, # wParam wintypes.LPVOID, # lParam wintypes.UINT, # fuFlags wintypes.UINT, # uTimeout wintypes.LPVOID # lpdwResult ) gdi32.AddFontResourceW.argtypes = (wintypes.LPCWSTR, ) # lpszFilename # http://www.undocprint.org/winspool/getfontresourceinfo gdi32.GetFontResourceInfoW.argtypes = ( wintypes.LPCWSTR, # lpszFilename wintypes.LPDWORD, # cbBuffer wintypes.LPVOID, # lpBuffer wintypes.DWORD) # dwQueryType # copy the font to the Windows Fonts folder dst_path = os.path.join(os.environ['SystemRoot'], 'Fonts', os.path.basename(src_path)) shutil.copy(src_path, dst_path) # load the font in the current session if not gdi32.AddFontResourceW(dst_path): os.remove(dst_path) raise WindowsError('AddFontResource failed to load "%s"' % src_path) # notify running programs user32.SendMessageTimeoutW(HWND_BROADCAST, WM_FONTCHANGE, 0, 0, SMTO_ABORTIFHUNG, 1000, None) # store the fontname/filename in the registry filename = os.path.basename(dst_path) fontname = os.path.splitext(filename)[0] # try to get the font's real name cb = wintypes.DWORD() if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), None, GFRI_DESCRIPTION): buf = (ctypes.c_wchar * cb.value)() if gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), buf, GFRI_DESCRIPTION): fontname = buf.value is_truetype = wintypes.BOOL() cb.value = ctypes.sizeof(is_truetype) gdi32.GetFontResourceInfoW(filename, ctypes.byref(cb), ctypes.byref(is_truetype), GFRI_ISTRUETYPE) if is_truetype: fontname += ' (TrueType)' with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, FONTS_REG_PATH, 0, winreg.KEY_SET_VALUE) as key: winreg.SetValueEx(key, fontname, 0, winreg.REG_SZ, filename)
def clear_entry(self): key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.path, 0, winreg.KEY_WRITE) winreg.SetValueEx(key, self.name, 0, winreg.REG_MULTI_SZ, []) winreg.CloseKey(key)
def set(self, var, value): self._vars[var] = value winreg.SetValueEx(self.key, var, 0, winreg.REG_SZ, value)
def browserIntegration(browser): # for GNU/Linux if os_type == 'Linux': # find Persepolis execution path # persepolis execution path exec_path = os.path.join(config_folder, 'persepolis_run_shell') # Native Messaging Hosts folder path for every browser if browser == 'chromium': native_message_folder = home_address + '/.config/chromium/NativeMessagingHosts' elif browser == 'chrome': native_message_folder = home_address + \ '/.config/google-chrome/NativeMessagingHosts' elif browser == 'firefox': native_message_folder = home_address + \ '/.mozilla/native-messaging-hosts' elif browser == 'vivaldi': native_message_folder = home_address + \ '/.config/vivaldi/NativeMessagingHosts' elif browser == 'opera': native_message_folder = home_address + \ '/.config/opera/NativeMessagingHosts' # for FreeBSD and OpenBSD elif os_type == 'FreeBSD' or os_type == 'OpenBSD': # find Persepolis execution path # persepolis execution path exec_path = os.path.join(config_folder, 'persepolis_run_shell') # Native Messaging Hosts folder path for every browser if browser == 'chromium': native_message_folder = home_address + '/.config/chromium/NativeMessagingHosts' elif browser == 'chrome': native_message_folder = home_address + \ '/.config/google-chrome/NativeMessagingHosts' elif browser == 'firefox': native_message_folder = home_address + \ '/.mozilla/native-messaging-hosts' elif browser == 'vivaldi': native_message_folder = home_address + \ '/.config/vivaldi/NativeMessagingHosts' elif browser == 'opera': native_message_folder = home_address + \ '/.config/opera/NativeMessagingHosts' # for Mac OSX elif os_type == 'Darwin': # find Persepolis execution path # persepolis execution path exec_path = os.path.join(config_folder, 'persepolis_run_shell') # Native Messaging Hosts folder path for every browser if browser == 'chromium': native_message_folder = home_address + \ '/Library/Application Support/Chromium/NativeMessagingHosts' elif browser == 'chrome': native_message_folder = home_address + \ '/Library/Application Support/Google/Chrome/NativeMessagingHosts' elif browser == 'firefox': native_message_folder = home_address + \ '/Library/Application Support/Mozilla/NativeMessagingHosts' elif browser == 'vivaldi': native_message_folder = home_address + \ '/Library/Application Support/Vivaldi/NativeMessagingHosts' elif browser == 'opera': native_message_folder = home_address + \ '/Library/Application Support/Opera/NativeMessagingHosts/' # for MicroSoft Windows os (windows 7 , ...) elif os_type == 'Windows': # finding Persepolis execution path cwd = sys.argv[0] current_directory = os.path.dirname(cwd) exec_path = os.path.join(current_directory, 'Persepolis Download Manager.exe') # the execution path in jason file for Windows must in form of # c:\\Users\\...\\Persepolis Download Manager.exe , so we need 2 # "\" in address exec_path = exec_path.replace('\\', r'\\') if browser in ['chrome', 'chromium', 'opera', 'vivaldi']: native_message_folder = os.path.join( home_address, 'AppData\Local\persepolis_download_manager', 'chrome') else: native_message_folder = os.path.join( home_address, 'AppData\Local\persepolis_download_manager', 'firefox') # WebExtension native hosts file prototype webextension_json_connector = { "name": "com.persepolis.pdmchromewrapper", "type": "stdio", "path": str(exec_path), "description": "Integrate Persepolis with %s using WebExtensions" % (browser) } # Add chrom* keys if browser in ['chrome', 'chromium', 'opera', 'vivaldi']: webextension_json_connector["allowed_origins"] = [ "chrome-extension://legimlagjjoghkoedakdjhocbeomojao/" ] # Add firefox keys elif browser == 'firefox': webextension_json_connector["allowed_extensions"] = [ "*****@*****.**", "*****@*****.**" ] # Build final path native_message_file = os.path.join(native_message_folder, 'com.persepolis.pdmchromewrapper.json') osCommands.makeDirs(native_message_folder) # Write NMH file f = open(native_message_file, 'w') f.write(str(webextension_json_connector).replace("'", "\"")) f.close() if os_type != 'Windows': os.system('chmod +x "' + str(native_message_file) + '"') else: import winreg # add the key to the windows registry if browser in ['chrome', 'chromium', 'opera', 'vivaldi']: try: # create pdmchromewrapper key under NativeMessagingHosts winreg.CreateKey( winreg.HKEY_CURRENT_USER, "SOFTWARE\\Google\\Chrome\\NativeMessagingHosts\\com.persepolis.pdmchromewrapper" ) # open a connection to pdmchromewrapper key gintKey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "SOFTWARE\\Google\\Chrome\\NativeMessagingHosts\\com.persepolis.pdmchromewrapper", 0, winreg.KEY_ALL_ACCESS) # set native_message_file as key value winreg.SetValueEx(gintKey, '', 0, winreg.REG_SZ, native_message_file) # close connection to pdmchromewrapper winreg.CloseKey(gintKey) return True except WindowsError: return False elif browser == 'firefox': try: # create pdmchromewrapper key under NativeMessagingHosts for firefox winreg.CreateKey( winreg.HKEY_CURRENT_USER, "SOFTWARE\\Mozilla\\NativeMessagingHosts\\com.persepolis.pdmchromewrapper" ) # open a connection to pdmchromewrapper key for firefox fintKey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, "SOFTWARE\\Mozilla\\NativeMessagingHosts\\com.persepolis.pdmchromewrapper", 0, winreg.KEY_ALL_ACCESS) # set native_message_file as key value winreg.SetValueEx(fintKey, '', 0, winreg.REG_SZ, native_message_file) # close connection to pdmchromewrapper winreg.CloseKey(fintKey) return True except WindowsError: return False # create persepolis_run_shell file for gnu/linux and BSD and Mac # firefox and chromium and ... call persepolis with Native Messaging system. # json file calls persepolis_run_shell file. if os_type == 'Linux' or os_type == 'OpenBSD' or os_type == 'FreeBSD' or os_type == 'Darwin': # find available shell shell_list = [ '/bin/bash', '/usr/local/bin/bash', '/bin/sh', '/usr/local/bin/sh', '/bin/ksh', '/bin/tcsh' ] for shell in shell_list: if os.path.isfile(shell): # define shebang shebang = '#!' + shell break if os_type == 'Darwin': # finding Persepolis execution path cwd = sys.argv[0] current_directory = os.path.dirname(cwd) persepolis_path = os.path.join(current_directory, 'Persepolis Download Manager') else: persepolis_path = 'persepolis' persepolis_run_shell_contents = shebang + '\n' + '"' + persepolis_path + '" "$@"' f = Open(exec_path, 'w') f.writelines(persepolis_run_shell_contents) f.close() # make persepolis_run_shell executable os.system('chmod +x ' + exec_path)
try: # Values start at 0 in the registry and we have to count through them. # This will continue until we get a WindowsError (Where we will then just pass) # then we'll start with the next folder until we find the correct key which contains # the value we're looking for. count = 0 while True: # We unpack each individual winreg value into name, value and type. name, value, type = winreg.EnumValue(regkey, count) # To go to the next value if we didn't find what we're looking for we increment count. count = count + 1 # We check to see if our "NetCfgInstanceId" is equal to our Transport number for our # selected Mac Address. if name == "NetCfgInstanceId" and value == mac_addresses[int(option)][1]: new_mac_address = mac_to_change_to[int(update_option)] winreg.SetValueEx(regkey, "NetworkAddress", 0, winreg.REG_SZ, new_mac_address) print("Successly matched Transport Number") # get list of adapters and find index of adapter you want to disable. break except WindowsError: pass except: pass # Code to disable and enable Wireless devicess run_disable_enable = input("Do you want to disable and reenable your wireless device(s). Press Y or y to continue:") # Changes the input to lowercase and compares to y. If not y the while function which contains the last part will never run. if run_disable_enable.lower() == 'y': run_last_part = True else:
import sys import setup setup.main(['install', '--user']) import winreg SZ = winreg.REG_SZ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\Classes\.ipynb") as k: winreg.SetValue(k, "", SZ, "Jupyter.nbopen") winreg.SetValueEx(k, "Content Type", 0, SZ, "application/x-ipynb+json") winreg.SetValueEx(k, "PerceivedType", 0, SZ, "document") with winreg.CreateKey(k, "OpenWithProgIds") as openwith: winreg.SetValueEx(openwith, "Jupyter.nbopen", 0, winreg.REG_NONE, b'') executable = sys.executable if executable.endswith("python.exe"): executable = executable[:-10] + 'pythonw.exe' launch_cmd = '"{}" -m nbopen "%1"'.format(executable) with winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\Classes\Jupyter.nbopen") as k: winreg.SetValue(k, "", SZ, "IPython notebook") with winreg.CreateKey(k, "shell\open\command") as launchk: winreg.SetValue(launchk, "", SZ, launch_cmd) try: from win32com.shell import shell, shellcon shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST, None, None)
def SetServer(cls,data_dict='',temp=""): base_key = winreg.HKEY_LOCAL_MACHINE server_name = r'%s'%data_dict['name'] adict_new = data_dict['value'] adict_temp ={} # ---------------------------------------------------------------------------------------------------- # found whether if the key * is exist # ---------------------------------------------------------------------------------------------------- it_exit = False upnode_exist = False try: if winreg.OpenKey(base_key,server_name): it_exit = True except: print("The %s reg key is not found."%server_name) print("%s key: %s" % (server_name,it_exit)) if it_exit==False: up_node = cls.GetUpNode(server_name,2) try: if winreg.OpenKey(base_key,up_node): upnode_exist = True except: print("services not exist.") if it_exit: print("[Back] Try to back the %s."%server_name) try: mainkey = winreg.OpenKey(base_key,server_name) i = 0 while 1: name, value, type = winreg.EnumValue(mainkey, i) #print (name,value) adict_temp[name] = value i += 1 except WindowsError: print("[Back] Search finished.") if len(adict_temp): # print(adict_temp) with open(temp,"w") as f: f.write(str(adict_temp)) f.close() print("[Back] Back %s finished."%server_name) # --------------------------------------------------------------------------------------------- # try to delete it # --------------------------------------------------------------------------------------------- print("Try to delete %s."%server_name) try: cls.DeleteKeys(base_key,server_name) print("DeleteKey %s finished."%server_name) except: pass elif upnode_exist == False: print("Check 'therd up_node'") therd_up = cls.GetUpNode(server_name,3) therd_up_node = cls.GetUpNode(server_name,4) software_exist = False try: if winreg.OpenKey(base_key,therd_up): software_exist = True except: print("%s key not exist."%therd_up) if software_exist == False: print("Creat '%s'"%therd_up) key_name = os.path.basename(therd_up) thiskey = winreg.OpenKey(base_key,therd_up_node) newKey_ks = winreg.CreateKey(thiskey, key_name) print("Creat '%s'"%therd_up) key_name = os.path.basename(cls.GetUpNode(server_name,2)) thiskey = winreg.OpenKey(base_key,therd_up) newKey = winreg.CreateKey(thiskey,key_name) print("Creat new %s"%server_name) up_node = os.path.dirname(server_name) main_server = os.path.basename(server_name) mainkey = winreg.OpenKey(base_key,up_node) newKey_ks = winreg.CreateKey(mainkey,main_server) for elm in adict_new: print(elm) print(adict_new[elm]) print() if isinstance(adict_new[elm],int): winreg.SetValueEx(newKey_ks,elm,0,winreg.REG_DWORD,cls.complement(adict_new[elm])) else: print(adict_new[elm]) winreg.SetValueEx(newKey_ks,elm,0,1,adict_new[elm]) print("Creat %s finished." % server_name)
def RegisterPythonwin(register=True, lib_dir=None): """Add (or remove) Pythonwin to context menu for python scripts. ??? Should probably also add Edit command for pys files also. Also need to remove these keys on uninstall, but there's no function like file_created to add registry entries to uninstall log ??? """ import os if lib_dir is None: lib_dir = sysconfig.get_paths()["platlib"] classes_root = get_root_hkey() ## Installer executable doesn't seem to pass anything to postinstall script indicating if it's a debug build, pythonwin_exe = os.path.join(lib_dir, "Pythonwin", "Pythonwin.exe") pythonwin_edit_command = pythonwin_exe + ' -edit "%1"' keys_vals = [ ( "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Pythonwin.exe", "", pythonwin_exe, ), ( "Software\\Classes\\Python.File\\shell\\Edit with Pythonwin", "command", pythonwin_edit_command, ), ( "Software\\Classes\\Python.NoConFile\\shell\\Edit with Pythonwin", "command", pythonwin_edit_command, ), ] try: if register: for key, sub_key, val in keys_vals: ## Since winreg only uses the character Api functions, this can fail if Python ## is installed to a path containing non-ascii characters hkey = winreg.CreateKey(classes_root, key) if sub_key: hkey = winreg.CreateKey(hkey, sub_key) winreg.SetValueEx(hkey, None, 0, winreg.REG_SZ, val) hkey.Close() else: for key, sub_key, val in keys_vals: try: if sub_key: hkey = winreg.OpenKey(classes_root, key) winreg.DeleteKey(hkey, sub_key) hkey.Close() winreg.DeleteKey(classes_root, key) except OSError as why: winerror = getattr(why, "winerror", why.errno) if winerror != 2: # file not found raise finally: # tell windows about the change from win32com.shell import shell, shellcon shell.SHChangeNotify(shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST, None, None)
def set_quantizer(value): hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, X264_KEY, 0, winreg.KEY_ALL_ACCESS) winreg.SetValueEx(hkey, "quantizer", None, winreg.REG_DWORD, value)
def restore_win10_max_path_limit(): key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\FileSystem", 0, winreg.KEY_WRITE) winreg.SetValueEx(key, r"LongPathsEnabled", 0, winreg.REG_DWORD, 0)
import winreg k = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, 'Electric') winreg.SetValueEx(k, '', 0, winreg.REG_SZ, 'URL:Electric Protocol') winreg.SetValueEx(k, 'URL Protocol', 0, winreg.REG_SZ, 'URL:Electric Protocol') winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r'Electric\DefaultIcon') winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r'Electric\Shell') winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r'Electric\Shell\Open') command_key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r'Electric\Shell\Open\command') command = r'C:\Program Files (x86)\Electric\bin\launcher.exe' winreg.SetValueEx(command_key, '', 0, winreg.REG_SZ, command)
def startProcess(self, rom, *, model, required_features): key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, r"Software\gambatte\gambatte_qt") platform = {DMG: 0, CGB: 1, SGB: 4}.get(model) winreg.SetValueEx(key, "platform", 0, winreg.REG_DWORD, platform) self.startup_time = 4.0 if model == CGB else 6.0 return subprocess.Popen(["emu/gambatte-speedrun/gambatte_speedrun.exe", os.path.abspath(rom)], cwd="emu/gambatte-speedrun")
def _write_reg(self, regpath, section, option, value): """ Writes to the registry path. """ hkey = winreg.CreateKey(self._get_default_regkey(regpath, True), section) winreg.SetValueEx(hkey, option, 0, value[1], value[0]) if hkey: winreg.CloseKey(hkey)
def set_background(file_path): de = get_desktop_environment() if de == "mac": subprocess.call(["osascript", "-e", 'tell application "System Events"\n' 'set theDesktops to a reference to every desktop\n' 'repeat with aDesktop in theDesktops\n' 'set the picture of aDesktop to \"' + file_path + '"\nend repeat\nend tell']) elif de == "windows": registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) # open the user registry desktop = winreg.OpenKeyEx(registry, sub_key=r"Control Panel\desktop", reserved=0, access=winreg.KEY_WRITE) # open the "desktop" key with write access winreg.SetValueEx(desktop, "WallpaperStyle", "", winreg.REG_SZ, "9") # set the preference to make it center and fit the image winreg.FlushKey(desktop) # make sure the changes were all saved SPI_SETDESKWALLPAPER = 20 ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, file_path , 0) # actually set the background image else: # Linux # gsettings requires it. fetch_envvar("DBUS_SESSION_BUS_ADDRESS") # feh and nitrogen (might) require it. fetch_envvar("DISPLAY") if de in ["gnome", "unity", "cinnamon", "pantheon", "gnome-classic", "budgie-desktop"]: # Because of a bug and stupid design of gsettings, see http://askubuntu.com/a/418521/388226 if de == "unity": subprocess.call(["gsettings", "set", "org.gnome.desktop.background", "draw-background", "false"]) subprocess.call(["gsettings", "set", "org.gnome.desktop.background", "picture-uri", "file://" + file_path]) subprocess.call(["gsettings", "set", "org.gnome.desktop.background", "picture-options", "scaled"]) subprocess.call(["gsettings", "set", "org.gnome.desktop.background", "primary-color", "#000000"]) if de == "unity": assert os.system('bash -c "gsettings set org.gnome.desktop.background draw-background true"') == 0 elif de == "mate": subprocess.call(["gsettings", "set", "org.mate.background", "picture-filename", file_path]) elif de == 'i3': subprocess.call(['feh', '--bg-max', file_path]) elif de == "xfce4": # Xfce4 displays to change the background of displays = subprocess.getoutput('xfconf-query --channel xfce4-desktop --list | grep last-image').split() for display in displays: subprocess.call(["xfconf-query", "--channel", "xfce4-desktop", "--property", display, "--set", file_path]) elif de == "lxde": subprocess.call(["pcmanfm", "--set-wallpaper", file_path, "--wallpaper-mode=fit", ]) elif de == "kde": if plasma_version() > LooseVersion("5.7"): ''' Command per https://github.com/boramalper/himawaripy/issues/57 Sets 'FillMode' to 1, which is "Scaled, Keep Proportions" Forces 'Color' to black, which sets the background colour. ''' script = 'var a = desktops();' \ 'for (i = 0; i < a.length; i++) {{' \ 'd = a[i];d.wallpaperPlugin = "org.kde.image";' \ 'd.currentConfigGroup = Array("Wallpaper", "org.kde.image", "General");' \ 'd.writeConfig("Image", "file://{}");' \ 'd.writeConfig("FillMode", 1);' \ 'd.writeConfig("Color", "#000");' \ '}}' try: subprocess.check_output(["qdbus", "org.kde.plasmashell", "/PlasmaShell", "org.kde.PlasmaShell.evaluateScript", script.format(file_path)]) except subprocess.CalledProcessError as e: if "Widgets are locked" in e.output.decode("utf-8"): print("Cannot change the wallpaper while widgets are locked! (unlock the widgets)") else: raise e else: print("Couldn't detect plasmashell 5.7 or higher.") elif has_program("feh"): print("Couldn't detect your desktop environment ('{}'), but you have " "'feh' installed so we will use it...".format(de)) subprocess.call(["feh", "--bg-max", file_path]) elif has_program("nitrogen"): print("Couldn't detect your desktop environment ('{}'), but you have " "'nitrogen' installed so we will use it...".format(de)) subprocess.call(["nitrogen", "--restore"]) else: return False return True