Python launcher что это за программа
Перейти к содержимому

Python launcher что это за программа

  • автор:

Python Launcher for Windows

Logo Python launcher for Windows

The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.

Getting started

From the command-line

You should ensure the launcher is on your PATH — depending on how it was installed it may already be there, but check just in case it is not.

From a command-prompt, execute the following command:

You should find that the latest version of Python 2.x you have installed is started — it can be exited as normal, and any additional command-line arguments specified will be sent directly to Python.

If you have multiple versions of Python 2.x installed (e.g., 2.6 and 2.7) you will have noticed that Python 2.7 was started — to launch Python 2.6, try the command:

If you have a Python 3.x installed, try the command:

You should find the latest version of Python 3.x starts.

From a script

Let’s create a test Python script — create a file called hello.py with the following contents

From the directory in which hello.py lives, execute the command:

You should notice the version number of your latest Python 2.x installation is printed. Now try changing the first line to be:

Re-executing the command should now print the latest Python 3.x information. As with the above command-line examples, you can specify a more explicit version qualifier. Assuming you have Python 2.6 installed, try changing the first line to #! python2.6 and you should find the 2.6 version information printed.

From file associations

The launcher should have been associated with Python files (i.e. .py, .pyw, .pyc, .pyo files) when it was installed. This means that when you double-click on one of these files from Windows explorer the launcher will be used, and therefore you can use the same facilities described above to have the script specify the version which should be used.

The key benefit of this is that a single launcher can support multiple Python versions at the same time depending on the contents of the first line.

If you type the following at a command line:

and if you type:

Similarly, .pyc and .pyo files should map to Python.CompiledFile, and .pyw should map to Python.NoConFile. While Python.CompiledFile maps to the same executable as Python.File, Python.NoConFile should map to pyw.exe rather than py.exe.

Shebang Lines

If the first line of a script file starts with #!, it is known as a "shebang" line. Linux and other Unix like operating systems have native support for such lines and are commonly used on such systems to indicate how a script should be executed. This launcher allows the same facilities to be using with Python scripts on Windows and the examples above demonstrate their use.

To allow shebang lines in Python scripts to be portable between Unix and Windows, this launcher supports a number of ‘virtual’ commands to specify which interpreter to use. The supported virtual commands are:

  • /usr/bin/env python
  • /usr/bin/python
  • /usr/local/bin/python
  • python

For example, if the first line of your script starts with

The default Python will be located and used. As many Python scripts written to work on Unix will already have this line, you should find these scripts can be used by the launcher without modification. If you are writing a new script on Windows which you hope will be useful on Unix, you should use one of the shebang lines starting with /usr.

Arguments in shebang lines

The shebang lines can also specify additional options to be passed to the Python interpreter. For example, if you have a shebang line:

Then Python will be started with the -v option

Customization

Customization via INI files

Two .ini files will be searched by the launcher — py.ini in the current user’s "application data" directory (i.e. the directory returned by calling the Windows function SHGetFolderPath with CSIDL_LOCAL_APPDATA) and py.ini in the same directory as the launcher. The same .ini files are used for both the ‘console’ version of the launcher (i.e. py.exe) and for the ‘windows’ version (i.e. pyw.exe)

Customization specified in the "application directory" will have precedence over the one next to the executable, so a user, who may not have write access to the .ini file next to the launcher, can override commands in that global .ini file)

Customizing default Python versions

In some cases, a version qualifier can be included in a command to dictate which version of Python will be used by the command. A version qualifier starts with a major version number and can optionally be followed by a period (‘.’) and a minor version specifier. If the minor qualifier is specified, it may optionally be followed by "-32" to indicate the 32-bit implementation of that version be used.

For example, a shebang line of #!python has no version qualifier, while #!python3 has a version qualifier which specifies only a major version.

If no version qualifiers are found in a command, the environment variable PY_PYTHON can be set to specify the default version qualifier — the default value is "2". Note this value could specify just a major version (e.g. "2") or a major.minor qualifier (e.g. "2.6"), or even major.minor-32.

If no minor version qualifiers are found, the environment variable PY_PYTHON (where is the current major version qualifier as determined above) can be set to specify the full version. If no such option is found, the launcher will enumerate the installed Python versions and use the latest minor release found for the major version, which is likely, although not guaranteed, to be the most recently installed version in that family.

