Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

regsetup.py 20KB

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