def cutname(c_path, cut_tag): cut_name_list = os.listdir(c_path) for cut_name in cut_name_list: #包含有.lnk pre = '' build = '' goal = '' shell = win32com.client.Dispatch("WScript.Shell") path = c_path + '/' + cut_name shortcut = shell.CreateShortCut(path) target = shortcut.Targetpath # print(target) path_name = target.split('\\') heads = path_name[:-1] for head in heads: pre = pre + head + '/' botton = path_name[-1] parts = botton.split('.') if cut_tag in parts: parts.remove(cut_tag) build = parts[0] for part in parts[1:]: build = build + '.' + part else: print('提示:输入的标签不存在于文件名中') new_name = pre + build print('重命名:', target) print('>>>', new_name, '\n') os.rename(target, new_name)
def create_shortcut(filename, description, target, arguments=None, iconpath=None, workdir=DEFAULT_WORK_DIR, iconindex=0): # This is based from # http://www.blog.pythonlibrary.org/2010/01/23/using-python-to-create-shortcuts/ # Another option would be to use the COM IShellLink interface of the windows shell # in comnbination with the standard IPersistFile. # They required constants are in win32com.shell.shell and pythoncom. # see: from pywin32: win32comex/shell/demos/create_link.py # or: http://timgolden.me.uk/python/win32_how_do_i/create-a-shortcut.html # Another interface would be the scripting interface of the windows shell: # Dispatch('Shell.Application').NameSpace('path to shortcut').ParseName('exising Shortcut Name.lnk').GetLink from win32com.client import Dispatch shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(filename) shortcut.Description = description # Quotes around filename are added automatically if necessary (contains spaces) shortcut.Targetpath = target if arguments is not None: shortcut.Arguments = arguments shortcut.WorkingDirectory = workdir if iconpath is not None: iconpath += ',%i' % iconindex shortcut.IconLocation = iconpath #shortcut.Hotkey = 'Ctrl+Alt+H' # To available window style are at # https://technet.microsoft.com/en-us/library/ee156605.aspx # Default is 1: Activates and displays a window. #shortcut.WindowStyle = 1 shortcut.save()
def new(l_path, new_tag): lost_name_list = os.listdir(l_path) for lose in lost_name_list: #lose中包含有.lnk pre = '' shell = win32com.client.Dispatch("WScript.Shell") path = l_path + '/' + lose shortcut = shell.CreateShortCut(path) target = shortcut.Targetpath # print(target) path_name = target.split('\\') heads = path_name[:-1] for head in heads: pre = pre + head + '/' botton = path_name[-1] new_name = pre + new_tag + '.' + botton # print('进度【',lost_name_list.index(lose)+1,'/',len(lost_name_list),'】 | ','重命名:',target) percent = int(( (lost_name_list.index(lose) + 1) / len(lost_name_list) * 100) / 5) perc = '★' * percent + '☆' * (20 - percent) print('\r进度【' + perc + '】', end='') print('\n>>>:', new_name, '\n') os.rename(target, new_name)
def _create_shortcut(self, favorite: Path, path: Path, /) -> None: try: shell = Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(str(favorite)) shortcut.Targetpath = str(path) shortcut.WorkingDirectory = str(path.parent) shortcut.IconLocation = str(path) shortcut.save() except Exception: log.warning(f"Could not create the favorite for {path!r}", exc_info=True) else: log.info(f"Registered new favorite in Explorer for {path!r}")
def createLink(path, name): shell = Dispatch("WScript.Shell") link = shell.CreateShortCut(os.path.join(path, name)) link.Targetpath = os.path.join(app.targetDir, "emzed.pyw") link.WorkingDirectory = path_to_python_exe location = os.path.abspath(os.path.join(app.targetDir, "emzed.ico")) # have to do that, do not know why, but else the icons are not # associated !!! location = location.replace(os.environ.get("PROGRAMFILES"), "%PROGRAMFILES%") link.IconLocation = location link.save()
def create_shortcut(target, description, filename, arguments, workdir, iconpath): '''Make a shortcut with direct calls to Windows''' shell = win32com.client.Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(filename) shortcut.TargetPath = target shortcut.Description = description shortcut.Arguments = arguments shortcut.WorkingDirectory = workdir shortcut.IconLocation = iconpath #shortcut.FullName # shortcut.Hotkey # shortcut.WindowStyle shortcut.Save()
def create_shortcut(source, dest, *args): if os.name == 'nt': shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(dest + ".lnk") shortcut.Targetpath = source shortcut.Arguments = ' '.join(args) path, file = os.path.split(source) shortcut.WorkingDirectory = path shortcut.save() else: # some other os may not support this, but throwing an error is good since # the function couldn't do what was requested os.symlink(source, dest) # linux also can't do args... maybe we should spit out a shell script? assert not args
def createShortcut(path, target='', wd='', icon=''): if HAS_PYWIN: wind_path = os.path.normpath(path) wind_target = os.path.normpath(target) wind_wd = os.path.normpath(wd) wind_icon = os.path.normpath(icon) user = str(os.environ['USERNAME']) shell = Dispatch('WScript.Shell', userName=user) shortcut = shell.CreateShortCut(str(wind_path)) shortcut.Targetpath = wind_target shortcut.WorkingDirectory = wind_wd if icon == '': pass else: shortcut.IconLocation = wind_icon shortcut.save()
def get(get_path, for_path): lost_name_list = os.listdir(get_path) for lose in lost_name_list: #lose中包含有.lnk pre = '' shell = win32com.client.Dispatch("WScript.Shell") path = get_path + '\\' + lose shortcut = shell.CreateShortCut(path) target = shortcut.Targetpath print(target) path_name = target.split('\\') file = path_name[-1] new_path = for_path + '\\' + file percent = int(( (lost_name_list.index(lose) + 1) / len(lost_name_list) * 100) / 5) perc = '★' * percent + '☆' * (20 - percent) print('\r进度【' + perc + '】', end='') copyfile(target, new_path)
def get_network_drives(): if platform.system() == "Linux": return "~/Projects/IBL/github/iblserver" import win32api import win32com.client from win32com.shell import shell, shellcon NETWORK_SHORTCUTS_FOLDER_PATH = shell.SHGetFolderPath(0, shellcon.CSIDL_NETHOOD, None, 0) # Add Logical Drives drives = win32api.GetLogicalDriveStrings() drives = drives.split("\000")[:-1] # Add Network Locations network_shortcuts = [ join(NETWORK_SHORTCUTS_FOLDER_PATH, f) + "\\target.lnk" for f in listdir(NETWORK_SHORTCUTS_FOLDER_PATH) ] shell = win32com.client.Dispatch("WScript.Shell") for network_shortcut in network_shortcuts: shortcut = shell.CreateShortCut(network_shortcut) drives.append(shortcut.Targetpath) return drives
def install(): pth = os.path.dirname(os.path.realpath(__file__)) s_name = "com-notifier.lnk" com_name = "\com-notifier.exe" frompath = '"' + pth + com_name + '"' print("\n Creating shortcut in startup folder for COM") print("\n shortcut target : %s\n" % frompath) print("\n copying shortcut to Windows Startup folder:") # pythoncom.CoInitialize() # remove the '#' at the beginning of the line if running in a thread. desktop = startupdirectory( ) #r'C:\Users\hcl23810p.WESTCON\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' # path to where you want to put the .lnk path = os.path.join(desktop, s_name) #(desktop + s_name) print(path) target = frompath #icon = r'C:\Users\XXXXX\Desktop\muell\icons8-link-512.ico' # not needed, but nice shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(path) shortcut.Targetpath = target #shortcut.IconLocation = icon shortcut.WindowStyle = 7 # 7 - Minimized, 3 - Maximized, 1 - Normal shortcut.save() time.sleep(2) print("\n \nRestart or double click COM.EXE to run script") time.sleep(5) #b = input("Do you want to run script?(y/n)") if b == "y": print("starting script..") print(frompath) os.system(frompath) else: print("Exiting") time.sleep(2) pass
def createShortcut( path, target='', wDir='', icon='' ): #code taken from: https://www.blog.pythonlibrary.org/2010/01/23/using-python-to-create-shortcuts/ ext = path[ -3:] # AUTHOR: @driscollis thanking him for the wonderful tutorial in creating a shortcut in python. if ext == 'url': shortcut = file(path, 'w') shortcut.write('[InternetShortcut]\n') shortcut.write('URL=%s' % target) shortcut.close() else: shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(path) shortcut.Targetpath = target shortcut.WorkingDirectory = wDir if icon == '': pass else: shortcut.IconLocation = icon shortcut.save()
def create_win_shortcut(src, dst): "Creates a windows shortcut (.lnk file). Requires win32api" shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(dst) shortcut.Targetpath = src shortcut.save()
else: print('\t| ' + tag_count[i]) # 批量操作 elif md[0] == 'sort': # 为所有文件编号 pic.format_name() elif md[0] == 'new': # 为所选文件添加标签 flist = pic.get(path=pic.cash)[1] for fish in flist: #fish中包含有.lnk pre = '' shell = win32com.client.Dispatch("WScript.Shell") path = os.path.join(pic.cash, fish) shortcut = shell.CreateShortCut(path) target = shortcut.Targetpath # print(target) path_name = target.split('\\') heads = path_name[:-1] for head in heads: pre = pre + head + '\\' botton = path_name[-1] new_name = pre + tags + '.' + botton percent = int(((flist.index(fish) + 1) / len(flist) * 100) / 5) perc = '★' * percent + '☆' * (20 - percent) print('\r进度【' + perc + '】', end='') print('\n>>>:', new_name, '\n') os.rename(target, new_name) confirm = input('已添加标签。是否清空缓存文件夹?[N/any]') if confirm != 'N':
def followLink(link: str): shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut(lnk) return (shortcut.Targetpath, shortcut.Arguments)
dlg = wx.FileDialog(None, 'Choose new GSAS-II shortcut name', desktop, shortbase, wildcard='GSAS-II shortcut (*.lnk)|*.lnk', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) dlg.Raise() try: if dlg.ShowModal() == wx.ID_OK: shortcut = dlg.GetPath() else: save = False finally: dlg.Destroy() if save: shell = win32com.client.Dispatch('WScript.Shell') shobj = shell.CreateShortCut(shortcut) shobj.Targetpath = G2bat #shobj.WorkingDirectory = wDir # could specify a default project location here shobj.IconLocation = G2icon shobj.save() print('Created shortcut to start GSAS-II on desktop') else: print('No shortcut for this GSAS-II created on desktop') except ImportError: print('Module pywin32 not present, will not make desktop shortcut') except: print('Unexpected error making desktop shortcut. Please report:') import traceback print(traceback.format_exc())
def install_menu(): import os import sys if plat == "darwin": ''' *makeMacApp: Create Mac Applet* =============================== This script creates an AppleScript app bundle to launch xrftomo. The app is created in the directory where the xrftomo script (__main__.py) is located. A softlink to Python is created, but is named xrftomo, and placed inside the bundle so that xrftomo shows up as the name of the app rather than Python in the menu bar, etc. A soft link named xrftomo.py, referencing XRFT.py, is created so that appropriate menu items also are labeled with xrftomo (but not the right capitalization, alas). This has been tested with several versions of Python interpreters from Anaconda and does not require pythonw (Python.app). It tests to make sure that a wx python script will run inside Python and if not, it searches for a pythonw image and tries that. Run this script with no arguments or with one optional argument, a reference to the XRFT.py, with a relative or absolute path. Either way the path will be converted via an absolute path. If no arguments are supplied, the XRFT.py script must be located in the same directory as this file. ''' AppleScript = '' '''Contains an AppleScript to start xrftomo, launching Python and the xrftomo python script ''' project="xrftomo" scriptdir = "/".join(os.path.abspath(project+".__file__").split("/")[:-1])+"/" script_path = scriptdir+"__main__.py" # where the app will be created appPath = os.path.abspath(os.path.join(scriptdir,project+".app")) env = "source activate py36; " AppleScript = '''(* xrftomo AppleScript by Fabricio S.Marin ([email protected]) It can launch xrftomo by double clicking It runs xrftomo in a terminal window. *) (* test if a file is present and exit with an error message if it is not *) on TestFilePresent(appwithpath) tell application "System Events" if (file appwithpath exists) then else display dialog "Error: file " & appwithpath & " not found. If you have moved this file recreate the AppleScript with bootstrap.py." with icon caution buttons {{"Quit"}} return end if end tell end TestFilePresent (* ------------------------------------------------------------------------ this section responds to a double-click. No file is supplied to xrftomo ------------------------------------------------------------------------ *) on run set env to "{:s}" set program to "{:s}" tell application "Terminal" activate do script env & program end tell end run ''' if os.path.exists(appPath): # cleanup print("\nRemoving old "+project+" app ("+str(appPath)+")") shutil.rmtree(appPath) shell = os.path.join("/tmp/","appscrpt.script") f = open(shell, "w") f.write(AppleScript.format(env, "xrftomo gui")) f.close() try: subprocess.check_output(["osacompile","-o",appPath,shell],stderr=subprocess.STDOUT) except subprocess.CalledProcessError as msg: sys.exit() # find Python used to run xrftomo and set a new to use to call it inside the app that will be created pythonExe = os.path.realpath(sys.executable) newpython = os.path.join(appPath,"Contents","MacOS",project) if pythonExe.split("/")[-1] == "python3.6": pythonExe = "/".join(pythonExe.split("/")[:-1])+"/python" # create a link to the python inside the app, if named to match the project if pythonExe != newpython: os.symlink(pythonExe,newpython) # # change the icon !! IOS catalina wont change icon for some reason. # iconfile = scriptdir+"xrftomo.icns" # oldicon = os.path.join(appPath,"Contents","Resources","applet.icns") # if os.path.exists(iconfile): # shutil.copyfile(iconfile,oldicon) print("\nCreated "+project+" app ("+str(appPath)+").\nViewing app in Finder so you can drag it to the dock if, you wish.") subprocess.call(["open","-R",appPath]) elif plat == "win32" or plat == "windows": ''' *makeBat: Create XRFtomo Batch File* ==================================== This script creates a file named ``XRFtomo.bat`` and a desktop shortcut to that file. Double-clicking on the shortcut opens XRFtomo. Run this script with no arguments; the path to the ``xrftomoBat.py`` file is assumed to be the the same as the path to the ``(xrftomo) __main__.py`` file and the path to Python is determined from the version of Python used to run this script. ''' import os, sys import datetime # import wx Script = '''@echo ======================================================================== @echo XRFtomo @echo ======================================================================== @ {:s} & {:s} {:s} {:s}"%~1" @REM To keep the window from disappearing with any error messages pause ''' try: import _winreg as winreg except ImportError: import winreg app = None # delay starting wx until we need it. Likely not needed. scriptpath = os.path.split(sys.argv[0])[0] if not scriptpath: scriptpath = "/".join(os.path.abspath("xrftomo.__file__").split("/")[:-1])+"/" #if no path specified: "", scriptpath="." scriptpath = os.path.abspath(os.path.expanduser(scriptpath)) #scriptpath = =current path XRFscript = os.path.join(scriptpath,'__main__.py') #assuming path is where script is XRFbat = os.path.join(scriptpath,'RunXRFtomo.bat') #place bat alongside xrftomo ? XRFicon = os.path.join(scriptpath,'xrftomo.ico') #place xrftomo.ico alongisde xrftomo.py ? pythonexe = os.path.realpath(sys.executable) #python path, automatically detects python path # if pythonExe.split("/")[-1] == "python3.6": # pythonExe = "/".join(pythonExe.split("/")[:-1])+"/python" print('Python installed at',pythonexe) print('xrftomo installed at',scriptpath) # Bob reports a problem using pythonw.exe w/Canopy on Windows, so change that if used if pythonexe.lower().endswith('pythonw.exe'): print(" using python.exe rather than "+pythonexe) pythonexe = os.path.join(os.path.split(pythonexe)[0],'python.exe') print(" now pythonexe="+pythonexe) # create a GSAS-II script fp = open(os.path.join(XRFbat),'w') fp.write("@REM created by run of bootstrap.py on {:%d %b %Y %H:%M}\n".format(datetime.datetime.now())) activate = os.path.join(os.path.split(pythonexe)[0],'Scripts','activate') print("Looking for",activate) if os.path.exists(activate): activate = os.path.realpath(activate) if ' ' in activate: activate = 'call "'+ activate + '"\n' else: activate = 'call '+ activate + '\n' print('adding activate to .bat file ({})'.format(activate)) else: try: AnacondaPathIndx = os.path.split(pythonexe)[0].split("\\").index("Anaconda3") except ValueError: try: AnacondaPathIndx = os.path.split(pythonexe)[0].split("\\").index("anaconda3") except ValueError: print("could not find Anaconda activate script") activate = "\\".join(os.path.split(pythonexe)[0].split("\\")[:AnacondaPathIndx+1])+"\\Scripts\\activate py36" print("set activate path to {}".format(activate)) pexe = pythonexe if ' ' in pythonexe: pexe = '"'+pythonexe+'"' XRFs = XRFscript if ' ' in XRFs: XRFs = '"'+XRFscript+'"' args = 'gui' fp.write(Script.format(activate,pexe,XRFs,args)) fp.close() print('\nCreated xrftomo batch file xrftomo.bat in '+scriptpath) try: import win32com.shell.shell, win32com.shell.shellcon, win32com.client desktop = win32com.shell.shell.SHGetFolderPath( 0, win32com.shell.shellcon.CSIDL_DESKTOP, None, 0) shortbase = "xrftomo.lnk" shortcut = os.path.join(desktop, shortbase) save = True if save: shell = win32com.client.Dispatch('WScript.Shell') shobj = shell.CreateShortCut(shortcut) shobj.Targetpath = XRFbat #shobj.WorkingDirectory = wDir # could specify a default project location here shobj.IconLocation = XRFicon shobj.save() print('Created shortcut to start xrftomo on desktop') else: print('No shortcut for this xrftomo created on desktop') except ImportError: print('Module pywin32 not present, will not make desktop shortcut') except: print('Unexpected error making desktop shortcut. Please report:') import traceback print(traceback.format_exc())
import sys import win32com.client import os import sys import win32com.shell.shell as shell ASADMIN = 'asadmin' if sys.argv[-1] != ASADMIN: script = os.path.abspath(sys.argv[0]) params = ' '.join([script] + sys.argv[1:] + [ASADMIN]) shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params) shell = win32com.client.Dispatch("WScript.Shell") shortcut = shell.CreateShortCut("Pendulum Sandbox.lnk") shortcut.WorkingDirectory = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs" #shortcut.IconLocation = "pendulum.ico,1" print shortcut.TargetPath shortcut.save()