On 64-bit Windows with both 32-bit and 64-bit implementations of the same (major.minor) Python version installed, the 64-bit version will always be preferred. This will be true for both 32-bit and 64-bit implementations of the launcher - a 32-bit launcher will prefer to execute a 64-bit Python installation of the specified version if available. This is so the behavior of the launcher can be predicted knowing only what versions are installed on the PC and without regard to the order in which they were installed (i.e., without knowing whether a 32 or 64-bit version of Python and corresponding launcher was installed last). As noted above, an optional "-32" suffix can be used on a version specifier to change this behaviour.

  • If no relevant options are set, the commands python and python2 will use the latest Python 2.x version installed and the command python3 will use the latest Python 3.x installed.
  • The commands python3.1 and python2.7 will not consult any options at all as the versions are fully specified.
  • If PY_PYTHON=3, the commands python and python3 will both use the latest installed Python 3 version.
  • If PY_PYTHON=3.1-32 , the command python will use the 32-bit implementation of 3.1 whereas the command python3 will use the latest installed Python (PY_PYTHON was not considered at all as a major version was specified.)
  • If PY_PYTHON=3 and PY_PYTHON3=3.1, the commands python and python3 will both use specifically 3.1

In addition to environment variables, the same settings can be configured in the .INI file used by the launcher. The section in the INI file is called [defaults] and the key name will be the same as the environment variables without the leading PY\_ prefix (and note that the key names in the INI file are case insensitive.) The contents of an environment variable will override things specified in the INI file.

PEP 397 – Python launcher for Windows

This PEP describes a Python launcher for the Windows platform. A Python launcher is a single executable which uses a number of heuristics to locate a Python executable and launch it with a specified command line.

Rationale

Windows provides “file associations” so an executable can be associated with an extension, allowing for scripts to be executed directly in some contexts (eg., double-clicking the file in Windows Explorer.) Until now, a strategy of “last installed Python wins” has been used and while not ideal, has generally been workable due to the conservative changes in Python 2.x releases. As Python 3.x scripts are often syntactically incompatible with Python 2.x scripts, a different strategy must be used to allow files with a ‘.py’ extension to use a different executable based on the Python version the script targets. This will be done by borrowing the existing practices of another operating system - scripts will be able to nominate the version of Python they need by way of a “shebang” line, as described below.

Unix-like operating systems (referred to simply as “Unix” in this PEP) allow scripts to be executed as if they were executable images by examining the script for a “shebang” line which specifies the actual executable to be used to run the script. This is described in detail in the evecve(2) man page [1] and while user documentation will be created for this feature, for the purposes of this PEP that man page describes a valid shebang line.

Additionally, these operating systems provide symbolic-links to Python executables in well-known directories. For example, many systems will have a link /usr/bin/python which references a particular version of Python installed under the operating-system. These symbolic links allow Python to be executed without regard for where Python it actually installed on the machine (eg., without requiring the path where Python is actually installed to be referenced in the shebang line or in the PATH .) PEP 394 ‘The “python” command on Unix-Like Systems’ describes additional conventions for more fine-grained specification of a particular Python version.

These 2 facilities combined allow for a portable and somewhat predictable way of both starting Python interactively and for allowing Python scripts to execute. This PEP describes an implementation of a launcher which can offer the same benefits for Python on the Windows platform and therefore allows the launcher to be the executable associated with ‘.py’ files to support multiple Python versions concurrently.

While this PEP offers the ability to use a shebang line which should work on both Windows and Unix, this is not the primary motivation for this PEP - the primary motivation is to allow a specific version to be specified without inventing new syntax or conventions to describe it.

Specification

This PEP specifies features of the launcher; a prototype implementation is provided in [3] which will be distributed together with the Windows installer of Python, but will also be available separately (but released along with the Python installer). New features may be added to the launcher as long as the features prescribed here continue to work.

Installation

The launcher comes in 2 versions - one which is a console program and one which is a “windows” (ie., GUI) program. These 2 launchers correspond to the ‘python.exe’ and ‘pythonw.exe’ executables which currently ship with Python. The console launcher will be named ‘py.exe’ and the Windows one named ‘pyw.exe’. The “windows” (ie., GUI) version of the launcher will attempt to locate and launch pythonw.exe even if a virtual shebang line nominates simply “python” - in fact, the trailing ‘w’ notation is not supported in the virtual shebang line at all.

The launcher is installed into the Windows directory (see discussion below) if installed by a privileged user. The stand-alone installer asks for an alternative location of the installer, and adds that location to the user’s PATH .

