ml

来自Tsetien’s Wiki
Tsetien Chü留言 | 贡献115年4月5日 (日) 05:23的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转到导航 跳转到搜索

A tiny python script to make shortcut files (.lnk) from command line on Windows. It requires python itself and module pywin32 to be installed.

Pass -r to grant the created .lnk file with administrator’s privilege.

ml.py
import os
import sys
import win32com.client

def e(s=''):
	print(s or 'Usage: ml [-r] <name[.lnk]> -t <target> [-a "<args>"] [-p <workdir>] [-i <icon>]')
	raise SystemExit(1)

n=t=a=p=i=None
r=0
v=sys.argv[1:]
k=0

while k<len(v):
	x=v[k]
	if x=='-r':
		r=1
		k+=1
	elif x in ('-t','-a','-p','-i'):
		if k+1>=len(v):
			e()
		if x=='-t':
			t=v[k+1]
		elif x=='-a':
			a=v[k+1]
		elif x=='-p':
			p=v[k+1]
		else:
			i=v[k+1]
		k+=2
	elif x[:1]=='-':
		e()
	else:
		if n is not None:
			e()
		n=x
		k+=1

if n is None:
	e()
if t is None:
	e()

n=os.path.abspath(os.path.expanduser(os.path.expandvars(n if n.lower().endswith('.lnk') else n+'.lnk')))
t=os.path.abspath(os.path.expanduser(os.path.expandvars(t)))
p=os.path.abspath(os.path.expanduser(os.path.expandvars(p))) if p else os.path.dirname(t) or os.getcwd()
i=os.path.expanduser(os.path.expandvars(i)) if i else None

s=win32com.client.Dispatch('WScript.Shell').CreateShortcut(n)
s.TargetPath=t
if a is not None:
	s.Arguments=a
s.WorkingDirectory=p
if i is not None:
	s.IconLocation=i
s.Save()

if r:
	with open(n,'r+b') as f:
		f.seek(0x15)
		b=f.read(1)
		if not b:
			e('Failed to patch the shortcut.')
		f.seek(0x15)
		f.write(bytes((b[0]|0x20,)))
ml.bat
@echo off
chcp 65001 >nul
py -3 "%~dpn0.py" %*