Uploaded Test files

This commit is contained in:
Batuhan Berk Başoğlu 2020-11-12 11:05:57 -05:00
parent f584ad9d97
commit 2e81cb7d99
16627 changed files with 2065359 additions and 102444 deletions

View file

@ -0,0 +1,255 @@
# ControlService.py
#
# A simple app which duplicates some of the functionality in the
# Services applet of the control panel.
#
# Suggested enhancements (in no particular order):
#
# 1. When changing the service status, continue to query the status
# of the service until the status change is complete. Use this
# information to put up some kind of a progress dialog like the CP
# applet does. Unlike the CP, allow canceling out in the event that
# the status change hangs.
# 2. When starting or stopping a service with dependencies, alert
# the user about the dependent services, then start (or stop) all
# dependent services as appropriate.
# 3. Allow toggling between service view and device view
# 4. Allow configuration of other service parameters such as startup
# name and password.
# 5. Allow connection to remote SCMs. This is just a matter of
# reconnecting to the SCM on the remote machine; the rest of the
# code should still work the same.
# 6. Either implement the startup parameters or get rid of the editbox.
# 7. Either implement or get rid of "H/W Profiles".
# 8. Either implement or get rid of "Help".
# 9. Improve error handling. Ideally, this would also include falling
# back to lower levels of functionality for users with less rights.
# Right now, we always try to get all the rights and fail when we can't
from pywin.mfc import dialog
import win32ui
import win32con
import win32service
class StartupDlg(dialog.Dialog):
IDC_LABEL = 127
IDC_DEVICE = 128
IDC_BOOT = 129
IDC_SYSTEM = 130
IDC_AUTOMATIC = 131
IDC_MANUAL = 132
IDC_DISABLED = 133
def __init__(self, displayname, service):
dialog.Dialog.__init__(self, self.GetResource())
self.name = displayname
self.service = service
def __del__(self):
win32service.CloseServiceHandle(self.service)
def OnInitDialog(self):
cfg = win32service.QueryServiceConfig(self.service)
self.GetDlgItem(self.IDC_BOOT + cfg[1]).SetCheck(1)
status = win32service.QueryServiceStatus(self.service)
if ((status[0] & win32service.SERVICE_KERNEL_DRIVER) or
(status[0] & win32service.SERVICE_FILE_SYSTEM_DRIVER)):
# driver
self.GetDlgItem(self.IDC_LABEL).SetWindowText('Device:')
else:
# service
self.GetDlgItem(self.IDC_LABEL).SetWindowText('Service:')
self.GetDlgItem(self.IDC_BOOT).EnableWindow(0)
self.GetDlgItem(self.IDC_SYSTEM).EnableWindow(0)
self.GetDlgItem(self.IDC_DEVICE).SetWindowText(str(self.name))
return dialog.Dialog.OnInitDialog(self)
def OnOK(self):
self.BeginWaitCursor()
starttype = self.GetCheckedRadioButton(self.IDC_BOOT, self.IDC_DISABLED) - self.IDC_BOOT
try:
win32service.ChangeServiceConfig(self.service, win32service.SERVICE_NO_CHANGE, starttype,
win32service.SERVICE_NO_CHANGE, None, None, 0, None, None, None, None)
except:
self.MessageBox('Unable to change startup configuration', None,
win32con.MB_ICONEXCLAMATION)
self.EndWaitCursor()
return dialog.Dialog.OnOK(self)
def GetResource(self):
style = win32con.WS_POPUP | win32con.DS_SETFONT | win32con.WS_SYSMENU | win32con.WS_CAPTION | win32con.WS_VISIBLE | win32con.DS_MODALFRAME
exstyle = None
t = [["Service Startup", (6, 18, 188, 107), style, exstyle, (8, 'MS Shell Dlg')], ]
t.append([130, "Device:", self.IDC_LABEL, (6, 7, 40, 8), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.SS_LEFT])
t.append([130, "", self.IDC_DEVICE, (48, 7, 134, 8), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.SS_LEFT])
t.append([128, "Startup Type", -1, (6, 21, 130, 80), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_GROUP | win32con.BS_GROUPBOX])
t.append([128, "&Boot", self.IDC_BOOT, (12, 33, 39, 10), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_AUTORADIOBUTTON])
t.append([128, "&System", self.IDC_SYSTEM, (12, 46, 39, 10), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_AUTORADIOBUTTON])
t.append([128, "&Automatic", self.IDC_AUTOMATIC, (12, 59, 118, 10), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_AUTORADIOBUTTON])
t.append([128, "&Manual", self.IDC_MANUAL, (12, 72, 118, 10), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_AUTORADIOBUTTON])
t.append([128, "&Disabled", self.IDC_DISABLED, (12, 85, 118, 10), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_AUTORADIOBUTTON])
t.append([128, "OK", win32con.IDOK, (142, 25, 40, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.WS_GROUP | win32con.BS_DEFPUSHBUTTON])
t.append([128, "Cancel", win32con.IDCANCEL, (142, 43, 40, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([128, "&Help", win32con.IDHELP, (142, 61, 40, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
return t
class ServiceDlg(dialog.Dialog):
IDC_LIST = 128
IDC_START = 129
IDC_STOP = 130
IDC_PAUSE = 131
IDC_CONTINUE = 132
IDC_STARTUP = 133
IDC_PROFILES = 134
IDC_PARAMS = 135
def __init__(self, machineName = ''):
dialog.Dialog.__init__(self, self.GetResource())
self.HookCommand(self.OnListEvent, self.IDC_LIST)
self.HookCommand(self.OnStartCmd, self.IDC_START)
self.HookCommand(self.OnStopCmd, self.IDC_STOP)
self.HookCommand(self.OnPauseCmd, self.IDC_PAUSE)
self.HookCommand(self.OnContinueCmd, self.IDC_CONTINUE)
self.HookCommand(self.OnStartupCmd, self.IDC_STARTUP)
self.machineName = machineName
self.scm = win32service.OpenSCManager(self.machineName, None, win32service.SC_MANAGER_ALL_ACCESS)
def __del__(self):
win32service.CloseServiceHandle(self.scm)
def OnInitDialog(self):
self.listCtrl = self.GetDlgItem(self.IDC_LIST)
self.listCtrl.SetTabStops([158, 200])
if self.machineName:
self.SetWindowText("Services on %s" % self.machineName)
self.ReloadData()
return dialog.Dialog.OnInitDialog(self)
def ReloadData(self):
service = self.GetSelService()
self.listCtrl.SetRedraw(0)
self.listCtrl.ResetContent()
svcs = win32service.EnumServicesStatus(self.scm)
i = 0
self.data = []
for svc in svcs:
try:
status = ('Unknown', 'Stopped', 'Starting', 'Stopping', 'Running',
'Continuing', 'Pausing', 'Paused')[svc[2][1]]
except:
status = 'Unknown'
s = win32service.OpenService(self.scm, svc[0], win32service.SERVICE_ALL_ACCESS)
cfg = win32service.QueryServiceConfig(s)
try:
startup = ('Boot', 'System', 'Automatic', 'Manual', 'Disabled')[cfg[1]]
except:
startup = 'Unknown'
win32service.CloseServiceHandle(s)
# svc[2][2] control buttons
pos = self.listCtrl.AddString(str(svc[1]) + '\t' + status + '\t' + startup)
self.listCtrl.SetItemData(pos, i)
self.data.append(tuple(svc[2]) + (svc[1], svc[0], ))
i = i + 1
if service and service[1] == svc[0]:
self.listCtrl.SetCurSel(pos)
self.OnListEvent(self.IDC_LIST, win32con.LBN_SELCHANGE)
self.listCtrl.SetRedraw(1)
def OnListEvent(self, id, code):
if code == win32con.LBN_SELCHANGE or code == win32con.LBN_SELCANCEL:
pos = self.listCtrl.GetCurSel()
if pos >= 0:
data = self.data[self.listCtrl.GetItemData(pos)][2]
canstart = (self.data[self.listCtrl.GetItemData(pos)][1] == win32service.SERVICE_STOPPED)
else:
data = 0
canstart = 0
self.GetDlgItem(self.IDC_START).EnableWindow(canstart)
self.GetDlgItem(self.IDC_STOP).EnableWindow(data & win32service.SERVICE_ACCEPT_STOP)
self.GetDlgItem(self.IDC_PAUSE).EnableWindow(data & win32service.SERVICE_ACCEPT_PAUSE_CONTINUE)
self.GetDlgItem(self.IDC_CONTINUE).EnableWindow(data & win32service.SERVICE_ACCEPT_PAUSE_CONTINUE)
def GetSelService(self):
pos = self.listCtrl.GetCurSel()
if pos < 0:
return None
pos = self.listCtrl.GetItemData(pos)
return self.data[pos][-2:]
def OnStartCmd(self, id, code):
service = self.GetSelService()
if not service:
return
s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
win32service.StartService(s, None)
win32service.CloseServiceHandle(s)
self.ReloadData()
def OnStopCmd(self, id, code):
service = self.GetSelService()
if not service:
return
s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
win32service.ControlService(s, win32service.SERVICE_CONTROL_STOP)
win32service.CloseServiceHandle(s)
self.ReloadData()
def OnPauseCmd(self, id, code):
service = self.GetSelService()
if not service:
return
s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
win32service.ControlService(s, win32service.SERVICE_CONTROL_PAUSE)
win32service.CloseServiceHandle(s)
self.ReloadData()
def OnContinueCmd(self, id, code):
service = self.GetSelService()
if not service:
return
s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
win32service.ControlService(s, win32service.SERVICE_CONTROL_CONTINUE)
win32service.CloseServiceHandle(s)
self.ReloadData()
def OnStartupCmd(self, id, code):
service = self.GetSelService()
if not service:
return
s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
if StartupDlg(service[0], s).DoModal() == win32con.IDOK:
self.ReloadData()
def GetResource(self):
style = win32con.WS_POPUP | win32con.DS_SETFONT | win32con.WS_SYSMENU | win32con.WS_CAPTION | win32con.WS_VISIBLE | win32con.DS_MODALFRAME
exstyle = None
t = [["Services", (16, 16, 333, 157), style, exstyle, (8, 'MS Shell Dlg')], ]
t.append([130, "Ser&vice", -1, (6, 6, 70, 8), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.SS_LEFT])
t.append([130, "Status", -1, (164, 6, 42, 8), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.SS_LEFT])
t.append([130, "Startup", -1, (206, 6, 50, 8), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.SS_LEFT])
t.append([131, "", self.IDC_LIST, (6, 16, 255, 106), win32con.LBS_USETABSTOPS | win32con.LBS_SORT | win32con.LBS_NOINTEGRALHEIGHT | win32con.WS_BORDER | win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_TABSTOP | win32con.LBS_NOTIFY | win32con.WS_VSCROLL])
t.append([128, "Close", win32con.IDOK, (267, 6, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_GROUP | win32con.WS_TABSTOP | win32con.BS_DEFPUSHBUTTON])
t.append([128, "&Start", self.IDC_START, (267, 27, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([128, "S&top", self.IDC_STOP, (267, 44, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([128, "&Pause", self.IDC_PAUSE, (267, 61, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([128, "&Continue", self.IDC_CONTINUE, (267, 78, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([128, "Sta&rtup...", self.IDC_STARTUP, (267, 99, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([128, "H&W Profiles...", self.IDC_PROFILES, (267, 116, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([128, "&Help", win32con.IDHELP, (267, 137, 60, 14), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON])
t.append([130, "St&artup Parameters:", -1, (6, 128, 70, 8), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.SS_LEFT])
t.append([129, "", self.IDC_PARAMS, (6, 139, 247, 12), win32con.WS_VISIBLE | win32con.WS_CHILD | win32con.WS_GROUP | win32con.WS_BORDER | win32con.ES_AUTOHSCROLL])
return t
if __name__=='__main__':
import sys
machine = ''
if len(sys.argv)>1:
machine = sys.argv[1]
ServiceDlg(machine).DoModal()

View file

@ -0,0 +1,81 @@
# BrandProject.py
#
# Brand a VSS project with a "build number", then optionally
# stamp DLL/EXE files with version information.
import win32api, os, string, sys
import vssutil
import bulkstamp
def BrandProject(vssProjectName, descFile, stampPath, filesToSubstitute, buildDesc = None, auto=0, bRebrand = 0):
# vssProjectName -- The name of the VSS project to brand.
# descFile -- A test file containing descriptions of the files in the release.
# stampPath -- The full path to where the files referenced in descFile can be found.
path=win32api.GetFullPathName(stampPath)
build = vssutil.MakeNewBuildNo(vssProjectName, buildDesc, auto, bRebrand)
if build is None:
print("Cancelled")
return
bulkstamp.scan( build, stampPath, descFile )
for infile, outfile in filesToSubstitute:
SubstituteVSSInFile(vssProjectName, infile, outfile)
return 1
def usage(msg):
print(msg)
print("""\
%s Usage:
%s [options] vssProject descFile stampPath
Automatically brand a VSS project with an automatically incremented
build number, and stamp DLL/EXE files with the build number.
Checks that no files are checked out in the project, and finds the last
build number, and suggests the next number.
Options:
-a - Auto increment the build number, and brand (otherwise prompt
for the build number after looking for the previous)
-r - Restamp the files with the existing build number.
-d - A description for the VSS Label.
-f infile=outfile - Substitute special VSS labels in the specified text
file with the text extracted from VSS.
""" % (os.path.basename(sys.argv[0]), os.path.basename(sys.argv[0])))
sys.exit(1)
if __name__=='__main__':
try:
import getopt
opts, args = getopt.getopt(sys.argv[1:], "af:d:r")
except getopts.error as msg:
usage(msg)
bAuto = bRebrand = 0
stampFiles = []
desc = None
for opt, val in opts:
if opt == '-a':
bAuto = 1
if opt == '-f':
infile, outfile = string.split(val, "=", 2)
stampFiles.append((infile, outfile))
if opt == '-d':
desc = val
if opt == '-r':
bRebrand = 1
if len(args)<3:
usage("You must specify the required arguments")
vssProjectName = "$\\" + args[0]
descFile = args[1]
path = args[2]
try:
os.stat(descFile)
except IOError:
usage("The description file '%s' can not be found" % (descFile))
if not os.path.isdir(path):
usage("The path to the files to stamp '%s' does not exist" % (path))
BrandProject(vssProjectName, descFile, path, stampFiles, desc, bAuto, bRebrand)

View file

@ -0,0 +1,136 @@
#
# bulkstamp.py:
# Stamp versions on all files that can be found in a given tree.
#
# USAGE: python bulkstamp.py <version> <root directory> <descriptions>
#
# Example: python bulkstamp.py 103 ..\win32\Build\ desc.txt
#
# <version> corresponds to the build number. It will be concatenated with
# the major and minor version numbers found in the description file.
#
# Description information is pulled from an input text file with lines of
# the form:
#
# <basename> <white space> <description>
#
# For example:
#
# PyWinTypes.dll Common types for Python on Win32
# etc
#
# The product's name, major, and minor versions are specified as:
#
# name <white space> <value>
# major <white space> <value>
# minor <white space> <value>
#
# The tags are case-sensitive.
#
# Any line beginning with "#" will be ignored. Empty lines are okay.
#
import sys
import os
import verstamp
import fnmatch
import win32api
numStamped = 0
g_patterns = [
'*.dll',
'*.pyd',
'*.exe',
'*.ocx',
]
def walk(arg, dirname, names):
global numStamped
vars, debug, descriptions = arg
for name in names:
for pat in g_patterns:
if fnmatch.fnmatch(name, pat):
# Handle the "_d" thing.
pathname = os.path.join(dirname, name)
base, ext = os.path.splitext(name)
if base[-2:]=='_d':
name = base[:-2] + ext
is_dll = ext.lower() != ".exe"
if os.path.normcase(name) in descriptions:
desc = descriptions[os.path.normcase(name)]
try:
verstamp.stamp(vars, pathname, desc, is_dll=is_dll)
numStamped = numStamped + 1
except win32api.error as exc:
print("Could not stamp", pathname, "Error", exc.winerror, "-", exc.strerror)
else:
print('WARNING: description not provided for:', name)
# skip branding this - assume already branded or handled elsewhere
# print "Stamped", pathname
def load_descriptions(fname, vars):
retvars = {}
descriptions = { }
lines = open(fname, 'r').readlines()
for i in range(len(lines)):
line = lines[i].strip()
if line != '' and line[0] != '#':
idx1 = line.find(' ')
idx2 = line.find('\t')
if idx1 == -1 or idx2 < idx1:
idx1 = idx2
if idx1 == -1:
print('ERROR: bad syntax in description file at line %d.' % (i+1))
sys.exit(1)
key = line[:idx1]
val = line[idx1:].strip()
if key in vars:
retvars[key] = val
else:
descriptions[key] = val
if 'product' not in retvars:
print('ERROR: description file is missing the product name.')
sys.exit(1)
if 'major' not in retvars:
print('ERROR: description file is missing the major version number.')
sys.exit(1)
if 'minor' not in retvars:
print('ERROR: description file is missing the minor version number.')
sys.exit(1)
return retvars, descriptions
def scan(build, root, desc, **custom_vars ):
global numStamped
numStamped = 0
try:
build = int(build)
except ValueError:
print('ERROR: build number is not a number: %s' % build)
sys.exit(1)
debug = 0 ### maybe fix this one day
varList = ['major', 'minor', 'sub', 'company', 'copyright', 'trademarks', 'product']
vars, descriptions = load_descriptions(desc, varList)
vars['build'] = build
vars.update(custom_vars)
arg = vars, debug, descriptions
os.path.walk(root, walk, arg)
print("Stamped %d files." % (numStamped))
if __name__ == '__main__':
if len(sys.argv) != 4:
print("ERROR: incorrect invocation. See script's header comments.")
sys.exit(1)
scan(*tuple(sys.argv[1:]))

View file

@ -0,0 +1,170 @@
import win32con, string, traceback
import win32com.client, win32com.client.gencache
import pythoncom
import time
import os
constants = win32com.client.constants
win32com.client.gencache.EnsureModule('{783CD4E0-9D54-11CF-B8EE-00608CC9A71F}', 0, 5, 0)
error = "vssutil error"
def GetSS():
ss=win32com.client.Dispatch("SourceSafe")
# SS seems a bit weird. It defaults the arguments as empty strings, but
# then complains when they are used - so we pass "Missing"
ss.Open(pythoncom.Missing, pythoncom.Missing, pythoncom.Missing)
return ss
def test(projectName):
ss=GetSS()
project = ss.VSSItem(projectName)
for item in project.GetVersions(constants.VSSFLAG_RECURSYES):
print(item.VSSItem.Name, item.VersionNumber, item.Action)
# item=i.Versions[0].VSSItem
# for h in i.Versions:
# print `h.Comment`, h.Action, h.VSSItem.Name
def SubstituteInString(inString, evalEnv):
substChar = "$"
fields = string.split(inString, substChar)
newFields = []
for i in range(len(fields)):
didSubst = 0
strVal = fields[i]
if i%2!=0:
try:
strVal = eval(strVal,evalEnv[0], evalEnv[1])
newFields.append(strVal)
didSubst = 1
except:
traceback.print_exc()
print("Could not substitute", strVal)
if not didSubst:
newFields.append(strVal)
return string.join(map(str, newFields), "")
def SubstituteInFile(inName, outName, evalEnv):
inFile = open(inName, "r")
try:
outFile = open(outName, "w")
try:
while 1:
line = inFile.read()
if not line: break
outFile.write(SubstituteInString(line, evalEnv))
finally:
outFile.close()
finally:
inFile.close()
def VssLog(project, linePrefix = "", noLabels = 5, maxItems=150):
lines = []
num = 0
labelNum = 0
for i in project.GetVersions(constants.VSSFLAG_RECURSYES):
num = num + 1
if num > maxItems : break
commentDesc = itemDesc = ""
if i.Action[:5]=="Added":
continue
if len(i.Label):
labelNum = labelNum + 1
itemDesc = i.Action
else:
itemDesc = i.VSSItem.Name
if str(itemDesc[-4:])==".dsp":
continue
if i.Comment:
commentDesc ="\n%s\t%s" % (linePrefix, i.Comment)
lines.append("%s%s\t%s%s" % (linePrefix, time.asctime(time.localtime(int(i.Date))), itemDesc, commentDesc))
if labelNum > noLabels:
break
return string.join(lines,"\n")
def SubstituteVSSInFile(projectName, inName, outName):
import win32api
if win32api.GetFullPathName(inName)==win32api.GetFullPathName(outName):
raise RuntimeError("The input and output filenames can not be the same")
sourceSafe=GetSS()
project = sourceSafe.VSSItem(projectName)
# Find the last label
label = None
for version in project.Versions:
if version.Label:
break
else:
print("Couldnt find a label in the sourcesafe project!")
return
# Setup some local helpers for the conversion strings.
vss_label = version.Label
vss_date = time.asctime(time.localtime(int(version.Date)))
now = time.asctime(time.localtime(time.time()))
SubstituteInFile(inName, outName, (locals(),globals()))
def CountCheckouts(item):
num = 0
if item.Type==constants.VSSITEM_PROJECT:
for sub in item.Items:
num = num + CountCheckouts(sub)
else:
if item.IsCheckedOut:
num = num + 1
return num
def GetLastBuildNo(project):
i = GetSS().VSSItem(project)
# Find the last label
lab = None
for version in i.Versions:
lab = str(version.Label)
if lab: return lab
return None
def MakeNewBuildNo(project, buildDesc = None, auto=0, bRebrand = 0):
if buildDesc is None: buildDesc = "Created by Python"
ss = GetSS()
i = ss.VSSItem(project)
num = CountCheckouts(i)
if num > 0:
msg = "This project has %d items checked out\r\n\r\nDo you still want to continue?" % num
import win32ui
if win32ui.MessageBox(msg, project, win32con.MB_YESNO) != win32con.IDYES:
return
oldBuild = buildNo = GetLastBuildNo(project)
if buildNo is None:
buildNo = "1"
oldBuild = "<None>"
else:
try:
buildNo = string.atoi(buildNo)
if not bRebrand: buildNo = buildNo + 1
buildNo = str(buildNo)
except ValueError:
raise error("The previous label could not be incremented: %s" % (oldBuild))
if not auto:
from pywin.mfc import dialog
buildNo = dialog.GetSimpleInput("Enter new build number", buildNo, "%s - Prev: %s" % (project, oldBuild))
if buildNo is None: return
i.Label(buildNo, "Build %s: %s" % (buildNo,buildDesc))
if auto:
print("Branded project %s with label %s" % (project, buildNo))
return buildNo
if __name__=='__main__':
# UpdateWiseExeName("PyWiseTest.wse", "PyWiseTest-10.exe")
# MakeVersion()
# test(tp)
# MakeNewBuildNo(tp)
tp = "\\Python\\Python Win32 Extensions"
SubstituteVSSInFile(tp, "d:\\src\\pythonex\\win32\\win32.txt", "d:\\temp\\win32.txt")

View file

@ -0,0 +1,40 @@
# Generate a base file name
import time, os
import win32api
import win32evtlog
def BackupClearLog(logType):
datePrefix = time.strftime("%Y%m%d", time.localtime(time.time()))
fileExists = 1
retry = 0
while fileExists:
if retry == 0:
index = ""
else:
index = "-%d" % retry
try:
fname = os.path.join(win32api.GetTempPath(), "%s%s-%s" % (datePrefix, index, logType) + ".evt")
os.stat(fname)
except os.error:
fileExists = 0
retry = retry + 1
# OK - have unique file name.
try:
hlog = win32evtlog.OpenEventLog(None, logType)
except win32evtlogutil.error as details:
print("Could not open the event log", details)
return
try:
if win32evtlog.GetNumberOfEventLogRecords(hlog)==0:
print("No records in event log %s - not backed up" % logType)
return
win32evtlog.ClearEventLog(hlog, fname)
print("Backed up %s log to %s" % (logType, fname))
finally:
win32evtlog.CloseEventLog(hlog)
if __name__=='__main__':
BackupClearLog("Application")
BackupClearLog("System")
BackupClearLog("Security")

View file

@ -0,0 +1,247 @@
# Simple CE synchronisation utility with Python features.
import wincerapi
import win32api
import win32file
import getopt
import sys
import os
import string
import win32con
import fnmatch
class InvalidUsage(Exception): pass
def print_error(api_exc, msg):
hr, fn, errmsg = api_exc
print("%s - %s(%d)" % (msg, errmsg, hr))
def GetFileAttributes(file, local=1):
if local: return win32api.GetFileAttributes(file)
else: return wincerapi.CeGetFileAttributes(file)
def FindFiles(spec, local=1):
if local: return win32api.FindFiles(spec)
else: return wincerapi.CeFindFiles(spec)
def isdir(name, local=1):
try:
attr = GetFileAttributes(name, local)
return attr & win32con.FILE_ATTRIBUTE_DIRECTORY
except win32api.error:
return 0
def CopyFileToCe(src_name, dest_name, progress = None):
sh = win32file.CreateFile(src_name, win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
bytes=0
try:
dh = wincerapi.CeCreateFile(dest_name, win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
try:
while 1:
hr, data = win32file.ReadFile(sh, 2048)
if not data:
break
wincerapi.CeWriteFile(dh, data)
bytes = bytes + len(data)
if progress is not None: progress(bytes)
finally:
pass
dh.Close()
finally:
sh.Close()
return bytes
def BuildFileList(spec, local, recurse, filter, filter_args, recursed_path = ""):
files = []
if isdir(spec, local):
path = spec
raw_spec = "*"
else:
path, raw_spec = os.path.split(spec)
if recurse:
# Need full scan, to get sub-direcetories.
infos = FindFiles(os.path.join(path, "*"), local)
else:
infos = FindFiles(os.path.join(path, raw_spec), local)
for info in infos:
src_name = str(info[8])
full_src_name = os.path.join(path, src_name)
if local: # Can't do this for CE!
full_src_name = win32api.GetFullPathName(full_src_name)
if isdir(full_src_name, local) :
if recurse and src_name not in ['.','..']:
new_spec = os.path.join(full_src_name, raw_spec)
files = files + BuildFileList(new_spec, local, 1, filter, filter_args, os.path.join(recursed_path, src_name))
if fnmatch.fnmatch(src_name, raw_spec):
rel_name = os.path.join(recursed_path, src_name)
filter_data = filter( full_src_name, rel_name, info, local, filter_args )
if filter_data is not None:
files.append( (full_src_name, info, filter_data) )
return files
def _copyfilter(full_name, rel_name, info, local, bMaintainDir):
if isdir(full_name, local): return
if bMaintainDir:
return rel_name
return os.path.split(rel_name)[1]
import pywin.dialogs.status, win32ui
class FileCopyProgressDialog(pywin.dialogs.status.CStatusProgressDialog):
def CopyProgress(self, bytes):
self.Set(bytes/1024)
def copy( args ):
"""copy src [src ...], dest
Copy files to/from the CE device
"""
bRecurse = bVerbose = 0
bMaintainDir = 1
try:
opts, args = getopt.getopt(args, "rv")
except getopt.error as details:
raise InvalidUsage(details)
for o, v in opts:
if o=="-r":
bRecuse=1
elif o=='-v':
bVerbose=1
if len(args)<2:
raise InvalidUsage("Must specify a source and destination")
src = args[:-1]
dest = args[-1]
# See if WCE: leading anywhere indicates a direction.
if string.find(src[0], "WCE:")==0:
bToDevice = 0
elif string.find(dest, "WCE:")==0:
bToDevice = 1
else:
# Assume copy to device.
bToDevice = 1
if not isdir(dest, not bToDevice):
print("%s does not indicate a directory")
files = [] # List of FQ (from_name, to_name)
num_files = 0
num_bytes = 0
dialog = FileCopyProgressDialog("Copying files")
dialog.CreateWindow(win32ui.GetMainFrame())
if bToDevice:
for spec in src:
new = BuildFileList(spec, 1, bRecurse, _copyfilter, bMaintainDir)
if not new:
print("Warning: '%s' did not match any files" % (spec))
files = files + new
for full_src, src_info, dest_info in files:
dest_name = os.path.join(dest, dest_info)
size = src_info[5]
print("Size=", size)
if bVerbose:
print(full_src, "->", dest_name,"- ", end=' ')
dialog.SetText(dest_name)
dialog.Set(0, size/1024)
bytes = CopyFileToCe(full_src, dest_name, dialog.CopyProgress)
num_bytes = num_bytes + bytes
if bVerbose:
print(bytes, "bytes")
num_files = num_files + 1
dialog.Close()
print("%d files copied (%d bytes)" % (num_files, num_bytes))
def _dirfilter(*args):
return args[1]
def dir(args):
"""dir directory_name ...
Perform a directory listing on the remote device
"""
bRecurse = 0
try:
opts, args = getopt.getopt(args, "r")
except getopt.error as details:
raise InvalidUsage(details)
for o, v in opts:
if o=="-r":
bRecurse=1
for arg in args:
print("Directory of WCE:%s" % arg)
files = BuildFileList(arg, 0, bRecurse, _dirfilter, None)
total_size=0
for full_name, info, rel_name in files:
date_str = info[3].Format("%d-%b-%Y %H:%M")
attr_string = " "
if info[0] & win32con.FILE_ATTRIBUTE_DIRECTORY: attr_string = "<DIR>"
print("%s %s %10d %s" % (date_str, attr_string, info[5], rel_name))
total_size = total_size + info[5]
print(" " * 14 + "%3d files, %10d bytes" % (len(files), total_size))
def run(args):
"""run program [args]
Starts the specified program on the remote device.
"""
prog_args = []
for arg in args:
if " " in arg:
prog_args.append('"' + arg + '"')
else:
prog_args.append(arg)
prog_args = string.join(prog_args, " ")
wincerapi.CeCreateProcess(prog_args, "", None, None, 0, 0, None, "", None)
def delete(args):
"""delete file, ...
Delete one or more remote files
"""
for arg in args:
try:
wincerapi.CeDeleteFile(arg)
print("Deleted: %s" % arg)
except win32api.error as details:
print_error(details, "Error deleting '%s'" % arg)
def DumpCommands():
print("%-10s - %s" % ("Command", "Description"))
print("%-10s - %s" % ("-------", "-----------"))
for name, item in list(globals().items()):
if type(item)==type(DumpCommands):
doc = getattr(item, "__doc__", "")
if doc:
lines = string.split(doc, "\n")
print("%-10s - %s" % (name, lines[0]))
for line in lines[1:]:
if line:
print(" " * 8, line)
def main():
if len(sys.argv)<2:
print("You must specify a command!")
DumpCommands()
return
command = sys.argv[1]
fn = globals().get(command)
if fn is None:
print("Unknown command:", command)
DumpCommands()
return
wincerapi.CeRapiInit()
try:
verinfo = wincerapi.CeGetVersionEx()
print("Connected to device, CE version %d.%d %s" % (verinfo[0], verinfo[1], verinfo[4]))
try:
fn(sys.argv[2:])
except InvalidUsage as msg:
print("Invalid syntax -", msg)
print(fn.__doc__)
finally:
try:
wincerapi.CeRapiUninit()
except win32api.error as details:
print_error(details, "Error disconnecting")
if __name__=='__main__':
main()

View file

@ -0,0 +1,56 @@
# Kills a process by process name
#
# Uses the Performance Data Helper to locate the PID, then kills it.
# Will only kill the process if there is only one process of that name
# (eg, attempting to kill "Python.exe" will only work if there is only
# one Python.exe running. (Note that the current process does not
# count - ie, if Python.exe is hosting this script, you can still kill
# another Python.exe (as long as there is only one other Python.exe)
# Really just a demo for the win32pdh(util) module, which allows you
# to get all sorts of information about a running process and many
# other aspects of your system.
import win32api, win32pdhutil, win32con, sys
def killProcName(procname):
# Change suggested by Dan Knierim, who found that this performed a
# "refresh", allowing us to kill processes created since this was run
# for the first time.
try:
win32pdhutil.GetPerformanceAttributes('Process','ID Process',procname)
except:
pass
pids = win32pdhutil.FindPerformanceAttributesByName(procname)
# If _my_ pid in there, remove it!
try:
pids.remove(win32api.GetCurrentProcessId())
except ValueError:
pass
if len(pids)==0:
result = "Can't find %s" % procname
elif len(pids)>1:
result = "Found too many %s's - pids=`%s`" % (procname,pids)
else:
handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,pids[0])
win32api.TerminateProcess(handle,0)
win32api.CloseHandle(handle)
result = ""
return result
if __name__ == '__main__':
if len(sys.argv)>1:
for procname in sys.argv[1:]:
result = killProcName(procname)
if result:
print(result)
print("Dumping all processes...")
win32pdhutil.ShowAllProcesses()
else:
print("Killed %s" % procname)
else:
print("Usage: killProcName.py procname ...")

View file

@ -0,0 +1,87 @@
# A demo of using the RAS API from Python
import sys
import win32ras
# The error raised if we can not
class ConnectionError(Exception):
pass
def Connect(rasEntryName, numRetries = 5):
"""Make a connection to the specified RAS entry.
Returns a tuple of (bool, handle) on success.
- bool is 1 if a new connection was established, or 0 is a connection already existed.
- handle is a RAS HANDLE that can be passed to Disconnect() to end the connection.
Raises a ConnectionError if the connection could not be established.
"""
assert numRetries > 0
for info in win32ras.EnumConnections():
if info[1].lower()==rasEntryName.lower():
print("Already connected to", rasEntryName)
return 0, info[0]
dial_params, have_pw = win32ras.GetEntryDialParams(None, rasEntryName)
if not have_pw:
print("Error: The password is not saved for this connection")
print("Please connect manually selecting the 'save password' option and try again")
sys.exit(1)
print("Connecting to", rasEntryName, "...")
retryCount = numRetries
while retryCount > 0:
rasHandle, errCode = win32ras.Dial(None, None, dial_params, None)
if win32ras.IsHandleValid(rasHandle):
bValid = 1
break
print("Retrying...")
win32api.Sleep(5000)
retryCount = retryCount - 1
if errCode:
raise ConnectionError(errCode, win32ras.GetErrorString(errCode))
return 1, rasHandle
def Disconnect(handle):
if type(handle)==type(''): # have they passed a connection name?
for info in win32ras.EnumConnections():
if info[1].lower()==handle.lower():
handle = info[0]
break
else:
raise ConnectionError(0, "Not connected to entry '%s'" % handle)
win32ras.HangUp(handle)
usage="""rasutil.py - Utilities for using RAS
Usage:
rasutil [-r retryCount] [-c rasname] [-d rasname]
-r retryCount - Number of times to retry the RAS connection
-c rasname - Connect to the phonebook entry specified by rasname
-d rasname - Disconnect from the phonebook entry specified by rasname
"""
def Usage(why):
print(why)
print(usage)
sys.exit(1)
if __name__=='__main__':
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], "r:c:d:")
except getopt.error as why:
Usage(why)
retries = 5
if len(args) != 0:
Usage("Invalid argument")
for opt, val in opts:
if opt=='-c':
Connect(val, retries)
if opt=='-d':
Disconnect(val)
if opt=='-r':
retries = int(val)

View file

@ -0,0 +1,519 @@
# A tool to setup the Python registry.
class error(Exception):
pass
import sys # at least we can count on this!
def FileExists(fname):
"""Check if a file exists. Returns true or false.
"""
import os
try:
os.stat(fname)
return 1
except os.error as details:
return 0
def IsPackageDir(path, packageName, knownFileName):
"""Given a path, a ni package name, and possibly a known file name in
the root of the package, see if this path is good.
"""
import os
if knownFileName is None:
knownFileName = "."
return FileExists(os.path.join(os.path.join(path, packageName),knownFileName))
def IsDebug():
"""Return "_d" if we're running a debug version.
This is to be used within DLL names when locating them.
"""
import imp
for suffix_item in imp.get_suffixes():
if suffix_item[0]=='_d.pyd':
return '_d'
return ''
def FindPackagePath(packageName, knownFileName, searchPaths):
"""Find a package.
Given a ni style package name, check the package is registered.
First place looked is the registry for an existing entry. Then
the searchPaths are searched.
"""
import regutil, os
pathLook = regutil.GetRegisteredNamedPath(packageName)
if pathLook and IsPackageDir(pathLook, packageName, knownFileName):
return pathLook, None # The currently registered one is good.
# Search down the search paths.
for pathLook in searchPaths:
if IsPackageDir(pathLook, packageName, knownFileName):
# Found it
ret = os.path.abspath(pathLook)
return ret, ret
raise error("The package %s can not be located" % packageName)
def FindHelpPath(helpFile, helpDesc, searchPaths):
# See if the current registry entry is OK
import os, win32api, win32con
try:
key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
try:
try:
path = win32api.RegQueryValueEx(key, helpDesc)[0]
if FileExists(os.path.join(path, helpFile)):
return os.path.abspath(path)
except win32api.error:
pass # no registry entry.
finally:
key.Close()
except win32api.error:
pass
for pathLook in searchPaths:
if FileExists(os.path.join(pathLook, helpFile)):
return os.path.abspath(pathLook)
pathLook = os.path.join(pathLook, "Help")
if FileExists(os.path.join( pathLook, helpFile)):
return os.path.abspath(pathLook)
raise error("The help file %s can not be located" % helpFile)
def FindAppPath(appName, knownFileName, searchPaths):
"""Find an application.
First place looked is the registry for an existing entry. Then
the searchPaths are searched.
"""
# Look in the first path.
import regutil, string, os
regPath = regutil.GetRegisteredNamedPath(appName)
if regPath:
pathLook = regPath.split(";")[0]
if regPath and FileExists(os.path.join(pathLook, knownFileName)):
return None # The currently registered one is good.
# Search down the search paths.
for pathLook in searchPaths:
if FileExists(os.path.join(pathLook, knownFileName)):
# Found it
return os.path.abspath(pathLook)
raise error("The file %s can not be located for application %s" % (knownFileName, appName))
def FindPythonExe(exeAlias, possibleRealNames, searchPaths):
"""Find an exe.
Returns the full path to the .exe, and a boolean indicating if the current
registered entry is OK. We don't trust the already registered version even
if it exists - it may be wrong (ie, for a different Python version)
"""
import win32api, regutil, string, os, sys
if possibleRealNames is None:
possibleRealNames = exeAlias
# Look first in Python's home.
found = os.path.join(sys.prefix, possibleRealNames)
if not FileExists(found): # for developers
if "64 bit" in sys.version:
found = os.path.join(sys.prefix, "PCBuild", "amd64", possibleRealNames)
else:
found = os.path.join(sys.prefix, "PCBuild", possibleRealNames)
if not FileExists(found):
found = LocateFileName(possibleRealNames, searchPaths)
registered_ok = 0
try:
registered = win32api.RegQueryValue(regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exeAlias)
registered_ok = found==registered
except win32api.error:
pass
return found, registered_ok
def QuotedFileName(fname):
"""Given a filename, return a quoted version if necessary
"""
import regutil, string
try:
fname.index(" ") # Other chars forcing quote?
return '"%s"' % fname
except ValueError:
# No space in name.
return fname
def LocateFileName(fileNamesString, searchPaths):
"""Locate a file name, anywhere on the search path.
If the file can not be located, prompt the user to find it for us
(using a common OpenFile dialog)
Raises KeyboardInterrupt if the user cancels.
"""
import regutil, string, os
fileNames = fileNamesString.split(";")
for path in searchPaths:
for fileName in fileNames:
try:
retPath = os.path.join(path, fileName)
os.stat(retPath)
break
except os.error:
retPath = None
if retPath:
break
else:
fileName = fileNames[0]
try:
import win32ui, win32con
except ImportError:
raise error("Need to locate the file %s, but the win32ui module is not available\nPlease run the program again, passing as a parameter the path to this file." % fileName)
# Display a common dialog to locate the file.
flags=win32con.OFN_FILEMUSTEXIST
ext = os.path.splitext(fileName)[1]
filter = "Files of requested type (*%s)|*%s||" % (ext,ext)
dlg = win32ui.CreateFileDialog(1,None,fileName,flags,filter,None)
dlg.SetOFNTitle("Locate " + fileName)
if dlg.DoModal() != win32con.IDOK:
raise KeyboardInterrupt("User cancelled the process")
retPath = dlg.GetPathName()
return os.path.abspath(retPath)
def LocatePath(fileName, searchPaths):
"""Like LocateFileName, but returns a directory only.
"""
import os
return os.path.abspath(os.path.split(LocateFileName(fileName, searchPaths))[0])
def LocateOptionalPath(fileName, searchPaths):
"""Like LocatePath, but returns None if the user cancels.
"""
try:
return LocatePath(fileName, searchPaths)
except KeyboardInterrupt:
return None
def LocateOptionalFileName(fileName, searchPaths = None):
"""Like LocateFileName, but returns None if the user cancels.
"""
try:
return LocateFileName(fileName, searchPaths)
except KeyboardInterrupt:
return None
def LocatePythonCore(searchPaths):
"""Locate and validate the core Python directories. Returns a list
of paths that should be used as the core (ie, un-named) portion of
the Python path.
"""
import os, regutil
currentPath = regutil.GetRegisteredNamedPath(None)
if currentPath:
presearchPaths = currentPath.split(";")
else:
presearchPaths = [os.path.abspath(".")]
libPath = None
for path in presearchPaths:
if FileExists(os.path.join(path, "os.py")):
libPath = path
break
if libPath is None and searchPaths is not None:
libPath = LocatePath("os.py", searchPaths)
if libPath is None:
raise error("The core Python library could not be located.")
corePath = None
suffix = IsDebug()
for path in presearchPaths:
if FileExists(os.path.join(path, "unicodedata%s.pyd" % suffix)):
corePath = path
break
if corePath is None and searchPaths is not None:
corePath = LocatePath("unicodedata%s.pyd" % suffix, searchPaths)
if corePath is None:
raise error("The core Python path could not be located.")
installPath = os.path.abspath(os.path.join(libPath, ".."))
return installPath, [libPath, corePath]
def FindRegisterPackage(packageName, knownFile, searchPaths, registryAppName = None):
"""Find and Register a package.
Assumes the core registry setup correctly.
In addition, if the location located by the package is already
in the **core** path, then an entry is registered, but no path.
(no other paths are checked, as the application whose path was used
may later be uninstalled. This should not happen with the core)
"""
import regutil, string
if not packageName: raise error("A package name must be supplied")
corePaths = regutil.GetRegisteredNamedPath(None).split(";")
if not searchPaths: searchPaths = corePaths
registryAppName = registryAppName or packageName
try:
pathLook, pathAdd = FindPackagePath(packageName, knownFile, searchPaths)
if pathAdd is not None:
if pathAdd in corePaths:
pathAdd = ""
regutil.RegisterNamedPath(registryAppName, pathAdd)
return pathLook
except error as details:
print("*** The %s package could not be registered - %s" % (packageName, details))
print("*** Please ensure you have passed the correct paths on the command line.")
print("*** - For packages, you should pass a path to the packages parent directory,")
print("*** - and not the package directory itself...")
def FindRegisterApp(appName, knownFiles, searchPaths):
"""Find and Register a package.
Assumes the core registry setup correctly.
"""
import regutil, string
if type(knownFiles)==type(''):
knownFiles = [knownFiles]
paths=[]
try:
for knownFile in knownFiles:
pathLook = FindAppPath(appName, knownFile, searchPaths)
if pathLook:
paths.append(pathLook)
except error as details:
print("*** ", details)
return
regutil.RegisterNamedPath(appName, ";".join(paths))
def FindRegisterPythonExe(exeAlias, searchPaths, actualFileNames = None):
"""Find and Register a Python exe (not necessarily *the* python.exe)
Assumes the core registry setup correctly.
"""
import regutil, string
fname, ok = FindPythonExe(exeAlias, actualFileNames, searchPaths)
if not ok:
regutil.RegisterPythonExe(fname, exeAlias)
return fname
def FindRegisterHelpFile(helpFile, searchPaths, helpDesc = None ):
import regutil
try:
pathLook = FindHelpPath(helpFile, helpDesc, searchPaths)
except error as details:
print("*** ", details)
return
# print "%s found at %s" % (helpFile, pathLook)
regutil.RegisterHelpFile(helpFile, pathLook, helpDesc)
def SetupCore(searchPaths):
"""Setup the core Python information in the registry.
This function makes no assumptions about the current state of sys.path.
After this function has completed, you should have access to the standard
Python library, and the standard Win32 extensions
"""
import sys
for path in searchPaths:
sys.path.append(path)
import os
import regutil, win32api,win32con
installPath, corePaths = LocatePythonCore(searchPaths)
# Register the core Pythonpath.
print(corePaths)
regutil.RegisterNamedPath(None, ';'.join(corePaths))
# Register the install path.
hKey = win32api.RegCreateKey(regutil.GetRootKey() , regutil.BuildDefaultPythonKey())
try:
# Core Paths.
win32api.RegSetValue(hKey, "InstallPath", win32con.REG_SZ, installPath)
finally:
win32api.RegCloseKey(hKey)
# Register the win32 core paths.
win32paths = os.path.abspath( os.path.split(win32api.__file__)[0]) + ";" + \
os.path.abspath( os.path.split(LocateFileName("win32con.py;win32con.pyc", sys.path ) )[0] )
# Python has builtin support for finding a "DLLs" directory, but
# not a PCBuild. Having it in the core paths means it is ignored when
# an EXE not in the Python dir is hosting us - so we add it as a named
# value
check = os.path.join(sys.prefix, "PCBuild")
if "64 bit" in sys.version:
check = os.path.join(check, "amd64")
if os.path.isdir(check):
regutil.RegisterNamedPath("PCBuild",check)
def RegisterShellInfo(searchPaths):
"""Registers key parts of the Python installation with the Windows Shell.
Assumes a valid, minimal Python installation exists
(ie, SetupCore() has been previously successfully run)
"""
import regutil, win32con
suffix = IsDebug()
# Set up a pointer to the .exe's
exePath = FindRegisterPythonExe("Python%s.exe" % suffix, searchPaths)
regutil.SetRegistryDefaultValue(".py", "Python.File", win32con.HKEY_CLASSES_ROOT)
regutil.RegisterShellCommand("Open", QuotedFileName(exePath)+" \"%1\" %*", "&Run")
regutil.SetRegistryDefaultValue("Python.File\\DefaultIcon", "%s,0" % exePath, win32con.HKEY_CLASSES_ROOT)
FindRegisterHelpFile("Python.hlp", searchPaths, "Main Python Documentation")
FindRegisterHelpFile("ActivePython.chm", searchPaths, "Main Python Documentation")
# We consider the win32 core, as it contains all the win32 api type
# stuff we need.
# FindRegisterApp("win32", ["win32con.pyc", "win32api%s.pyd" % suffix], searchPaths)
usage = """\
regsetup.py - Setup/maintain the registry for Python apps.
Run without options, (but possibly search paths) to repair a totally broken
python registry setup. This should allow other options to work.
Usage: %s [options ...] paths ...
-p packageName -- Find and register a package. Looks in the paths for
a sub-directory with the name of the package, and
adds a path entry for the package.
-a appName -- Unconditionally add an application name to the path.
A new path entry is create with the app name, and the
paths specified are added to the registry.
-c -- Add the specified paths to the core Pythonpath.
If a path appears on the core path, and a package also
needs that same path, the package will not bother
registering it. Therefore, By adding paths to the
core path, you can avoid packages re-registering the same path.
-m filename -- Find and register the specific file name as a module.
Do not include a path on the filename!
--shell -- Register everything with the Win95/NT shell.
--upackage name -- Unregister the package
--uapp name -- Unregister the app (identical to --upackage)
--umodule name -- Unregister the module
--description -- Print a description of the usage.
--examples -- Print examples of usage.
""" % sys.argv[0]
description="""\
If no options are processed, the program attempts to validate and set
the standard Python path to the point where the standard library is
available. This can be handy if you move Python to a new drive/sub-directory,
in which case most of the options would fail (as they need at least string.py,
os.py etc to function.)
Running without options should repair Python well enough to run with
the other options.
paths are search paths that the program will use to seek out a file.
For example, when registering the core Python, you may wish to
provide paths to non-standard places to look for the Python help files,
library files, etc.
See also the "regcheck.py" utility which will check and dump the contents
of the registry.
"""
examples="""\
Examples:
"regsetup c:\\wierd\\spot\\1 c:\\wierd\\spot\\2"
Attempts to setup the core Python. Looks in some standard places,
as well as the 2 wierd spots to locate the core Python files (eg, Python.exe,
python14.dll, the standard library and Win32 Extensions.
"regsetup -a myappname . .\subdir"
Registers a new Pythonpath entry named myappname, with "C:\\I\\AM\\HERE" and
"C:\\I\\AM\\HERE\subdir" added to the path (ie, all args are converted to
absolute paths)
"regsetup -c c:\\my\\python\\files"
Unconditionally add "c:\\my\\python\\files" to the 'core' Python path.
"regsetup -m some.pyd \\windows\\system"
Register the module some.pyd in \\windows\\system as a registered
module. This will allow some.pyd to be imported, even though the
windows system directory is not (usually!) on the Python Path.
"regsetup --umodule some"
Unregister the module "some". This means normal import rules then apply
for that module.
"""
if __name__=='__main__':
if len(sys.argv)>1 and sys.argv[1] in ['/?','-?','-help','-h']:
print(usage)
elif len(sys.argv)==1 or not sys.argv[1][0] in ['/','-']:
# No args, or useful args.
searchPath = sys.path[:]
for arg in sys.argv[1:]:
searchPath.append(arg)
# Good chance we are being run from the "regsetup.py" directory.
# Typically this will be "\somewhere\win32\Scripts" and the
# "somewhere" and "..\Lib" should also be searched.
searchPath.append("..\\Build")
searchPath.append("..\\Lib")
searchPath.append("..")
searchPath.append("..\\..")
# for developers:
# also search somewhere\lib, ..\build, and ..\..\build
searchPath.append("..\\..\\lib")
searchPath.append("..\\build")
if "64 bit" in sys.version:
searchPath.append("..\\..\\pcbuild\\amd64")
else:
searchPath.append("..\\..\\pcbuild")
print("Attempting to setup/repair the Python core")
SetupCore(searchPath)
RegisterShellInfo(searchPath)
FindRegisterHelpFile("PyWin32.chm", searchPath, "Pythonwin Reference")
# Check the registry.
print("Registration complete - checking the registry...")
import regcheck
regcheck.CheckRegistry()
else:
searchPaths = []
import getopt, string
opts, args = getopt.getopt(sys.argv[1:], 'p:a:m:c',
['shell','upackage=','uapp=','umodule=','description','examples'])
for arg in args:
searchPaths.append(arg)
for o,a in opts:
if o=='--description':
print(description)
if o=='--examples':
print(examples)
if o=='--shell':
print("Registering the Python core.")
RegisterShellInfo(searchPaths)
if o=='-p':
print("Registering package", a)
FindRegisterPackage(a,None,searchPaths)
if o in ['--upackage', '--uapp']:
import regutil
print("Unregistering application/package", a)
regutil.UnregisterNamedPath(a)
if o=='-a':
import regutil
path = ";".join(searchPaths)
print("Registering application", a,"to path",path)
regutil.RegisterNamedPath(a,path)
if o=='-c':
if not len(searchPaths):
raise error("-c option must provide at least one additional path")
import win32api, regutil
currentPaths = regutil.GetRegisteredNamedPath(None).split(";")
oldLen = len(currentPaths)
for newPath in searchPaths:
if newPath not in currentPaths:
currentPaths.append(newPath)
if len(currentPaths)!=oldLen:
print("Registering %d new core paths" % (len(currentPaths)-oldLen))
regutil.RegisterNamedPath(None,";".join(currentPaths))
else:
print("All specified paths are already registered.")

View file

@ -0,0 +1,91 @@
# Install and register pythonxx_d.dll, pywintypesxx_d.dll and pythoncomxx_d.dll
#
# Assumes the _d files can be found in the same directory as this script
# or in the cwd.
import win32api
import winreg
import sys
import shutil
import os
def usage_and_die(rc):
print()
print("This script is designed to copy and register the Python debug")
print("binaries. It looks for pythonxx_d.dll, pythoncomxx_d.dll etc,")
print("and installs them to work correctly with Python debug builds.")
print()
print("You will generally find this script in the. zip file that")
print("included these _d files. Please run this script from")
print("that directory")
sys.exit(rc)
if win32api.__file__.find("_d") > 0:
print("This scripts appears to be running a DEBUG version of Python.")
print("Please run it using a normal release build (python.exe)")
usage_and_die(1)
try:
import pythoncom
except ImportError as details:
print("Could not import the release version of pythoncom")
print("The error details are: %s" % (details,))
print("Please correct this error and rerun the script")
usage_and_die(2)
try:
import pywintypes
except ImportError as details:
print("Could not import the release version of pywintypes")
print("The error details are: %s" % (details,))
print("Please correct this error and rerun the script")
usage_and_die(2)
def _docopy(src, dest):
orig_src = src
if not os.path.isfile(src):
src = os.path.join( os.path.split(sys.argv[0])[0], src)
print("Can not find %s or %s to copy" % (os.path.abspath(orig_src), os.path.abspath(src)))
return 0
try:
shutil.copy(src, dest)
print("Copied %s -> %s" % (src, dest))
return 1
except:
print("Error copying '%s' -> '%s'" % (src, dest))
print(str(sys.exc_info[1]))
usage_and_die(3)
def _doregister(mod_name, dll_name):
assert os.path.isfile(dll_name), "Shouldn't get here if the file doesn't exist!"
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, mod_name))
except winreg.error:
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\Modules\\%s" % (sys.winver, mod_name))
except winreg.error:
print("Could not find the existing '%s' module registered in the registry" % (mod_name,))
usage_and_die(4)
# Create the debug key.
sub_key = winreg.CreateKey(key, "Debug")
winreg.SetValue(sub_key, None, winreg.REG_SZ, dll_name)
print("Registered '%s' in the registry" % (dll_name,))
def _domodule(mod_name, release_mod_filename):
path, fname = os.path.split(release_mod_filename)
base, ext = os.path.splitext(fname)
new_fname = base + "_d" + ext
if _docopy(new_fname, path):
_doregister( mod_name, os.path.abspath( os.path.join(path, new_fname) ) )
# First the main Python DLL.
path, fname = path, fname = os.path.split(win32api.GetModuleFileName(sys.dllhandle))
base, ext = os.path.splitext(fname)
_docopy(base + "_d" + ext, path)
# Then pythoncom and pywintypes.
_domodule("pythoncom", pythoncom.__file__)
_domodule("pywintypes", pywintypes.__file__)
print("System _d files were setup.")