The installation in the Windows directory is a 32-bit executable (see discussion); the standalone installer may also offer to install 64-bit versions of the launcher.

The launcher installation is registered in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\CurrentVersion\SharedDLLs with a reference counter. It contains a version resource matching the version number of the pythonXY.dll with which it is distributed. Independent installations will overwrite older version of the launcher with newer versions. Stand-alone releases use a release level of 0x10 in FIELD3 of the CPython release on which they are based.

Once installed, the “console” version of the launcher is associated with .py files and the “windows” version associated with .pyw files.

The launcher is not tied to a specific version of Python - eg., a launcher distributed with Python 3.3 should be capable of locating and executing any Python 2.x and Python 3.x version. However, the launcher binaries have a version resource that is the same as the version resource in the Python binaries that they are released with.

Python Script Launching

The launcher is restricted to launching Python scripts. It is not intended as a general-purpose script launcher or shebang processor.

The launcher supports the syntax of shebang lines as described in [1], including all restrictions listed.

The launcher supports shebang lines referring to Python executables with any of the (regex) prefixes “/usr/bin/”, “/usr/local/bin” and “/usr/bin/env *”, as well as binaries specified without

For example, a shebang line of ‘#! /usr/bin/python’ should work even though there is unlikely to be an executable in the relative Windows directory “\usr\bin”. This means that many scripts can use a single shebang line and be likely to work on both Unix and Windows without modification.

The launcher will support fully-qualified paths to executables. While this will make the script inherently non-portable, it is a feature offered by Unix and would be useful for Windows users in some cases.

The launcher will be capable of supporting implementations other than CPython, such as jython and IronPython, but given both the absence of common links on Unix (such as “/usr/bin/jython”) and the inability for the launcher to automatically locate the installation location of these implementations on Windows, the launcher will support this via customization options. Scripts taking advantage of this will not be portable (as these customization options must be set to reflect the configuration of the machine on which the launcher is running) but this ability is nonetheless considered worthwhile.

On Unix, the user can control which specific version of Python is used by adjusting the links in /usr/bin to point to the desired version. As the launcher on Windows will not use Windows links, customization options (exposed via both environment variables and INI files) will be used to override the semantics for determining what version of Python will be used. For example, while a shebang line of “/usr/bin/python2” will automatically locate a Python 2.x implementation, an environment variable can override exactly which Python 2.x implementation will be chosen. Similarly for “/usr/bin/python” and “/usr/bin/python3”. This is specified in detail later in this PEP.

Shebang line parsing

If the first command-line argument does not start with a dash (‘-‘) character, an attempt will be made to open that argument as a file and parsed for a shebang line according to the rules in [1]:

Once parsed, the command will be categorized according to the following rules:

  • If the command starts with the definition of a customized command followed by a whitespace character (including a newline), the customized command will be used. See below for a description of customized commands.
  • The launcher will define a set of prefixes which are considered Unix compatible commands to launch Python, namely “/usr/bin/python”, “/usr/local/bin/python”, “/usr/bin/env python”, and “python”. If a command starts with one of these strings will be treated as a ‘virtual command’ and the rules described in Python Version Qualifiers (below) will be used to locate the executable to use.
  • Otherwise the command is assumed to be directly ready to execute - ie. a fully-qualified path (or a reference to an executable on the PATH ) optionally followed by arguments. The contents of the string will not be parsed - it will be passed directly to the Windows CreateProcess function after appending the name of the script and the launcher command-line arguments. This means that the rules used by CreateProcess will be used, including how relative path names and executable references without extensions are treated. Notably, the Windows command processor will not be used, so special rules used by the command processor (such as automatic appending of extensions other than ‘.exe’, support for batch files, etc) will not be used.

The use of ‘virtual’ shebang lines is encouraged as this should allow for portable shebang lines to be specified which work on multiple operating systems and different installations of the same operating system.

If the first argument can not be opened as a file or if no valid shebang line can be found, the launcher will act as if a shebang line of ‘#!python’ was found - ie., a default Python interpreter will be located and the arguments passed to that. However, if a valid shebang line is found but the process specified by that line can not be started, the default interpreter will not be started - the error to create the specified child process will cause the launcher to display an appropriate message and terminate with a specific exit code.

Configuration file

