regsetup.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. # A tool to setup the Python registry.
  2. class error(Exception):
  3. pass
  4. import sys # at least we can count on this!
  5. def FileExists(fname):
  6. """Check if a file exists. Returns true or false.
  7. """
  8. import os
  9. try:
  10. os.stat(fname)
  11. return 1
  12. except os.error, details:
  13. return 0
  14. def IsPackageDir(path, packageName, knownFileName):
  15. """Given a path, a ni package name, and possibly a known file name in
  16. the root of the package, see if this path is good.
  17. """
  18. import os
  19. if knownFileName is None:
  20. knownFileName = "."
  21. return FileExists(os.path.join(os.path.join(path, packageName),knownFileName))
  22. def IsDebug():
  23. """Return "_d" if we're running a debug version.
  24. This is to be used within DLL names when locating them.
  25. """
  26. import imp
  27. for suffix_item in imp.get_suffixes():
  28. if suffix_item[0]=='_d.pyd':
  29. return '_d'
  30. return ''
  31. def FindPackagePath(packageName, knownFileName, searchPaths):
  32. """Find a package.
  33. Given a ni style package name, check the package is registered.
  34. First place looked is the registry for an existing entry. Then
  35. the searchPaths are searched.
  36. """
  37. import regutil, os
  38. pathLook = regutil.GetRegisteredNamedPath(packageName)
  39. if pathLook and IsPackageDir(pathLook, packageName, knownFileName):
  40. return pathLook, None # The currently registered one is good.
  41. # Search down the search paths.
  42. for pathLook in searchPaths:
  43. if IsPackageDir(pathLook, packageName, knownFileName):
  44. # Found it
  45. ret = os.path.abspath(pathLook)
  46. return ret, ret
  47. raise error("The package %s can not be located" % packageName)
  48. def FindHelpPath(helpFile, helpDesc, searchPaths):
  49. # See if the current registry entry is OK
  50. import os, win32api, win32con
  51. try:
  52. key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
  53. try:
  54. try:
  55. path = win32api.RegQueryValueEx(key, helpDesc)[0]
  56. if FileExists(os.path.join(path, helpFile)):
  57. return os.path.abspath(path)
  58. except win32api.error:
  59. pass # no registry entry.
  60. finally:
  61. key.Close()
  62. except win32api.error:
  63. pass
  64. for pathLook in searchPaths:
  65. if FileExists(os.path.join(pathLook, helpFile)):
  66. return os.path.abspath(pathLook)
  67. pathLook = os.path.join(pathLook, "Help")
  68. if FileExists(os.path.join( pathLook, helpFile)):
  69. return os.path.abspath(pathLook)
  70. raise error("The help file %s can not be located" % helpFile)
  71. def FindAppPath(appName, knownFileName, searchPaths):
  72. """Find an application.
  73. First place looked is the registry for an existing entry. Then
  74. the searchPaths are searched.
  75. """
  76. # Look in the first path.
  77. import regutil, string, os
  78. regPath = regutil.GetRegisteredNamedPath(appName)
  79. if regPath:
  80. pathLook = regPath.split(";")[0]
  81. if regPath and FileExists(os.path.join(pathLook, knownFileName)):
  82. return None # The currently registered one is good.
  83. # Search down the search paths.
  84. for pathLook in searchPaths:
  85. if FileExists(os.path.join(pathLook, knownFileName)):
  86. # Found it
  87. return os.path.abspath(pathLook)
  88. raise error("The file %s can not be located for application %s" % (knownFileName, appName))
  89. def FindPythonExe(exeAlias, possibleRealNames, searchPaths):
  90. """Find an exe.
  91. Returns the full path to the .exe, and a boolean indicating if the current
  92. registered entry is OK. We don't trust the already registered version even
  93. if it exists - it may be wrong (ie, for a different Python version)
  94. """
  95. import win32api, regutil, string, os, sys
  96. if possibleRealNames is None:
  97. possibleRealNames = exeAlias
  98. # Look first in Python's home.
  99. found = os.path.join(sys.prefix, possibleRealNames)
  100. if not FileExists(found): # for developers
  101. if "64 bit" in sys.version:
  102. found = os.path.join(sys.prefix, "PCBuild", "amd64", possibleRealNames)
  103. else:
  104. found = os.path.join(sys.prefix, "PCBuild", possibleRealNames)
  105. if not FileExists(found):
  106. found = LocateFileName(possibleRealNames, searchPaths)
  107. registered_ok = 0
  108. try:
  109. registered = win32api.RegQueryValue(regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exeAlias)
  110. registered_ok = found==registered
  111. except win32api.error:
  112. pass
  113. return found, registered_ok
  114. def QuotedFileName(fname):
  115. """Given a filename, return a quoted version if necessary
  116. """
  117. import regutil, string
  118. try:
  119. fname.index(" ") # Other chars forcing quote?
  120. return '"%s"' % fname
  121. except ValueError:
  122. # No space in name.
  123. return fname
  124. def LocateFileName(fileNamesString, searchPaths):
  125. """Locate a file name, anywhere on the search path.
  126. If the file can not be located, prompt the user to find it for us
  127. (using a common OpenFile dialog)
  128. Raises KeyboardInterrupt if the user cancels.
  129. """
  130. import regutil, string, os
  131. fileNames = fileNamesString.split(";")
  132. for path in searchPaths:
  133. for fileName in fileNames:
  134. try:
  135. retPath = os.path.join(path, fileName)
  136. os.stat(retPath)
  137. break
  138. except os.error:
  139. retPath = None
  140. if retPath:
  141. break
  142. else:
  143. fileName = fileNames[0]
  144. try:
  145. import win32ui, win32con
  146. except ImportError:
  147. 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)
  148. # Display a common dialog to locate the file.
  149. flags=win32con.OFN_FILEMUSTEXIST
  150. ext = os.path.splitext(fileName)[1]
  151. filter = "Files of requested type (*%s)|*%s||" % (ext,ext)
  152. dlg = win32ui.CreateFileDialog(1,None,fileName,flags,filter,None)
  153. dlg.SetOFNTitle("Locate " + fileName)
  154. if dlg.DoModal() != win32con.IDOK:
  155. raise KeyboardInterrupt("User cancelled the process")
  156. retPath = dlg.GetPathName()
  157. return os.path.abspath(retPath)
  158. def LocatePath(fileName, searchPaths):
  159. """Like LocateFileName, but returns a directory only.
  160. """
  161. import os
  162. return os.path.abspath(os.path.split(LocateFileName(fileName, searchPaths))[0])
  163. def LocateOptionalPath(fileName, searchPaths):
  164. """Like LocatePath, but returns None if the user cancels.
  165. """
  166. try:
  167. return LocatePath(fileName, searchPaths)
  168. except KeyboardInterrupt:
  169. return None
  170. def LocateOptionalFileName(fileName, searchPaths = None):
  171. """Like LocateFileName, but returns None if the user cancels.
  172. """
  173. try:
  174. return LocateFileName(fileName, searchPaths)
  175. except KeyboardInterrupt:
  176. return None
  177. def LocatePythonCore(searchPaths):
  178. """Locate and validate the core Python directories. Returns a list
  179. of paths that should be used as the core (ie, un-named) portion of
  180. the Python path.
  181. """
  182. import os, regutil
  183. currentPath = regutil.GetRegisteredNamedPath(None)
  184. if currentPath:
  185. presearchPaths = currentPath.split(";")
  186. else:
  187. presearchPaths = [os.path.abspath(".")]
  188. libPath = None
  189. for path in presearchPaths:
  190. if FileExists(os.path.join(path, "os.py")):
  191. libPath = path
  192. break
  193. if libPath is None and searchPaths is not None:
  194. libPath = LocatePath("os.py", searchPaths)
  195. if libPath is None:
  196. raise error("The core Python library could not be located.")
  197. corePath = None
  198. suffix = IsDebug()
  199. for path in presearchPaths:
  200. if FileExists(os.path.join(path, "unicodedata%s.pyd" % suffix)):
  201. corePath = path
  202. break
  203. if corePath is None and searchPaths is not None:
  204. corePath = LocatePath("unicodedata%s.pyd" % suffix, searchPaths)
  205. if corePath is None:
  206. raise error("The core Python path could not be located.")
  207. installPath = os.path.abspath(os.path.join(libPath, ".."))
  208. return installPath, [libPath, corePath]
  209. def FindRegisterPackage(packageName, knownFile, searchPaths, registryAppName = None):
  210. """Find and Register a package.
  211. Assumes the core registry setup correctly.
  212. In addition, if the location located by the package is already
  213. in the **core** path, then an entry is registered, but no path.
  214. (no other paths are checked, as the application whose path was used
  215. may later be uninstalled. This should not happen with the core)
  216. """
  217. import regutil, string
  218. if not packageName: raise error("A package name must be supplied")
  219. corePaths = regutil.GetRegisteredNamedPath(None).split(";")
  220. if not searchPaths: searchPaths = corePaths
  221. registryAppName = registryAppName or packageName
  222. try:
  223. pathLook, pathAdd = FindPackagePath(packageName, knownFile, searchPaths)
  224. if pathAdd is not None:
  225. if pathAdd in corePaths:
  226. pathAdd = ""
  227. regutil.RegisterNamedPath(registryAppName, pathAdd)
  228. return pathLook
  229. except error, details:
  230. print "*** The %s package could not be registered - %s" % (packageName, details)
  231. print "*** Please ensure you have passed the correct paths on the command line."
  232. print "*** - For packages, you should pass a path to the packages parent directory,"
  233. print "*** - and not the package directory itself..."
  234. def FindRegisterApp(appName, knownFiles, searchPaths):
  235. """Find and Register a package.
  236. Assumes the core registry setup correctly.
  237. """
  238. import regutil, string
  239. if type(knownFiles)==type(''):
  240. knownFiles = [knownFiles]
  241. paths=[]
  242. try:
  243. for knownFile in knownFiles:
  244. pathLook = FindAppPath(appName, knownFile, searchPaths)
  245. if pathLook:
  246. paths.append(pathLook)
  247. except error, details:
  248. print "*** ", details
  249. return
  250. regutil.RegisterNamedPath(appName, ";".join(paths))
  251. def FindRegisterPythonExe(exeAlias, searchPaths, actualFileNames = None):
  252. """Find and Register a Python exe (not necessarily *the* python.exe)
  253. Assumes the core registry setup correctly.
  254. """
  255. import regutil, string
  256. fname, ok = FindPythonExe(exeAlias, actualFileNames, searchPaths)
  257. if not ok:
  258. regutil.RegisterPythonExe(fname, exeAlias)
  259. return fname
  260. def FindRegisterHelpFile(helpFile, searchPaths, helpDesc = None ):
  261. import regutil
  262. try:
  263. pathLook = FindHelpPath(helpFile, helpDesc, searchPaths)
  264. except error, details:
  265. print "*** ", details
  266. return
  267. # print "%s found at %s" % (helpFile, pathLook)
  268. regutil.RegisterHelpFile(helpFile, pathLook, helpDesc)
  269. def SetupCore(searchPaths):
  270. """Setup the core Python information in the registry.
  271. This function makes no assumptions about the current state of sys.path.
  272. After this function has completed, you should have access to the standard
  273. Python library, and the standard Win32 extensions
  274. """
  275. import sys
  276. for path in searchPaths:
  277. sys.path.append(path)
  278. import os
  279. import regutil, win32api,win32con
  280. installPath, corePaths = LocatePythonCore(searchPaths)
  281. # Register the core Pythonpath.
  282. print corePaths
  283. regutil.RegisterNamedPath(None, ';'.join(corePaths))
  284. # Register the install path.
  285. hKey = win32api.RegCreateKey(regutil.GetRootKey() , regutil.BuildDefaultPythonKey())
  286. try:
  287. # Core Paths.
  288. win32api.RegSetValue(hKey, "InstallPath", win32con.REG_SZ, installPath)
  289. finally:
  290. win32api.RegCloseKey(hKey)
  291. # Register the win32 core paths.
  292. win32paths = os.path.abspath( os.path.split(win32api.__file__)[0]) + ";" + \
  293. os.path.abspath( os.path.split(LocateFileName("win32con.py;win32con.pyc", sys.path ) )[0] )
  294. # Python has builtin support for finding a "DLLs" directory, but
  295. # not a PCBuild. Having it in the core paths means it is ignored when
  296. # an EXE not in the Python dir is hosting us - so we add it as a named
  297. # value
  298. check = os.path.join(sys.prefix, "PCBuild")
  299. if "64 bit" in sys.version:
  300. check = os.path.join(check, "amd64")
  301. if os.path.isdir(check):
  302. regutil.RegisterNamedPath("PCBuild",check)
  303. def RegisterShellInfo(searchPaths):
  304. """Registers key parts of the Python installation with the Windows Shell.
  305. Assumes a valid, minimal Python installation exists
  306. (ie, SetupCore() has been previously successfully run)
  307. """
  308. import regutil, win32con
  309. suffix = IsDebug()
  310. # Set up a pointer to the .exe's
  311. exePath = FindRegisterPythonExe("Python%s.exe" % suffix, searchPaths)
  312. regutil.SetRegistryDefaultValue(".py", "Python.File", win32con.HKEY_CLASSES_ROOT)
  313. regutil.RegisterShellCommand("Open", QuotedFileName(exePath)+" \"%1\" %*", "&Run")
  314. regutil.SetRegistryDefaultValue("Python.File\\DefaultIcon", "%s,0" % exePath, win32con.HKEY_CLASSES_ROOT)
  315. FindRegisterHelpFile("Python.hlp", searchPaths, "Main Python Documentation")
  316. FindRegisterHelpFile("ActivePython.chm", searchPaths, "Main Python Documentation")
  317. # We consider the win32 core, as it contains all the win32 api type
  318. # stuff we need.
  319. # FindRegisterApp("win32", ["win32con.pyc", "win32api%s.pyd" % suffix], searchPaths)
  320. usage = """\
  321. regsetup.py - Setup/maintain the registry for Python apps.
  322. Run without options, (but possibly search paths) to repair a totally broken
  323. python registry setup. This should allow other options to work.
  324. Usage: %s [options ...] paths ...
  325. -p packageName -- Find and register a package. Looks in the paths for
  326. a sub-directory with the name of the package, and
  327. adds a path entry for the package.
  328. -a appName -- Unconditionally add an application name to the path.
  329. A new path entry is create with the app name, and the
  330. paths specified are added to the registry.
  331. -c -- Add the specified paths to the core Pythonpath.
  332. If a path appears on the core path, and a package also
  333. needs that same path, the package will not bother
  334. registering it. Therefore, By adding paths to the
  335. core path, you can avoid packages re-registering the same path.
  336. -m filename -- Find and register the specific file name as a module.
  337. Do not include a path on the filename!
  338. --shell -- Register everything with the Win95/NT shell.
  339. --upackage name -- Unregister the package
  340. --uapp name -- Unregister the app (identical to --upackage)
  341. --umodule name -- Unregister the module
  342. --description -- Print a description of the usage.
  343. --examples -- Print examples of usage.
  344. """ % sys.argv[0]
  345. description="""\
  346. If no options are processed, the program attempts to validate and set
  347. the standard Python path to the point where the standard library is
  348. available. This can be handy if you move Python to a new drive/sub-directory,
  349. in which case most of the options would fail (as they need at least string.py,
  350. os.py etc to function.)
  351. Running without options should repair Python well enough to run with
  352. the other options.
  353. paths are search paths that the program will use to seek out a file.
  354. For example, when registering the core Python, you may wish to
  355. provide paths to non-standard places to look for the Python help files,
  356. library files, etc.
  357. See also the "regcheck.py" utility which will check and dump the contents
  358. of the registry.
  359. """
  360. examples="""\
  361. Examples:
  362. "regsetup c:\\wierd\\spot\\1 c:\\wierd\\spot\\2"
  363. Attempts to setup the core Python. Looks in some standard places,
  364. as well as the 2 wierd spots to locate the core Python files (eg, Python.exe,
  365. python14.dll, the standard library and Win32 Extensions.
  366. "regsetup -a myappname . .\subdir"
  367. Registers a new Pythonpath entry named myappname, with "C:\\I\\AM\\HERE" and
  368. "C:\\I\\AM\\HERE\subdir" added to the path (ie, all args are converted to
  369. absolute paths)
  370. "regsetup -c c:\\my\\python\\files"
  371. Unconditionally add "c:\\my\\python\\files" to the 'core' Python path.
  372. "regsetup -m some.pyd \\windows\\system"
  373. Register the module some.pyd in \\windows\\system as a registered
  374. module. This will allow some.pyd to be imported, even though the
  375. windows system directory is not (usually!) on the Python Path.
  376. "regsetup --umodule some"
  377. Unregister the module "some". This means normal import rules then apply
  378. for that module.
  379. """
  380. if __name__=='__main__':
  381. if len(sys.argv)>1 and sys.argv[1] in ['/?','-?','-help','-h']:
  382. print usage
  383. elif len(sys.argv)==1 or not sys.argv[1][0] in ['/','-']:
  384. # No args, or useful args.
  385. searchPath = sys.path[:]
  386. for arg in sys.argv[1:]:
  387. searchPath.append(arg)
  388. # Good chance we are being run from the "regsetup.py" directory.
  389. # Typically this will be "\somewhere\win32\Scripts" and the
  390. # "somewhere" and "..\Lib" should also be searched.
  391. searchPath.append("..\\Build")
  392. searchPath.append("..\\Lib")
  393. searchPath.append("..")
  394. searchPath.append("..\\..")
  395. # for developers:
  396. # also search somewhere\lib, ..\build, and ..\..\build
  397. searchPath.append("..\\..\\lib")
  398. searchPath.append("..\\build")
  399. if "64 bit" in sys.version:
  400. searchPath.append("..\\..\\pcbuild\\amd64")
  401. else:
  402. searchPath.append("..\\..\\pcbuild")
  403. print "Attempting to setup/repair the Python core"
  404. SetupCore(searchPath)
  405. RegisterShellInfo(searchPath)
  406. FindRegisterHelpFile("PyWin32.chm", searchPath, "Pythonwin Reference")
  407. # Check the registry.
  408. print "Registration complete - checking the registry..."
  409. import regcheck
  410. regcheck.CheckRegistry()
  411. else:
  412. searchPaths = []
  413. import getopt, string
  414. opts, args = getopt.getopt(sys.argv[1:], 'p:a:m:c',
  415. ['shell','upackage=','uapp=','umodule=','description','examples'])
  416. for arg in args:
  417. searchPaths.append(arg)
  418. for o,a in opts:
  419. if o=='--description':
  420. print description
  421. if o=='--examples':
  422. print examples
  423. if o=='--shell':
  424. print "Registering the Python core."
  425. RegisterShellInfo(searchPaths)
  426. if o=='-p':
  427. print "Registering package", a
  428. FindRegisterPackage(a,None,searchPaths)
  429. if o in ['--upackage', '--uapp']:
  430. import regutil
  431. print "Unregistering application/package", a
  432. regutil.UnregisterNamedPath(a)
  433. if o=='-a':
  434. import regutil
  435. path = ";".join(searchPaths)
  436. print "Registering application", a,"to path",path
  437. regutil.RegisterNamedPath(a,path)
  438. if o=='-c':
  439. if not len(searchPaths):
  440. raise error("-c option must provide at least one additional path")
  441. import win32api, regutil
  442. currentPaths = regutil.GetRegisteredNamedPath(None).split(";")
  443. oldLen = len(currentPaths)
  444. for newPath in searchPaths:
  445. if newPath not in currentPaths:
  446. currentPaths.append(newPath)
  447. if len(currentPaths)!=oldLen:
  448. print "Registering %d new core paths" % (len(currentPaths)-oldLen)
  449. regutil.RegisterNamedPath(None,";".join(currentPaths))
  450. else:
  451. print "All specified paths are already registered."