PageRenderTime 2993ms CodeModel.GetById 40ms RepoModel.GetById 4ms app.codeStats 1ms

/Doc/using/windows.rst

https://github.com/albertz/CPython
ReStructuredText | 1111 lines | 826 code | 285 blank | 0 comment | 0 complexity | f4b3692aa2533a104124d5a6077cee24 MD5 | raw file
  1. .. highlightlang:: none
  2. .. _using-on-windows:
  3. *************************
  4. Using Python on Windows
  5. *************************
  6. .. sectionauthor:: Robert Lehmann <lehmannro@gmail.com>
  7. .. sectionauthor:: Steve Dower <steve.dower@microsoft.com>
  8. This document aims to give an overview of Windows-specific behaviour you should
  9. know about when using Python on Microsoft Windows.
  10. Unlike most Unix systems and services, Windows does not include a system
  11. supported installation of Python. To make Python available, the CPython team
  12. has compiled Windows installers (MSI packages) with every `release
  13. <https://www.python.org/download/releases/>`_ for many years. These installers
  14. are primarily intended to add a per-user installation of Python, with the
  15. core interpreter and library being used by a single user. The installer is also
  16. able to install for all users of a single machine, and a separate ZIP file is
  17. available for application-local distributions.
  18. As specified in :pep:`11`, a Python release only supports a Windows platform
  19. while Microsoft considers the platform under extended support. This means that
  20. Python |version| supports Windows Vista and newer. If you require Windows XP
  21. support then please install Python 3.4.
  22. There are a number of different installers available for Windows, each with
  23. certain benefits and downsides.
  24. :ref:`windows-full` contains all components and is the best option for
  25. developers using Python for any kind of project.
  26. :ref:`windows-store` is a simple installation of Python that is suitable for
  27. running scripts and packages, and using IDLE or other development environments.
  28. It requires Windows 10, but can be safely installed without corrupting other
  29. programs. It also provides many convenient commands for launching Python and
  30. its tools.
  31. :ref:`windows-nuget` are lightweight installations intended for continuous
  32. integration systems. It can be used to build Python packages or run scripts,
  33. but is not updateable and has no user interface tools.
  34. :ref:`windows-embeddable` is a minimal package of Python suitable for
  35. embedding into a larger application.
  36. .. _windows-full:
  37. The full installer
  38. ==================
  39. Installation steps
  40. ------------------
  41. Four Python |version| installers are available for download - two each for the
  42. 32-bit and 64-bit versions of the interpreter. The *web installer* is a small
  43. initial download, and it will automatically download the required components as
  44. necessary. The *offline installer* includes the components necessary for a
  45. default installation and only requires an internet connection for optional
  46. features. See :ref:`install-layout-option` for other ways to avoid downloading
  47. during installation.
  48. After starting the installer, one of two options may be selected:
  49. .. image:: win_installer.png
  50. If you select "Install Now":
  51. * You will *not* need to be an administrator (unless a system update for the
  52. C Runtime Library is required or you install the :ref:`launcher` for all
  53. users)
  54. * Python will be installed into your user directory
  55. * The :ref:`launcher` will be installed according to the option at the bottom
  56. of the first page
  57. * The standard library, test suite, launcher and pip will be installed
  58. * If selected, the install directory will be added to your :envvar:`PATH`
  59. * Shortcuts will only be visible for the current user
  60. Selecting "Customize installation" will allow you to select the features to
  61. install, the installation location and other options or post-install actions.
  62. To install debugging symbols or binaries, you will need to use this option.
  63. To perform an all-users installation, you should select "Customize
  64. installation". In this case:
  65. * You may be required to provide administrative credentials or approval
  66. * Python will be installed into the Program Files directory
  67. * The :ref:`launcher` will be installed into the Windows directory
  68. * Optional features may be selected during installation
  69. * The standard library can be pre-compiled to bytecode
  70. * If selected, the install directory will be added to the system :envvar:`PATH`
  71. * Shortcuts are available for all users
  72. .. _max-path:
  73. Removing the MAX_PATH Limitation
  74. --------------------------------
  75. Windows historically has limited path lengths to 260 characters. This meant that
  76. paths longer than this would not resolve and errors would result.
  77. In the latest versions of Windows, this limitation can be expanded to
  78. approximately 32,000 characters. Your administrator will need to activate the
  79. "Enable Win32 long paths" group policy, or set the registry value
  80. ``HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem@LongPathsEnabled``
  81. to ``1``.
  82. This allows the :func:`open` function, the :mod:`os` module and most other
  83. path functionality to accept and return paths longer than 260 characters when
  84. using strings. (Use of bytes as paths is deprecated on Windows, and this feature
  85. is not available when using bytes.)
  86. After changing the above option, no further configuration is required.
  87. .. versionchanged:: 3.6
  88. Support for long paths was enabled in Python.
  89. .. _install-quiet-option:
  90. Installing Without UI
  91. ---------------------
  92. All of the options available in the installer UI can also be specified from the
  93. command line, allowing scripted installers to replicate an installation on many
  94. machines without user interaction. These options may also be set without
  95. suppressing the UI in order to change some of the defaults.
  96. To completely hide the installer UI and install Python silently, pass the
  97. ``/quiet`` option. To skip past the user interaction but still display
  98. progress and errors, pass the ``/passive`` option. The ``/uninstall``
  99. option may be passed to immediately begin removing Python - no prompt will be
  100. displayed.
  101. All other options are passed as ``name=value``, where the value is usually
  102. ``0`` to disable a feature, ``1`` to enable a feature, or a path. The full list
  103. of available options is shown below.
  104. +---------------------------+--------------------------------------+--------------------------+
  105. | Name | Description | Default |
  106. +===========================+======================================+==========================+
  107. | InstallAllUsers | Perform a system-wide installation. | 0 |
  108. +---------------------------+--------------------------------------+--------------------------+
  109. | TargetDir | The installation directory | Selected based on |
  110. | | | InstallAllUsers |
  111. +---------------------------+--------------------------------------+--------------------------+
  112. | DefaultAllUsersTargetDir | The default installation directory | :file:`%ProgramFiles%\\\ |
  113. | | for all-user installs | Python X.Y` or :file:`\ |
  114. | | | %ProgramFiles(x86)%\\\ |
  115. | | | Python X.Y` |
  116. +---------------------------+--------------------------------------+--------------------------+
  117. | DefaultJustForMeTargetDir | The default install directory for | :file:`%LocalAppData%\\\ |
  118. | | just-for-me installs | Programs\\PythonXY` or |
  119. | | | :file:`%LocalAppData%\\\ |
  120. | | | Programs\\PythonXY-32` or|
  121. | | | :file:`%LocalAppData%\\\ |
  122. | | | Programs\\PythonXY-64` |
  123. +---------------------------+--------------------------------------+--------------------------+
  124. | DefaultCustomTargetDir | The default custom install directory | (empty) |
  125. | | displayed in the UI | |
  126. +---------------------------+--------------------------------------+--------------------------+
  127. | AssociateFiles | Create file associations if the | 1 |
  128. | | launcher is also installed. | |
  129. +---------------------------+--------------------------------------+--------------------------+
  130. | CompileAll | Compile all ``.py`` files to | 0 |
  131. | | ``.pyc``. | |
  132. +---------------------------+--------------------------------------+--------------------------+
  133. | PrependPath | Add install and Scripts directories | 0 |
  134. | | to :envvar:`PATH` and ``.PY`` to | |
  135. | | :envvar:`PATHEXT` | |
  136. +---------------------------+--------------------------------------+--------------------------+
  137. | Shortcuts | Create shortcuts for the interpreter,| 1 |
  138. | | documentation and IDLE if installed. | |
  139. +---------------------------+--------------------------------------+--------------------------+
  140. | Include_doc | Install Python manual | 1 |
  141. +---------------------------+--------------------------------------+--------------------------+
  142. | Include_debug | Install debug binaries | 0 |
  143. +---------------------------+--------------------------------------+--------------------------+
  144. | Include_dev | Install developer headers and | 1 |
  145. | | libraries | |
  146. +---------------------------+--------------------------------------+--------------------------+
  147. | Include_exe | Install :file:`python.exe` and | 1 |
  148. | | related files | |
  149. +---------------------------+--------------------------------------+--------------------------+
  150. | Include_launcher | Install :ref:`launcher`. | 1 |
  151. +---------------------------+--------------------------------------+--------------------------+
  152. | InstallLauncherAllUsers | Installs :ref:`launcher` for all | 1 |
  153. | | users. | |
  154. +---------------------------+--------------------------------------+--------------------------+
  155. | Include_lib | Install standard library and | 1 |
  156. | | extension modules | |
  157. +---------------------------+--------------------------------------+--------------------------+
  158. | Include_pip | Install bundled pip and setuptools | 1 |
  159. +---------------------------+--------------------------------------+--------------------------+
  160. | Include_symbols | Install debugging symbols (`*`.pdb) | 0 |
  161. +---------------------------+--------------------------------------+--------------------------+
  162. | Include_tcltk | Install Tcl/Tk support and IDLE | 1 |
  163. +---------------------------+--------------------------------------+--------------------------+
  164. | Include_test | Install standard library test suite | 1 |
  165. +---------------------------+--------------------------------------+--------------------------+
  166. | Include_tools | Install utility scripts | 1 |
  167. +---------------------------+--------------------------------------+--------------------------+
  168. | LauncherOnly | Only installs the launcher. This | 0 |
  169. | | will override most other options. | |
  170. +---------------------------+--------------------------------------+--------------------------+
  171. | SimpleInstall | Disable most install UI | 0 |
  172. +---------------------------+--------------------------------------+--------------------------+
  173. | SimpleInstallDescription | A custom message to display when the | (empty) |
  174. | | simplified install UI is used. | |
  175. +---------------------------+--------------------------------------+--------------------------+
  176. For example, to silently install a default, system-wide Python installation,
  177. you could use the following command (from an elevated command prompt)::
  178. python-3.7.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0
  179. To allow users to easily install a personal copy of Python without the test
  180. suite, you could provide a shortcut with the following command. This will
  181. display a simplified initial page and disallow customization::
  182. python-3.7.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
  183. SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite."
  184. (Note that omitting the launcher also omits file associations, and is only
  185. recommended for per-user installs when there is also a system-wide installation
  186. that included the launcher.)
  187. The options listed above can also be provided in a file named ``unattend.xml``
  188. alongside the executable. This file specifies a list of options and values.
  189. When a value is provided as an attribute, it will be converted to a number if
  190. possible. Values provided as element text are always left as strings. This
  191. example file sets the same options as the previous example:
  192. .. code-block:: xml
  193. <Options>
  194. <Option Name="InstallAllUsers" Value="no" />
  195. <Option Name="Include_launcher" Value="0" />
  196. <Option Name="Include_test" Value="no" />
  197. <Option Name="SimpleInstall" Value="yes" />
  198. <Option Name="SimpleInstallDescription">Just for me, no test suite</Option>
  199. </Options>
  200. .. _install-layout-option:
  201. Installing Without Downloading
  202. ------------------------------
  203. As some features of Python are not included in the initial installer download,
  204. selecting those features may require an internet connection. To avoid this
  205. need, all possible components may be downloaded on-demand to create a complete
  206. *layout* that will no longer require an internet connection regardless of the
  207. selected features. Note that this download may be bigger than required, but
  208. where a large number of installations are going to be performed it is very
  209. useful to have a locally cached copy.
  210. Execute the following command from Command Prompt to download all possible
  211. required files. Remember to substitute ``python-3.7.0.exe`` for the actual
  212. name of your installer, and to create layouts in their own directories to
  213. avoid collisions between files with the same name.
  214. ::
  215. python-3.7.0.exe /layout [optional target directory]
  216. You may also specify the ``/quiet`` option to hide the progress display.
  217. Modifying an install
  218. --------------------
  219. Once Python has been installed, you can add or remove features through the
  220. Programs and Features tool that is part of Windows. Select the Python entry and
  221. choose "Uninstall/Change" to open the installer in maintenance mode.
  222. "Modify" allows you to add or remove features by modifying the checkboxes -
  223. unchanged checkboxes will not install or remove anything. Some options cannot be
  224. changed in this mode, such as the install directory; to modify these, you will
  225. need to remove and then reinstall Python completely.
  226. "Repair" will verify all the files that should be installed using the current
  227. settings and replace any that have been removed or modified.
  228. "Uninstall" will remove Python entirely, with the exception of the
  229. :ref:`launcher`, which has its own entry in Programs and Features.
  230. .. _windows-store:
  231. The Microsoft Store package
  232. ===========================
  233. .. versionadded:: 3.7.2
  234. .. note::
  235. The Microsoft Store package is currently considered unstable while its
  236. interactions with other tools and other copies of Python are evaluated.
  237. While Python itself is stable, this installation method may change its
  238. behavior and capabilities during Python 3.7 releases.
  239. The Microsoft Store package is an easily installable Python interpreter that
  240. is intended mainly for interactive use, for example, by students.
  241. To install the package, ensure you have the latest Windows 10 updates and
  242. search the Microsoft Store app for "Python |version|". Ensure that the app
  243. you select is published by the Python Software Foundation, and install it.
  244. .. warning::
  245. Python will always be available for free on the Microsoft Store. If you
  246. are asked to pay for it, you have not selected the correct package.
  247. After installation, Python may be launched by finding it in Start.
  248. Alternatively, it will be available from any Command Prompt or PowerShell
  249. session by typing ``python``. Further, pip and IDLE may be used by typing
  250. ``pip`` or ``idle``. IDLE can also be found in Start.
  251. All three commands are also available with version number suffixes, for
  252. example, as ``python3.exe`` and ``python3.x.exe`` as well as
  253. ``python.exe`` (where ``3.x`` is the specific version you want to launch,
  254. such as |version|).
  255. Virtual environments can be created with ``python -m venv`` and activated
  256. and used as normal.
  257. If you have installed another version of Python and added it to your
  258. ``PATH`` variable, it will be available as ``python.exe`` rather than the
  259. one from the Microsoft Store. To access the new installation, use
  260. ``python3.exe`` or ``python3.x.exe``.
  261. To remove Python, open Settings and use Apps and Features, or else find
  262. Python in Start and right-click to select Uninstall. Uninstalling will
  263. remove all packages you installed directly into this Python installation, but
  264. will not remove any virtual environments
  265. Known Issues
  266. ------------
  267. Currently, the ``py.exe`` launcher cannot be used to start Python when it
  268. has been installed from the Microsoft Store.
  269. Because of restrictions on Microsoft Store apps, Python scripts may not have
  270. full write access to shared locations such as ``TEMP`` and the registry.
  271. Instead, it will write to a private copy. If your scripts must modify the
  272. shared locations, you will need to install the full installer.
  273. .. _windows-nuget:
  274. The nuget.org packages
  275. ======================
  276. .. versionadded:: 3.5.2
  277. The nuget.org package is a reduced size Python environment intended for use on
  278. continuous integration and build systems that do not have a system-wide
  279. install of Python. While nuget is "the package manager for .NET", it also works
  280. perfectly fine for packages containing build-time tools.
  281. Visit `nuget.org <https://www.nuget.org/>`_ for the most up-to-date information
  282. on using nuget. What follows is a summary that is sufficient for Python
  283. developers.
  284. The ``nuget.exe`` command line tool may be downloaded directly from
  285. ``https://aka.ms/nugetclidl``, for example, using curl or PowerShell. With the
  286. tool, the latest version of Python for 64-bit or 32-bit machines is installed
  287. using::
  288. nuget.exe install python -ExcludeVersion -OutputDirectory .
  289. nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory .
  290. To select a particular version, add a ``-Version 3.x.y``. The output directory
  291. may be changed from ``.``, and the package will be installed into a
  292. subdirectory. By default, the subdirectory is named the same as the package,
  293. and without the ``-ExcludeVersion`` option this name will include the specific
  294. version installed. Inside the subdirectory is a ``tools`` directory that
  295. contains the Python installation::
  296. # Without -ExcludeVersion
  297. > .\python.3.5.2\tools\python.exe -V
  298. Python 3.5.2
  299. # With -ExcludeVersion
  300. > .\python\tools\python.exe -V
  301. Python 3.5.2
  302. In general, nuget packages are not upgradeable, and newer versions should be
  303. installed side-by-side and referenced using the full path. Alternatively,
  304. delete the package directory manually and install it again. Many CI systems
  305. will do this automatically if they do not preserve files between builds.
  306. Alongside the ``tools`` directory is a ``build\native`` directory. This
  307. contains a MSBuild properties file ``python.props`` that can be used in a
  308. C++ project to reference the Python install. Including the settings will
  309. automatically use the headers and import libraries in your build.
  310. The package information pages on nuget.org are
  311. `www.nuget.org/packages/python <https://www.nuget.org/packages/python>`_
  312. for the 64-bit version and `www.nuget.org/packages/pythonx86
  313. <https://www.nuget.org/packages/pythonx86>`_ for the 32-bit version.
  314. .. _windows-embeddable:
  315. The embeddable package
  316. ======================
  317. .. versionadded:: 3.5
  318. The embedded distribution is a ZIP file containing a minimal Python environment.
  319. It is intended for acting as part of another application, rather than being
  320. directly accessed by end-users.
  321. When extracted, the embedded distribution is (almost) fully isolated from the
  322. user's system, including environment variables, system registry settings, and
  323. installed packages. The standard library is included as pre-compiled and
  324. optimized ``.pyc`` files in a ZIP, and ``python3.dll``, ``python37.dll``,
  325. ``python.exe`` and ``pythonw.exe`` are all provided. Tcl/tk (including all
  326. dependants, such as Idle), pip and the Python documentation are not included.
  327. .. note::
  328. The embedded distribution does not include the `Microsoft C Runtime
  329. <https://www.microsoft.com/en-us/download/details.aspx?id=48145>`_ and it is
  330. the responsibility of the application installer to provide this. The
  331. runtime may have already been installed on a user's system previously or
  332. automatically via Windows Update, and can be detected by finding
  333. ``ucrtbase.dll`` in the system directory.
  334. Third-party packages should be installed by the application installer alongside
  335. the embedded distribution. Using pip to manage dependencies as for a regular
  336. Python installation is not supported with this distribution, though with some
  337. care it may be possible to include and use pip for automatic updates. In
  338. general, third-party packages should be treated as part of the application
  339. ("vendoring") so that the developer can ensure compatibility with newer
  340. versions before providing updates to users.
  341. The two recommended use cases for this distribution are described below.
  342. Python Application
  343. ------------------
  344. An application written in Python does not necessarily require users to be aware
  345. of that fact. The embedded distribution may be used in this case to include a
  346. private version of Python in an install package. Depending on how transparent it
  347. should be (or conversely, how professional it should appear), there are two
  348. options.
  349. Using a specialized executable as a launcher requires some coding, but provides
  350. the most transparent experience for users. With a customized launcher, there are
  351. no obvious indications that the program is running on Python: icons can be
  352. customized, company and version information can be specified, and file
  353. associations behave properly. In most cases, a custom launcher should simply be
  354. able to call ``Py_Main`` with a hard-coded command line.
  355. The simpler approach is to provide a batch file or generated shortcut that
  356. directly calls the ``python.exe`` or ``pythonw.exe`` with the required
  357. command-line arguments. In this case, the application will appear to be Python
  358. and not its actual name, and users may have trouble distinguishing it from other
  359. running Python processes or file associations.
  360. With the latter approach, packages should be installed as directories alongside
  361. the Python executable to ensure they are available on the path. With the
  362. specialized launcher, packages can be located in other locations as there is an
  363. opportunity to specify the search path before launching the application.
  364. Embedding Python
  365. ----------------
  366. Applications written in native code often require some form of scripting
  367. language, and the embedded Python distribution can be used for this purpose. In
  368. general, the majority of the application is in native code, and some part will
  369. either invoke ``python.exe`` or directly use ``python3.dll``. For either case,
  370. extracting the embedded distribution to a subdirectory of the application
  371. installation is sufficient to provide a loadable Python interpreter.
  372. As with the application use, packages can be installed to any location as there
  373. is an opportunity to specify search paths before initializing the interpreter.
  374. Otherwise, there is no fundamental differences between using the embedded
  375. distribution and a regular installation.
  376. Alternative bundles
  377. ===================
  378. Besides the standard CPython distribution, there are modified packages including
  379. additional functionality. The following is a list of popular versions and their
  380. key features:
  381. `ActivePython <https://www.activestate.com/activepython/>`_
  382. Installer with multi-platform compatibility, documentation, PyWin32
  383. `Anaconda <https://www.anaconda.com/download/>`_
  384. Popular scientific modules (such as numpy, scipy and pandas) and the
  385. ``conda`` package manager.
  386. `Canopy <https://www.enthought.com/product/canopy/>`_
  387. A "comprehensive Python analysis environment" with editors and other
  388. development tools.
  389. `WinPython <https://winpython.github.io/>`_
  390. Windows-specific distribution with prebuilt scientific packages and
  391. tools for building packages.
  392. Note that these packages may not include the latest versions of Python or
  393. other libraries, and are not maintained or supported by the core Python team.
  394. Configuring Python
  395. ==================
  396. To run Python conveniently from a command prompt, you might consider changing
  397. some default environment variables in Windows. While the installer provides an
  398. option to configure the PATH and PATHEXT variables for you, this is only
  399. reliable for a single, system-wide installation. If you regularly use multiple
  400. versions of Python, consider using the :ref:`launcher`.
  401. .. _setting-envvars:
  402. Excursus: Setting environment variables
  403. ---------------------------------------
  404. Windows allows environment variables to be configured permanently at both the
  405. User level and the System level, or temporarily in a command prompt.
  406. To temporarily set environment variables, open Command Prompt and use the
  407. :command:`set` command:
  408. .. code-block:: doscon
  409. C:\>set PATH=C:\Program Files\Python 3.7;%PATH%
  410. C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
  411. C:\>python
  412. These changes will apply to any further commands executed in that console, and
  413. will be inherited by any applications started from the console.
  414. Including the variable name within percent signs will expand to the existing
  415. value, allowing you to add your new value at either the start or the end.
  416. Modifying :envvar:`PATH` by adding the directory containing
  417. :program:`python.exe` to the start is a common way to ensure the correct version
  418. of Python is launched.
  419. To permanently modify the default environment variables, click Start and search
  420. for 'edit environment variables', or open System properties, :guilabel:`Advanced
  421. system settings` and click the :guilabel:`Environment Variables` button.
  422. In this dialog, you can add or modify User and System variables. To change
  423. System variables, you need non-restricted access to your machine
  424. (i.e. Administrator rights).
  425. .. note::
  426. Windows will concatenate User variables *after* System variables, which may
  427. cause unexpected results when modifying :envvar:`PATH`.
  428. The :envvar:`PYTHONPATH` variable is used by all versions of Python 2 and
  429. Python 3, so you should not permanently configure this variable unless it
  430. only includes code that is compatible with all of your installed Python
  431. versions.
  432. .. seealso::
  433. https://www.microsoft.com/en-us/wdsi/help/folder-variables
  434. Environment variables in Windows NT
  435. https://technet.microsoft.com/en-us/library/cc754250.aspx
  436. The SET command, for temporarily modifying environment variables
  437. https://technet.microsoft.com/en-us/library/cc755104.aspx
  438. The SETX command, for permanently modifying environment variables
  439. https://support.microsoft.com/en-us/help/310519/how-to-manage-environment-variables-in-windows-xp
  440. How To Manage Environment Variables in Windows XP
  441. https://www.chem.gla.ac.uk/~louis/software/faq/q1.html
  442. Setting Environment variables, Louis J. Farrugia
  443. .. _windows-path-mod:
  444. Finding the Python executable
  445. -----------------------------
  446. .. versionchanged:: 3.5
  447. Besides using the automatically created start menu entry for the Python
  448. interpreter, you might want to start Python in the command prompt. The
  449. installer has an option to set that up for you.
  450. On the first page of the installer, an option labelled "Add Python to PATH"
  451. may be selected to have the installer add the install location into the
  452. :envvar:`PATH`. The location of the :file:`Scripts\\` folder is also added.
  453. This allows you to type :command:`python` to run the interpreter, and
  454. :command:`pip` for the package installer. Thus, you can also execute your
  455. scripts with command line options, see :ref:`using-on-cmdline` documentation.
  456. If you don't enable this option at install time, you can always re-run the
  457. installer, select Modify, and enable it. Alternatively, you can manually
  458. modify the :envvar:`PATH` using the directions in :ref:`setting-envvars`. You
  459. need to set your :envvar:`PATH` environment variable to include the directory
  460. of your Python installation, delimited by a semicolon from other entries. An
  461. example variable could look like this (assuming the first two entries already
  462. existed)::
  463. C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.7
  464. .. _launcher:
  465. Python Launcher for Windows
  466. ===========================
  467. .. versionadded:: 3.3
  468. The Python launcher for Windows is a utility which aids in locating and
  469. executing of different Python versions. It allows scripts (or the
  470. command-line) to indicate a preference for a specific Python version, and
  471. will locate and execute that version.
  472. Unlike the :envvar:`PATH` variable, the launcher will correctly select the most
  473. appropriate version of Python. It will prefer per-user installations over
  474. system-wide ones, and orders by language version rather than using the most
  475. recently installed version.
  476. The launcher was originally specified in :pep:`397`.
  477. Getting started
  478. ---------------
  479. From the command-line
  480. ^^^^^^^^^^^^^^^^^^^^^
  481. .. versionchanged:: 3.6
  482. System-wide installations of Python 3.3 and later will put the launcher on your
  483. :envvar:`PATH`. The launcher is compatible with all available versions of
  484. Python, so it does not matter which version is installed. To check that the
  485. launcher is available, execute the following command in Command Prompt:
  486. ::
  487. py
  488. You should find that the latest version of Python you have installed is
  489. started - it can be exited as normal, and any additional command-line
  490. arguments specified will be sent directly to Python.
  491. If you have multiple versions of Python installed (e.g., 2.7 and |version|) you
  492. will have noticed that Python |version| was started - to launch Python 2.7, try
  493. the command:
  494. ::
  495. py -2.7
  496. If you want the latest version of Python 2.x you have installed, try the
  497. command:
  498. ::
  499. py -2
  500. You should find the latest version of Python 2.x starts.
  501. If you see the following error, you do not have the launcher installed:
  502. ::
  503. 'py' is not recognized as an internal or external command,
  504. operable program or batch file.
  505. Per-user installations of Python do not add the launcher to :envvar:`PATH`
  506. unless the option was selected on installation.
  507. Virtual environments
  508. ^^^^^^^^^^^^^^^^^^^^
  509. .. versionadded:: 3.5
  510. If the launcher is run with no explicit Python version specification, and a
  511. virtual environment (created with the standard library :mod:`venv` module or
  512. the external ``virtualenv`` tool) active, the launcher will run the virtual
  513. environment's interpreter rather than the global one. To run the global
  514. interpreter, either deactivate the virtual environment, or explicitly specify
  515. the global Python version.
  516. From a script
  517. ^^^^^^^^^^^^^
  518. Let's create a test Python script - create a file called ``hello.py`` with the
  519. following contents
  520. .. code-block:: python
  521. #! python
  522. import sys
  523. sys.stdout.write("hello from Python %s\n" % (sys.version,))
  524. From the directory in which hello.py lives, execute the command:
  525. ::
  526. py hello.py
  527. You should notice the version number of your latest Python 2.x installation
  528. is printed. Now try changing the first line to be:
  529. .. code-block:: python
  530. #! python3
  531. Re-executing the command should now print the latest Python 3.x information.
  532. As with the above command-line examples, you can specify a more explicit
  533. version qualifier. Assuming you have Python 2.6 installed, try changing the
  534. first line to ``#! python2.6`` and you should find the 2.6 version
  535. information printed.
  536. Note that unlike interactive use, a bare "python" will use the latest
  537. version of Python 2.x that you have installed. This is for backward
  538. compatibility and for compatibility with Unix, where the command ``python``
  539. typically refers to Python 2.
  540. From file associations
  541. ^^^^^^^^^^^^^^^^^^^^^^
  542. The launcher should have been associated with Python files (i.e. ``.py``,
  543. ``.pyw``, ``.pyc`` files) when it was installed. This means that
  544. when you double-click on one of these files from Windows explorer the launcher
  545. will be used, and therefore you can use the same facilities described above to
  546. have the script specify the version which should be used.
  547. The key benefit of this is that a single launcher can support multiple Python
  548. versions at the same time depending on the contents of the first line.
  549. Shebang Lines
  550. -------------
  551. If the first line of a script file starts with ``#!``, it is known as a
  552. "shebang" line. Linux and other Unix like operating systems have native
  553. support for such lines and they are commonly used on such systems to indicate
  554. how a script should be executed. This launcher allows the same facilities to
  555. be used with Python scripts on Windows and the examples above demonstrate their
  556. use.
  557. To allow shebang lines in Python scripts to be portable between Unix and
  558. Windows, this launcher supports a number of 'virtual' commands to specify
  559. which interpreter to use. The supported virtual commands are:
  560. * ``/usr/bin/env python``
  561. * ``/usr/bin/python``
  562. * ``/usr/local/bin/python``
  563. * ``python``
  564. For example, if the first line of your script starts with
  565. .. code-block:: sh
  566. #! /usr/bin/python
  567. The default Python will be located and used. As many Python scripts written
  568. to work on Unix will already have this line, you should find these scripts can
  569. be used by the launcher without modification. If you are writing a new script
  570. on Windows which you hope will be useful on Unix, you should use one of the
  571. shebang lines starting with ``/usr``.
  572. Any of the above virtual commands can be suffixed with an explicit version
  573. (either just the major version, or the major and minor version).
  574. Furthermore the 32-bit version can be requested by adding "-32" after the
  575. minor version. I.e. ``/usr/bin/python2.7-32`` will request usage of the
  576. 32-bit python 2.7.
  577. .. versionadded:: 3.7
  578. Beginning with python launcher 3.7 it is possible to request 64-bit version
  579. by the "-64" suffix. Furthermore it is possible to specify a major and
  580. architecture without minor (i.e. ``/usr/bin/python3-64``).
  581. The ``/usr/bin/env`` form of shebang line has one further special property.
  582. Before looking for installed Python interpreters, this form will search the
  583. executable :envvar:`PATH` for a Python executable. This corresponds to the
  584. behaviour of the Unix ``env`` program, which performs a :envvar:`PATH` search.
  585. Arguments in shebang lines
  586. --------------------------
  587. The shebang lines can also specify additional options to be passed to the
  588. Python interpreter. For example, if you have a shebang line:
  589. .. code-block:: sh
  590. #! /usr/bin/python -v
  591. Then Python will be started with the ``-v`` option
  592. Customization
  593. -------------
  594. Customization via INI files
  595. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  596. Two .ini files will be searched by the launcher - ``py.ini`` in the current
  597. user's "application data" directory (i.e. the directory returned by calling the
  598. Windows function ``SHGetFolderPath`` with ``CSIDL_LOCAL_APPDATA``) and ``py.ini`` in the
  599. same directory as the launcher. The same .ini files are used for both the
  600. 'console' version of the launcher (i.e. py.exe) and for the 'windows' version
  601. (i.e. pyw.exe).
  602. Customization specified in the "application directory" will have precedence over
  603. the one next to the executable, so a user, who may not have write access to the
  604. .ini file next to the launcher, can override commands in that global .ini file.
  605. Customizing default Python versions
  606. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  607. In some cases, a version qualifier can be included in a command to dictate
  608. which version of Python will be used by the command. A version qualifier
  609. starts with a major version number and can optionally be followed by a period
  610. ('.') and a minor version specifier. Furthermore it is possible to specifiy
  611. if a 32 or 64 bit implementation shall be requested by adding "-32" or "-64".
  612. For example, a shebang line of ``#!python`` has no version qualifier, while
  613. ``#!python3`` has a version qualifier which specifies only a major version.
  614. If no version qualifiers are found in a command, the environment
  615. variable :envvar:`PY_PYTHON` can be set to specify the default version
  616. qualifier. If it is not set, the default is "3". The variable can
  617. specify any value that may be passed on the command line, such as "3",
  618. "3.7", "3.7-32" or "3.7-64". (Note that the "-64" option is only
  619. available with the launcher included with Python 3.7 or newer.)
  620. If no minor version qualifiers are found, the environment variable
  621. ``PY_PYTHON{major}`` (where ``{major}`` is the current major version qualifier
  622. as determined above) can be set to specify the full version. If no such option
  623. is found, the launcher will enumerate the installed Python versions and use
  624. the latest minor release found for the major version, which is likely,
  625. although not guaranteed, to be the most recently installed version in that
  626. family.
  627. On 64-bit Windows with both 32-bit and 64-bit implementations of the same
  628. (major.minor) Python version installed, the 64-bit version will always be
  629. preferred. This will be true for both 32-bit and 64-bit implementations of the
  630. launcher - a 32-bit launcher will prefer to execute a 64-bit Python installation
  631. of the specified version if available. This is so the behavior of the launcher
  632. can be predicted knowing only what versions are installed on the PC and
  633. without regard to the order in which they were installed (i.e., without knowing
  634. whether a 32 or 64-bit version of Python and corresponding launcher was
  635. installed last). As noted above, an optional "-32" or "-64" suffix can be
  636. used on a version specifier to change this behaviour.
  637. Examples:
  638. * If no relevant options are set, the commands ``python`` and
  639. ``python2`` will use the latest Python 2.x version installed and
  640. the command ``python3`` will use the latest Python 3.x installed.
  641. * The commands ``python3.1`` and ``python2.7`` will not consult any
  642. options at all as the versions are fully specified.
  643. * If ``PY_PYTHON=3``, the commands ``python`` and ``python3`` will both use
  644. the latest installed Python 3 version.
  645. * If ``PY_PYTHON=3.1-32``, the command ``python`` will use the 32-bit
  646. implementation of 3.1 whereas the command ``python3`` will use the latest
  647. installed Python (PY_PYTHON was not considered at all as a major
  648. version was specified.)
  649. * If ``PY_PYTHON=3`` and ``PY_PYTHON3=3.1``, the commands
  650. ``python`` and ``python3`` will both use specifically 3.1
  651. In addition to environment variables, the same settings can be configured
  652. in the .INI file used by the launcher. The section in the INI file is
  653. called ``[defaults]`` and the key name will be the same as the
  654. environment variables without the leading ``PY_`` prefix (and note that
  655. the key names in the INI file are case insensitive.) The contents of
  656. an environment variable will override things specified in the INI file.
  657. For example:
  658. * Setting ``PY_PYTHON=3.1`` is equivalent to the INI file containing:
  659. .. code-block:: ini
  660. [defaults]
  661. python=3.1
  662. * Setting ``PY_PYTHON=3`` and ``PY_PYTHON3=3.1`` is equivalent to the INI file
  663. containing:
  664. .. code-block:: ini
  665. [defaults]
  666. python=3
  667. python3=3.1
  668. Diagnostics
  669. -----------
  670. If an environment variable ``PYLAUNCH_DEBUG`` is set (to any value), the
  671. launcher will print diagnostic information to stderr (i.e. to the console).
  672. While this information manages to be simultaneously verbose *and* terse, it
  673. should allow you to see what versions of Python were located, why a
  674. particular version was chosen and the exact command-line used to execute the
  675. target Python.
  676. .. _finding_modules:
  677. Finding modules
  678. ===============
  679. Python usually stores its library (and thereby your site-packages folder) in the
  680. installation directory. So, if you had installed Python to
  681. :file:`C:\\Python\\`, the default library would reside in
  682. :file:`C:\\Python\\Lib\\` and third-party modules should be stored in
  683. :file:`C:\\Python\\Lib\\site-packages\\`.
  684. To completely override :data:`sys.path`, create a ``._pth`` file with the same
  685. name as the DLL (``python37._pth``) or the executable (``python._pth``) and
  686. specify one line for each path to add to :data:`sys.path`. The file based on the
  687. DLL name overrides the one based on the executable, which allows paths to be
  688. restricted for any program loading the runtime if desired.
  689. When the file exists, all registry and environment variables are ignored,
  690. isolated mode is enabled, and :mod:`site` is not imported unless one line in the
  691. file specifies ``import site``. Blank paths and lines starting with ``#`` are
  692. ignored. Each path may be absolute or relative to the location of the file.
  693. Import statements other than to ``site`` are not permitted, and arbitrary code
  694. cannot be specified.
  695. Note that ``.pth`` files (without leading underscore) will be processed normally
  696. by the :mod:`site` module when ``import site`` has been specified.
  697. When no ``._pth`` file is found, this is how :data:`sys.path` is populated on
  698. Windows:
  699. * An empty entry is added at the start, which corresponds to the current
  700. directory.
  701. * If the environment variable :envvar:`PYTHONPATH` exists, as described in
  702. :ref:`using-on-envvars`, its entries are added next. Note that on Windows,
  703. paths in this variable must be separated by semicolons, to distinguish them
  704. from the colon used in drive identifiers (``C:\`` etc.).
  705. * Additional "application paths" can be added in the registry as subkeys of
  706. :samp:`\\SOFTWARE\\Python\\PythonCore\\{version}\\PythonPath` under both the
  707. ``HKEY_CURRENT_USER`` and ``HKEY_LOCAL_MACHINE`` hives. Subkeys which have
  708. semicolon-delimited path strings as their default value will cause each path
  709. to be added to :data:`sys.path`. (Note that all known installers only use
  710. HKLM, so HKCU is typically empty.)
  711. * If the environment variable :envvar:`PYTHONHOME` is set, it is assumed as
  712. "Python Home". Otherwise, the path of the main Python executable is used to
  713. locate a "landmark file" (either ``Lib\os.py`` or ``pythonXY.zip``) to deduce
  714. the "Python Home". If a Python home is found, the relevant sub-directories
  715. added to :data:`sys.path` (``Lib``, ``plat-win``, etc) are based on that
  716. folder. Otherwise, the core Python path is constructed from the PythonPath
  717. stored in the registry.
  718. * If the Python Home cannot be located, no :envvar:`PYTHONPATH` is specified in
  719. the environment, and no registry entries can be found, a default path with
  720. relative entries is used (e.g. ``.\Lib;.\plat-win``, etc).
  721. If a ``pyvenv.cfg`` file is found alongside the main executable or in the
  722. directory one level above the executable, the following variations apply:
  723. * If ``home`` is an absolute path and :envvar:`PYTHONHOME` is not set, this
  724. path is used instead of the path to the main executable when deducing the
  725. home location.
  726. The end result of all this is:
  727. * When running :file:`python.exe`, or any other .exe in the main Python
  728. directory (either an installed version, or directly from the PCbuild
  729. directory), the core path is deduced, and the core paths in the registry are
  730. ignored. Other "application paths" in the registry are always read.
  731. * When Python is hosted in another .exe (different directory, embedded via COM,
  732. etc), the "Python Home" will not be deduced, so the core path from the
  733. registry is used. Other "application paths" in the registry are always read.
  734. * If Python can't find its home and there are no registry value (frozen .exe,
  735. some very strange installation setup) you get a path with some default, but
  736. relative, paths.
  737. For those who want to bundle Python into their application or distribution, the
  738. following advice will prevent conflicts with other installations:
  739. * Include a ``._pth`` file alongside your executable containing the
  740. directories to include. This will ignore paths listed in the registry and
  741. environment variables, and also ignore :mod:`site` unless ``import site`` is
  742. listed.
  743. * If you are loading :file:`python3.dll` or :file:`python37.dll` in your own
  744. executable, explicitly call :c:func:`Py_SetPath` or (at least)
  745. :c:func:`Py_SetProgramName` before :c:func:`Py_Initialize`.
  746. * Clear and/or overwrite :envvar:`PYTHONPATH` and set :envvar:`PYTHONHOME`
  747. before launching :file:`python.exe` from your application.
  748. * If you cannot use the previous suggestions (for example, you are a
  749. distribution that allows people to run :file:`python.exe` directly), ensure
  750. that the landmark file (:file:`Lib\\os.py`) exists in your install directory.
  751. (Note that it will not be detected inside a ZIP file, but a correctly named
  752. ZIP file will be detected instead.)
  753. These will ensure that the files in a system-wide installation will not take
  754. precedence over the copy of the standard library bundled with your application.
  755. Otherwise, your users may experience problems using your application. Note that
  756. the first suggestion is the best, as the others may still be susceptible to
  757. non-standard paths in the registry and user site-packages.
  758. .. versionchanged::
  759. 3.6
  760. * Adds ``._pth`` file support and removes ``applocal`` option from
  761. ``pyvenv.cfg``.
  762. * Adds ``pythonXX.zip`` as a potential landmark when directly adjacent
  763. to the executable.
  764. .. deprecated::
  765. 3.6
  766. Modules specified in the registry under ``Modules`` (not ``PythonPath``)
  767. may be imported by :class:`importlib.machinery.WindowsRegistryFinder`.
  768. This finder is enabled on Windows in 3.6.0 and earlier, but may need to
  769. be explicitly added to :attr:`sys.meta_path` in the future.
  770. Additional modules
  771. ==================
  772. Even though Python aims to be portable among all platforms, there are features
  773. that are unique to Windows. A couple of modules, both in the standard library
  774. and external, and snippets exist to use these features.
  775. The Windows-specific standard modules are documented in
  776. :ref:`mswin-specific-services`.
  777. PyWin32
  778. -------
  779. The `PyWin32 <https://pypi.org/project/pywin32>`_ module by Mark Hammond
  780. is a collection of modules for advanced Windows-specific support. This includes
  781. utilities for:
  782. * `Component Object Model
  783. <https://docs.microsoft.com/en-us/windows/desktop/com/component-object-model--com--portal>`_
  784. (COM)
  785. * Win32 API calls
  786. * Registry
  787. * Event log
  788. * `Microsoft Foundation Classes <https://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx>`_ (MFC)
  789. user interfaces
  790. `PythonWin <https://web.archive.org/web/20060524042422/
  791. https://www.python.org/windows/pythonwin/>`_ is a sample MFC application
  792. shipped with PyWin32. It is an embeddable IDE with a built-in debugger.
  793. .. seealso::
  794. `Win32 How Do I...? <http://timgolden.me.uk/python/win32_how_do_i.html>`_
  795. by Tim Golden
  796. `Python and COM <http://www.boddie.org.uk/python/COM.html>`_
  797. by David and Paul Boddie
  798. cx_Freeze
  799. ---------
  800. `cx_Freeze <https://anthony-tuininga.github.io/cx_Freeze/>`_ is a :mod:`distutils`
  801. extension (see :ref:`extending-distutils`) which wraps Python scripts into
  802. executable Windows programs (:file:`{*}.exe` files). When you have done this,
  803. you can distribute your application without requiring your users to install
  804. Python.
  805. WConio
  806. ------
  807. Since Python's advanced terminal handling layer, :mod:`curses`, is restricted to
  808. Unix-like systems, there is a library exclusive to Windows as well: Windows
  809. Console I/O for Python.
  810. `WConio <http://newcenturycomputers.net/projects/wconio.html>`_ is a wrapper for
  811. Turbo-C's :file:`CONIO.H`, used to create text user interfaces.
  812. Compiling Python on Windows
  813. ===========================
  814. If you want to compile CPython yourself, first thing you should do is get the
  815. `source <https://www.python.org/downloads/source/>`_. You can download either the
  816. latest release's source or just grab a fresh `checkout
  817. <https://devguide.python.org/setup/#getting-the-source-code>`_.
  818. The source tree contains a build solution and project files for Microsoft
  819. Visual Studio 2015, which is the compiler used to build the official Python
  820. releases. These files are in the :file:`PCbuild` directory.
  821. Check :file:`PCbuild/readme.txt` for general information on the build process.
  822. For extension modules, consult :ref:`building-on-windows`.
  823. .. seealso::
  824. `Python + Windows + distutils + SWIG + gcc MinGW <http://sebsauvage.net/python/mingw.html>`_
  825. or "Creating Python extensions in C/C++ with SWIG and compiling them with
  826. MinGW gcc under Windows" or "Installing Python extensio