Two .ini files will be searched by the launcher - py.ini in the current user’s “application data” directory (i.e. the directory returned by calling the Windows function SHGetFolderPath with CSIDL_LOCAL_APPDATA , %USERPROFILE%\AppData\Local on Vista+, %USERPROFILE%\Local Settings\Application Data on XP) and py.ini in the same directory as the launcher. The same .ini files are used for both the ‘console’ version of the launcher (i.e. py.exe) and for the ‘windows’ version (i.e. pyw.exe)

Customization specified in the “application directory” will have precedence over the one next to the executable, so a user, who may not have write access to the .ini file next to the launcher, can override commands in that global .ini file)

Virtual commands in shebang lines

Virtual Commands are shebang lines which start with strings which would be expected to work on Unix platforms - examples include ‘/usr/bin/python’, ‘/usr/bin/env python’ and ‘python’. Optionally, the virtual command may be suffixed with a version qualifier (see below), such as ‘/usr/bin/python2’ or ‘/usr/bin/python3.2’. The command executed is based on the rules described in Python Version Qualifiers below.

Customized Commands

The launcher will support the ability to define “Customized Commands” in a Windows .ini file (ie, a file which can be parsed by the Windows function GetPrivateProfileString). A section called ‘[commands]’ can be created with key names defining the virtual command and the value specifying the actual command-line to be used for this virtual command.

For example, if an INI file has the contents:

Then a shebang line of ‘#! vpython’ in a script named ‘doit.py’ will result in the launcher using the command-line c:\bin\vpython.exe -foo doit.py

The precise details about the names, locations and search order of the .ini files is in the launcher documentation [4]

Python Version Qualifiers

Some of the features described allow an optional Python version qualifier to be used.

A version qualifier starts with a major version number and can optionally be followed by a period (‘.’) and a minor version specifier. If the minor qualifier is specified, it may optionally be followed by “-32” to indicate the 32bit implementation of that version be used. Note that no “-64” qualifier is necessary as this is the default implementation (see below).

On 64bit Windows with both 32bit and 64bit implementations of the same (major.minor) Python version installed, the 64bit version will always be preferred. This will be true for both 32bit and 64bit implementations of the launcher - a 32bit launcher will prefer to execute a 64bit Python installation of the specified version if available. This is so the behavior of the launcher can be predicted knowing only what versions are installed on the PC and without regard to the order in which they were installed (ie, without knowing whether a 32 or 64bit version of Python and corresponding launcher was installed last). As noted above, an optional “-32” suffix can be used on a version specifier to change this behaviour.

If no version qualifiers are found in a command, the environment variable PY_PYTHON can be set to specify the default version qualifier - the default value is “2”. Note this value could specify just a major version (e.g. “2”) or a major.minor qualifier (e.g. “2.6”), or even major.minor-32.

If no minor version qualifiers are found, the environment variable PY_PYTHON (where is the current major version qualifier as determined above) can be set to specify the full version. If no such option is found, the launcher will enumerate the installed Python versions and use the latest minor release found for the major version, which is likely, although not guaranteed, to be the most recently installed version in that family.

In addition to environment variables, the same settings can be configured in the .INI file used by the launcher. The section in the INI file is called [defaults] and the key name will be the same as the environment variables without the leading PY_ prefix (and note that the key names in the INI file are case insensitive.) The contents of an environment variable will override things specified in the INI file.

Command-line handling

Only the first command-line argument will be checked for a shebang line and only if that argument does not start with a ‘-‘.

If the only command-line argument is “-h” or “–help”, the launcher will print a small banner and command-line usage, then pass the argument to the default Python. This will cause help for the launcher being printed followed by help for Python itself. The output from the launcher will clearly indicate the extended help information is coming from the launcher and not Python.

As a concession to interactively launching Python, the launcher will support the first command-line argument optionally being a dash (“-“) followed by a version qualifier, as described above, to nominate a specific version be used. For example, while “py.exe” may locate and launch the latest Python 2.x implementation installed, a command-line such as “py.exe -3” could specify the latest Python 3.x implementation be launched, while “py.exe -2.6-32” could specify a 32bit implementation Python 2.6 be located and launched. If a Python 2.x implementation is desired to be launched with the -3 flag, the command-line would need to be similar to “py.exe -2 -3” (or the specific version of Python could obviously be launched manually without use of this launcher.) Note that this feature can not be used with shebang processing as the file scanned for a shebang line and this argument must both be the first argument and therefore are mutually exclusive.

All other arguments will be passed untouched to the child Python process.

