regsetup.py 20 KB

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