Process Launching

The launcher offers some conveniences for Python developers working interactively - for example, starting the launcher with no command-line arguments will launch the default Python with no command-line arguments. Further, command-line arguments will be supported to allow a specific Python version to be launched interactively - however, these conveniences must not detract from the primary purpose of launching scripts and must be easy to avoid if desired.

The launcher creates a subprocess to start the actual interpreter. See Discussion below for the rationale.

Discussion

It may be surprising that the launcher is installed into the Windows directory, and not the System32 directory. The reason is that the System32 directory is not on the Path of a 32-bit process running on a 64-bit system. However, the Windows directory is always on the path.

The launcher that is installed into the Windows directory is a 32-bit executable so that the 32-bit CPython installer can provide the same binary for both 32-bit and 64-bit Windows installations.

Ideally, the launcher process would execute Python directly inside the same process, primarily so the parent of the launcher process could terminate the launcher and have the Python interpreter terminate. If the launcher executes Python as a sub-process and the parent of the launcher terminates the launcher, the Python process will be unaffected.

However, there are a number of practical problems associated with this approach. Windows does not support the execv* family of Unix functions, so this could only be done by the launcher dynamically loading the Python DLL, but this would have a number of side-effects. The most serious side effect of this is that the value of sys.executable would refer to the launcher instead of the Python implementation. Many Python scripts use the value of sys.executable to launch child processes, and these scripts may fail to work as expected if the launcher is used. Consider a “parent” script with a shebang line of ‘#! /usr/bin/python3’ which attempts to launch a child script (with no shebang) via sys.executable - currently the child is launched using the exact same version running the parent script. If sys.executable referred to the launcher the child would be likely executed using a Python 2.x version and would be likely to fail with a SyntaxError .

Another hurdle is the support for alternative Python implementations using the “customized commands” feature described above, where loading the command dynamically into a running executable is not possible.

The final hurdle is the rules above regarding 64bit and 32bit programs - a 32bit launcher would be unable to load the 64bit version of Python and vice-versa.

Given these considerations, the launcher will execute its command in a child process, remaining alive while the child process is executing, then terminate with the same exit code as returned by the child. To address concerns regarding the termination of the launcher not killing the child, the Win32 Job API will be used to arrange so that the child process is automatically killed when the parent is terminated (although children of that child process will continue as is the case now.) As this Windows API is available in Windows XP and later, this launcher will not work on Windows 2000 or earlier.

Установка Python в ОС Windows

Операционная система Windows позволяет установить сразу несколько версий интерпретатора Python . Будем считать, что нам необходимо установить последнюю из доступных на официальном сайте.

Для загрузки установочного файла последней версии Python необходимо перейти на страницу загрузок официального сайта и нажать желтую кнопку «Download Python 3.*.*» (см. рис. №1 ).

Рис. №1. Официальная страница загрузок сайта python.org.

Далее необходимо запустить загруженный установочный файл python-*.exe , который запустит окно установщика (см. рис. №2 ).

Рис. №2. Окно установщика python.

Чтобы без проблем пользоваться утилитой py launcher , которая будет запускать данную версию интерпретатора по умолчанию командой «py» , ставим галочку напротив «Use admin privileges when installing py.exe» . Если данная версия интерпретатора Python устанавливается в систему в качестве основной, то для того, чтобы в командной строке можно было обращаться к нему посредством простой команды «python» (вместо указания полного пути к интерпретатору), добавляем Python в переменную окружения PATH , поставив галочку напротив «Add Python.exe to PATH» (см. рис. №3 ).

Рис. №3. Активация пунктов для py.exe и PATH.

Если по какой-то причине при использовании команды «python» запускается интерпретатор другой версии, просто переустановите нужную версию еще раз, незабыв добавить ее в переменную окружения PATH , либо измените эту переменную в самой системе так, чтобы путь к нему стал располагаться ближе к началу списка (это для более продвинутых пользователей).

Теперь можно смело кликать по кнопке «Install now» (т.е. «Установить сейчас») и просто ждать завершения установки в предложенную папку с параметрами по умолчанию (см. рис. №4 ). Однако торопиться с выбором данного варианта не стоит, т.к. он подходит больше для обычных пользователей, которые не собираются устанавливать несколько версий интерпретатора.

Рис. №4. Установка с параметрами по умолчанию.

Для более продвинутых пользователей, лучше выбрать вариант «Customize installation» (т.е. «Выборочная установка») для самостоятельного выбора устанавливаемых параметров (см. рис. №5 ).

Рис. №5. Выборочная установка.

  • Documentation – установить документацию Python (не помешает);
  • pip – установить менеджер пакетов pip для загрузки сторонних пакетов и библиотек, написанных на Python (выбираем обязательно);
  • tcl/tk and IDLE – установить средства разработки на Python (не помешает);
  • Python test suite – установить библиотеку для тестирования приложений (не помешает);
  • py launcher – утилита, которая помогает находить и запускать сценариям (или командной строке) различные версии Python (если опция еще доступна и мы хотим сделать текущую версию интерпретатора запускаемой по умолчанию командой «py» , обязательно выбираем этот пункт; если опция уже недоступна, то ранее мы установили утилиту с другой версией интерпретатора, поэтому нужно выйти из установки и сперва удалить ее из системы);
  • for all users – этот пункт позволяет установить утилиту py launcher для всех пользователей, но лучше отключить этот пункт, если компьютер приходится делить с кем-то еще (каждый пользователь должен установить в свое окружение собственные инструменты разработки).

Нажимаем кнопку «Next» (т.е. «Далее») и совершаем переход к окну дополнительных опций (см. рис. №6 ).

Рис. №6. Выборочная установка Python: необязательные опции.

  • Install Python 3.* for all users – если за компьютером работает несколько пользователей, лучше отключить этот пункт, т.к. пользователи смогут менять общие настройки и зависимости, что рано или поздно приведет к неразберихе и неполадкам (каждый пользователь должен установить в свое окружение собственную версию и сопутствующие библиотеки);
  • Associate files with Python – выбор данной опции позволит Windows связать с Python файлы, имеющие расширение *.py , что сделает возможным запуск скриптов по двойному щелчку мыши (обязательно выбираем);
  • Create shortcuts for installed applications – для запуска приложений будут созданы ярлыки (пусть будут);
  • Add Python to environment variables – путь к интерпретатору Python будет добавлен в переменную окружения PATH (обязательно выбираем);
  • Precomple standard library – провести прекомпиляцию стандартной библиотеки (включаем, не помешает, хотя процесс установки и будет идти чуть дольше);
  • Download debugging simbols и Download debug binaries – эти два пункта связаны с загрузкой компонентов для отладки, их установка нам может не понадобиться, но и не помешает.

После того, как все необходимые опции будут выбраны, указываем путь до папки Python . При этом, если вы работаете за компьютером один, лучше указать более простой путь, например, c:\python\python311 . Если же за компьютером работает несколько пользователей, то устанавливать Python желательно в папку пользователя, предлагаемую системой (у каждого пользователя должна быть своя папка для установки интерпретаторов Python ).

Завершив с выбором опций, можно переходить непосредственно к установке, нажав кнопку «Install» , т.е. «Установить» (см. рис. №7 ).

Рис. №7. Выборочная установка Python: дополнительные опции.

Если все было сделано правильно, то после успешной установки должно появиться окно успешного завершения установки «Setup was successful» (см. рис. №8 ).

Рис. №8. Окно успешного завершения установки.

Закрываем финальное окно установщика Python и приступаем к проверке установки.

Перед загрузкой интерпретатора более ранней версии внимательно ознакомьтесь с информацией на странице загрузки. Убедитесь, что скачиваемая версия интерпретатора подходит для версии вашей операционной системы. Например, интерпретатор версии 3.9.2 не будет корректно работать под управлением ОС Windows 7 и более ранними версиями этой операционной системы. О чем жирным шрифтом предупреждается на странице загрузки.

Запуск интерпретатора и файлов Python

Для начала давайте откроем командную строку ОС Windows , использовав комбинацию клавиш Win+R , и введем в нее команду «cmd» . Результатом выполнения данной команды должно стать появление окна системной консоли (см. рис. №9 ).

Рис. №9. Запуск интерпретатора Python в консоли ОС Windows.

В открывшемся окне консоли введем команду «python» , которая должна запустить интерпретатор. Тот же эффект может быть получен и при использовании команды «py» , которой мы должны быть благодарны установленной утилите Python Launcher (см. рис. №9 ). Данная команда по умолчанию запускает тот интерпретатор Python , вместе с которым она была установлена в систему. Если же требуется запустить интерпретатор определенной версии, следует использовать команду «py -*.*» , указав версию после дефиса. В нашем примере для запуска установленной одиннадцатой версии интерпретатора мы использовали команду «py -3.11» . Список всех установленных в системе версий Python можно получить, выполнив команду «py --list» или аналогичную ей «py -0» . Версия по умолчанию будет выделена в списке звездочкой. В нашем случае, например, мы получили список всего лишь с одной строчкой «-V:3.11 * Python 3.11 (64-bit)» , т.к. других интерпретаторов пока что установлено не было. С другими командами утилиты можно познакомиться в справке, выполнив команду «py --help» .

Стоит добавить, что запустить интерпретатор можно и с помощью указания полного пути к нему. Именно поэтому, если вы работаете за компьютером один, его удобно устанавливать в папку, например, «c:\python\python311» . Тогда запускать его можно будет командой «c:\python\python311\python.exe» (в нашем случае пришлось ввести более длинный путь).

Что касается запуска скриптов Python , то для этого нужно после перечисленных выше команд для запуска интерпретатора указать через пробел либо полный путь к скрипту, либо имя скрипта, если мы находимся в папке с ним (см. рис. №10 ).

Рис. №10. Запуск файлов Python в консоли ОС Windows.

В примере выше мы запускали файл main.py , содержащий всего одну инструкцию «print('Привет, Мир!')» . Его мы создали в каталоге d:\python . Однако запускать его можно не только через консоль, но и обычным для ОС Windows способом, т.е. двойным кликом мыши по ярлыку файла. Здесь главное помнить, что сохранять python -файлы необходимо либо с расширением .py , чтобы система могла определить связанное с файлом приложение, либо с расширением .pyw , которое часто используется в приложениях с графическим интерфейсом для скрытия окна консоли.

Стоит заметить, что в комплекте с интерпретатором поставляется собственная IDE , которую в Windows можно легко найти в меню «Пуск» под именем IDLE (после имени в скобках дополнительно указывается версия Python ). В ней удобно запускать и тестировать короткие фрагменты исходного кода, т.к. в отличие от интерпретатора в консоли, здесь присутствует ряд дополнительных плюсов, например, графическая оболочка и подсветка синтаксиса (см. рис. №11 ).

Рис. №11. Использование встроенной IDE Python.

Перечисленные нами способы запуска скриптов Python , конечно же не единственные. Но большая часть других способов предназначена для более узкоспециализированных задач, поэтому здесь мы их рассматривать не будем.

Вопросы и задания для самоконтроля

1. С какого ресурса следует загружать установочный файл дистрибутива Python ? Почему? Показать решение.

Ответ. Для загрузки установочного файла дистрибутива Python необходимо использовать страницу загрузок официального сайта https://www.python.org . Загрузка из других источников может быть причиной сбоев и появления в системе вирусов.

2. Зачем добавлять путь к интерпретатору Python в переменную окружения PATH ? Показать решение.

Ответ. Это позволит запускать интерпретатор с помощью простой команды «python» , без необходимости указывать полный путь до него.

3. Для чего нужен менеджер пакетов pip ? Показать решение.

Ответ. Менеджер пакетов pip используется для загрузки сторонних пакетов и библиотек, написанных на Python .

4. Для чего стоит установить утилиту Python Launcher ? Показать решение.

Ответ. Данная утилита поможет сценариям (или командной строке) находить и запускать различные версии Python . Кроме того, станет доступна более короткая команда «py» для запуска интерпретатора, с которым она была установлена. Любую другую версию интерпретатора, установленного в системе, можно будет запускать с помощью команды формата «py --*.*» , указав после дефисов вместо звездочек желаемую версию Python .

What does Python Launcher do?

When download python from https://www.python.org/ and install it, I saw 2 apps installed, it is easy to see the purpose of IDLE but I am confused with the purpose of Python Launcher. What does Python Launcher do ? When do I need to it?

Qiulang 邱朗's user avatar

1 Answer 1

For running Python on a mac start at Python's documentation

Python Launcher allows you to run python scripts from the desktop.

The documentation says

To run your script from the Finder you have two options:

Drag it to PythonLauncher

Select PythonLauncher as the default application to open your script (or any .py script) through the finder Info window and double-click it. PythonLauncher has various preferences to control how your script is launched. Option-dragging allows you to change these for one invocation, or use its Preferences menu to change things globally.

From other Stack Exchange questions I think Python Launcher is not part of the python that Apple provides as part of the OS. But as you really should not use that python I have never tried to see.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *