Первые шаги¶
Давайте посмотрим, как создать традиционную программу “Hello World” на Python. Это научит вас писать, сохранять и выполнять программы на Python.
Существует два способа запуска программ на Python: использование интерактивного приглашения интерпретатора и использование файла с текстом программы. Сейчас мы увидим, как пользоваться обоими методами.
Использование командной строки интерпретатора¶
Откройте окно терминала (как было описано в главе Установка ) и запустите интерпретатор Python, введя команду python3 и нажав Enter .
Пользователи Windows могут запустить интерпретатор в командной строке, если установили переменную PATH надлежащим образом. Чтобы открыть командную строку в Windows, зайдите в меню “Пуск” и нажмите “Выполнить. ”. В появившемся диалоговом окне введите “cmd” и нажмите Enter ; теперь у вас будет всё необходимое для начала работы с python в командной строке DOS.
Как только вы запустили python3 , вы должны увидеть >>> в начале строки, где вы можете что-то набирать. Это и называется командной строкой интерпретатора Python.
Теперь введите print(‘Hello World’) и нажмите клавишу Enter . В результате должны появиться слова “Hello World”.
Вот пример того, что вы можете увидеть на экране, если будете использовать компьютер с Mac OS X. Информация о версии Python может отличаться в зависимости от компьютера, но часть, начинающаяся с приглашения (т.е. от >>> и далее) должна быть одинаковой на всех операционных системах.
Обратите внимание, что Python выдаёт результат работы строки немедленно! Вы только что ввели одиночный “оператор” Python. print используется для того, чтобы (что неудивительно[1] ) напечатать любое переданное в него значение. В данном случае мы передали в него текст “Hello World”, который и был напечатан на экране.
Как выйти из командной строки интерпретатора
Если вы используете IDLE или оболочку GNU/Linux или BSD, вы можете выйти из командной строки интерпретатора нажатием Ctrl-D или введя команду exit() (примечание: не забудьте написать скобки, “()”), а затем нажав клавишу Enter . Если вы используете командную строку Windows, нажмите Ctrl-Z , а затем нажмите клавишу Enter .
Выбор редактора¶
Поскольку мы не можем набирать программу в командной строке интерпретатора каждый раз, когда нам нужно что-то запустить, нам понадобится сохранять программы в файлах, чтобы потом иметь возможность запускать их сколько угодно раз.
Прежде чем приступить к написанию программ на Python в файлах, нам нужен редактор для работы с файлами программ. Выбор редактора крайне важен. Подходить к выбору редактора следует так же, как и к выбору личного автомобиля. Хороший редактор поможет вам легко писать программы на Python, делая ваше путешествие более комфортным, а также позволяя быстрее и безопаснее достичь вашей цели.
Одно из самых основных требований – это подсветка синтаксиса, когда разные элементы программы на Python раскрашены так, чтобы вы могли легко видеть вашу программу и ход её выполнения.
Если вы не знаете, с чего начать, я бы порекомендовал воспользоваться программой Komodo Edit, которая доступна для Windows, Mac OS X и GNU/Linux.
Если вы пользуетесь Windows, Не используйте Блокнот – это плохой выбор, поскольку он не обладает функцией подсветки синтаксиса, а также не позволяет автоматически вставлять отступы, что очень важно в нашем случае, как мы увидим позже. Хорошие редакторы, как Komodo Edit, позволяют делать это автоматически.
Опытные программисты, должно быть, уже используют Vim или Emacs. Не стоит даже и говорить, что это два наиболее мощных редактора, и вы только выиграете от их использования для написания программ на Python. Лично я пользуюсь ими обоими для большинства своих программ, и даже написал книгу о Vim. Я настоятельно рекомендую вам решиться и потратить время на изучение Vim или Emacs, поскольку это будет приносить вам пользу долгие годы. Однако, как я уже писал выше, новички могут пока просто остановиться на Komodo Edit и сосредоточиться на изучении Python, а не текстового редактора.
Я повторюсь ещё раз: обязательно выберите подходящий редактор – это сделает написание программ на Python более простым и занимательным.
Для пользователей Vim
Для пользователей Emacs
Использование программных файлов¶
А теперь давайте вернёмся к программированию. Существует такая традиция, что какой бы язык программирования вы ни начинали учить, первой вашей программой должна быть программа “Привет, Мир!”. Это программа, которая просто выводит надпись “Привет, Мир!”. Как сказал Simon Cozens[2], это “традиционное заклинание богов программирования, которое поможет вам лучше изучить язык”.
Запустите выбранный вами редактор, введите следующую программу и сохраните её под именем helloworld.py .
Если вы пользуетесь Komodo Edit, нажмите “Файл” –> “Новый” –> “Новый файл”, введите строку:
В Komodo Edit нажмите “Файл” –> “Сохранить” для сохранения файла.
Куда сохранить файл? В любую папку, расположение которой вы знаете. Если вы не понимаете, что это значит, то создайте новую папку и используйте её для всех ваших программ на Python:
- C:\py в Windows
- /tmp/py в GNU/Linux
- /tmp/py в Mac OS X
Чтобы создать папку, воспользуйтесь командой mkdir в терминале. Например, mkdir /tmp/py .
Не забывайте указывать расширение файла .py . Например, “ file.py ”.
В Komodo Edit нажмите “Инструменты” –> “Запуск команды”, наберите python3 helloworld.py и нажмите “Выполнить”. Вы должны увидеть вывод, показанный на скриншоте ниже.
Но всё-таки лучше редактировать программу в Komodo Edit, а запускать в терминале:
- Откройте терминал, как описано в главе Установка .
- Перейдите в каталог, в котором вы сохранили файл. Например, cd /tmp/py .
- Запустите программу, введя команду python3 helloworld.py .
Вывод программы показан ниже.
Если у вас получился такой же вывод, поздравляю! – вы успешно выполнили вашу первую программу на Python. Вы только что совершили самый сложный шаг в обучении программированию, заключающийся в написании своей первой программы!
Если вы получите сообщение об ошибке, введите вышеуказанную программу в точности так, как показано здесь, и запустите снова. Обратите внимание, что Python различает регистр букв, то есть print – это не то же самое, что Print (обратите внимание на букву p в нижнем регистре в первом случае и на букву P в верхнем регистре во втором). Также убедитесь, что перед первым символом в строке нет пробелов или символов табуляции – позже мы увидим, почему это важно.
Как это работает
Исполнимые программы на Python¶
Это касается только пользователей GNU/Linux и Unix, но пользователям Windows тоже будет полезно об этом знать.
Каждый раз, когда нам нужно запустить программу на Python, нам приходится в явном виде запускать python3 foo.py . Но почему бы нам не запускать её точно так же, как и все другие программы? Этого можно достичь при помощи так называемого hashbang.
Добавьте строку, указанную ниже, в самое начало вашей программы:
Теперь ваша программа должна выглядеть так:
Теперь необходимо установить программе атрибут исполнимости, используя команду chmod , а затем выполнить программу.
Команда chmod здесь используется для изменения режима файла[3] добавлением атрибута исполнимости для всех пользователей в системе[4].
После этого мы можем запускать программу напрямую, потому что наша операционная система запустит /usr/bin/env , который, в свою очередь, найдёт Python 3, а значит, сможет запустить наш файл.
Здесь “ ./ ” обозначает, что программа находится в текущем каталоге.
Ради интереса можете даже переименовать файл в просто “ helloworld ” и запустить его как ./helloworld , и это также сработает, поскольку система знает, что запускать программу нужно интерпретатором, положение которого указано в первой строке файла программы.
Но до сих пор мы могли выполнять свою программу только если знали полный путь к ней. А что, если нам нужно запускать эту программу из любого каталога? Это можно организовать, расположив свою программу в одном из каталогов, перечисленных в переменной окружения PATH .
При попытке запуска какой-либо программы система ищет её в каталогах, перечисленных в переменной окружения PATH , и запускает. Таким образом, мы можем сделать программу доступной из любого места, скопировав её в один из каталогов, перечисленных в PATH .
Мы можем вывести на экран значение переменной PATH при помощи команды echo , добавив перед именем переменной символ $ , чтобы указать оболочке, что мы хотим получить значение этой переменной. Мы видим, что /home/swaroop/bin – один из каталогов в переменной PATH, где swaroop – это имя пользователя, которое я использую в своей системе. В вашей системе, скорее всего, будет аналогичный каталог для вашего пользователя.
Вы также можете добавить какой-либо каталог к переменной PATH – это можно сделать, выполнив PATH=$PATH:/home/swaroop/mydir , где ‘/home/swaroop/mydir’ – это каталог, который я хочу добавить к переменной PATH .
Этот метод полезен для написания сценариев, которые будут доступны для запуска в любой момент из любого места. По сути, это равносильно созданию собственных команд, как cd или любой другой, которые часто используются в терминале GNU/Linux или приглашении DOS.
Когда речь идёт о Python, слова “программа” или “сценарий (скрипт)” обозначают одно и то же.
Получение помощи¶
Для быстрого получения информации о любой функции или операторе Python служит встроенная функция help . Это особенно удобно при использовании командной строки интерпретатора. К примеру, выполните help(print) – это покажет справку по функции print , которая используется для вывода на экран.
Для выхода из справки нажмите q .
Аналогичным образом можно получить информацию почти о чём угодно в Python. При помощи функции help() можно даже получить описание самой функции help !
Если вас интересует информация об операторах, как например, return , их необходимо указывать в кавычках (например, help(‘return’) ), чтобы Python понял, чего мы хотим.
Резюме¶
Теперь вы умеете с лёгкостью писать, сохранять и запускать программы на Python.
И поскольку сейчас вы уже используете Python, давайте узнаем больше о его основных принципах.
1. Command line and environment¶
The CPython interpreter scans the command line and the environment for various settings.
CPython implementation detail: Other implementations’ command line schemes may differ. See Alternate Implementations for further resources.
1.1. Command line¶
When invoking Python, you may specify any of these options:
The most common use case is, of course, a simple invocation of a script:
1.1.1. Interface options¶
The interpreter interface resembles that of the UNIX shell, but provides some additional methods of invocation:
When called with standard input connected to a tty device, it prompts for commands and executes them until an EOF (an end-of-file character, you can produce that with Ctrl — D on UNIX or Ctrl — Z, Enter on Windows) is read.
When called with a file name argument or with a file as standard input, it reads and executes a script from that file.
When called with a directory name argument, it reads and executes an appropriately named script from that directory.
When called with -c command , it executes the Python statement(s) given as command. Here command may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements!
When called with -m module-name , the given module is located on the Python module path and executed as a script.
In non-interactive mode, the entire input is parsed before it is executed.
An interface option terminates the list of options consumed by the interpreter, all consecutive arguments will end up in sys.argv – note that the first element, subscript zero ( sys.argv[0] ), is a string reflecting the program’s source.
Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.
If this option is given, the first element of sys.argv will be "-c" and the current directory will be added to the start of sys.path (allowing modules in that directory to be imported as top level modules).
Raises an auditing event cpython.run_command with argument command .
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you must not give a file extension ( .py ). The module name should be a valid absolute Python module name, but the implementation may not always enforce this (e.g. it may allow you to use a name that includes a hyphen).
Package names (including namespace packages) are also permitted. When a package name is supplied instead of a normal module, the interpreter will execute <pkg>.__main__ as the main module. This behaviour is deliberately similar to the handling of directories and zipfiles that are passed to the interpreter as the script argument.
This option cannot be used with built-in modules and extension modules written in C, since they do not have Python module files. However, it can still be used for precompiled modules, even if the original source file is not available.
If this option is given, the first element of sys.argv will be the full path to the module file (while the module file is being located, the first element will be set to "-m" ). As with the -c option, the current directory will be added to the start of sys.path .
-I option can be used to run the script in isolated mode where sys.path contains neither the current directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.
Many standard library modules contain code that is invoked on their execution as a script. An example is the timeit module:
Raises an auditing event cpython.run_module with argument module-name .
Equivalent functionality directly available to Python code
PEP 338 – Executing modules as scripts
Changed in version 3.1: Supply the package name to run a __main__ submodule.
Changed in version 3.4: namespace packages are also supported
Read commands from standard input ( sys.stdin ). If standard input is a terminal, -i is implied.
If this option is given, the first element of sys.argv will be "-" and the current directory will be added to the start of sys.path .
Raises an auditing event cpython.run_stdin with no arguments.
Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to either a Python file, a directory containing a __main__.py file, or a zipfile containing a __main__.py file.
If this option is given, the first element of sys.argv will be the script name as given on the command line.
If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path , and the file is executed as the __main__ module.
If the script name refers to a directory or zipfile, the script name is added to the start of sys.path and the __main__.py file in that location is executed as the __main__ module.
-I option can be used to run the script in isolated mode where sys.path contains neither the script’s directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.
Raises an auditing event cpython.run_file with argument filename .
Equivalent functionality directly available to Python code
If no interface option is given, -i is implied, sys.argv[0] is an empty string ( "" ) and the current directory will be added to the start of sys.path . Also, tab-completion and history editing is automatically enabled, if available on your platform (see Readline configuration ).
Changed in version 3.4: Automatic enabling of tab-completion and history editing.
1.1.2. Generic options¶
Print a short description of all command line options and corresponding environment variables and exit.
Print a short description of Python-specific environment variables and exit.
New in version 3.11.
Print a description of implementation-specific -X options and exit.
New in version 3.11.
Print complete usage information and exit.
New in version 3.11.
Print the Python version number and exit. Example output could be:
When given twice, print more information about the build, like:
New in version 3.6: The -VV option.
1.1.3. Miscellaneous options¶
Issue a warning when comparing bytes or bytearray with str or bytes with int . Issue an error when the option is given twice ( -bb ).
Changed in version 3.5: Affects comparisons of bytes with int .
If given, Python won’t try to write .pyc files on the import of source modules. See also PYTHONDONTWRITEBYTECODE .
Control the validation behavior of hash-based .pyc files. See Cached bytecode invalidation . When set to default , checked and unchecked hash-based bytecode cache files are validated according to their default semantics. When set to always , all hash-based .pyc files, whether checked or unchecked, are validated against their corresponding source file. When set to never , hash-based .pyc files are not validated against their corresponding source files.
The semantics of timestamp-based .pyc files are unaffected by this option.
Turn on parser debugging output (for expert only, depending on compilation options). See also PYTHONDEBUG .
Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME , that might be set.
See also the -P and -I (isolated) options.
When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal. The PYTHONSTARTUP file is not read.
This can be useful to inspect global variables or a stack trace when a script raises an exception. See also PYTHONINSPECT .
Run Python in isolated mode. This also implies -E , -P and -s options.
In isolated mode sys.path contains neither the script’s directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too. Further restrictions may be imposed to prevent the user from injecting malicious code.
New in version 3.4.
Remove assert statements and any code conditional on the value of __debug__ . Augment the filename for compiled ( bytecode ) files by adding .opt-1 before the .pyc extension (see PEP 488). See also PYTHONOPTIMIZE .
Changed in version 3.5: Modify .pyc filenames according to PEP 488.
Do -O and also discard docstrings. Augment the filename for compiled ( bytecode ) files by adding .opt-2 before the .pyc extension (see PEP 488).
Changed in version 3.5: Modify .pyc filenames according to PEP 488.
Don’t prepend a potentially unsafe path to sys.path :
python -m module command line: Don’t prepend the current working directory.
python script.py command line: Don’t prepend the script’s directory. If it’s a symbolic link, resolve symbolic links.
python -c code and python (REPL) command lines: Don’t prepend an empty string, which means the current working directory.
See also the PYTHONSAFEPATH environment variable, and -E and -I (isolated) options.
New in version 3.11.
Don’t display the copyright and version messages even in interactive mode.
New in version 3.2.
Turn on hash randomization. This option only has an effect if the PYTHONHASHSEED environment variable is set to 0 , since hash randomization is enabled by default.
On previous versions of Python, this option turns on hash randomization, so that the __hash__() values of str and bytes objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.
Hash randomization is intended to provide protection against a denial-of-service caused by carefully chosen inputs that exploit the worst case performance of a dict construction, O(n 2 ) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.
PYTHONHASHSEED allows you to set a fixed value for the hash seed secret.
Changed in version 3.7: The option is no longer ignored.
New in version 3.2.3.
PEP 370 – Per user site-packages directory
Disable the import of the module site and the site-dependent manipulations of sys.path that it entails. Also disable these manipulations if site is explicitly imported later (call site.main() if you want them to be triggered).
Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream.
Changed in version 3.7: The text layer of the stdout and stderr streams now is unbuffered.
Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. When given twice ( -vv ), print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit.
Changed in version 3.10: The site module reports the site-specific paths and .pth files being processed.
Warning control. Python’s warning machinery by default prints warning messages to sys.stderr .
The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):
The action names can be abbreviated as desired and the interpreter will resolve them to the appropriate action name. For example, -Wi is the same as -Wignore .
The full form of argument is:
Empty fields match all values; trailing empty fields may be omitted. For example -W ignore::DeprecationWarning ignores all DeprecationWarning warnings.
The action field is as explained above but only applies to warnings that match the remaining fields.
The message field must match the whole warning message; this match is case-insensitive.
The category field matches the warning category (ex: DeprecationWarning ). This must be a class name; the match test whether the actual warning category of the message is a subclass of the specified warning category.
The module field matches the (fully qualified) module name; this match is case-sensitive.
The lineno field matches the line number, where zero matches all line numbers and is thus equivalent to an omitted line number.
Multiple -W options can be given; when a warning matches more than one option, the action for the last matching option is performed. Invalid -W options are ignored (though, a warning message is printed about invalid options when the first warning is issued).
Warnings can also be controlled using the PYTHONWARNINGS environment variable and from within a Python program using the warnings module. For example, the warnings.filterwarnings() function can be used to use a regular expression on the warning message.
Skip the first line of the source, allowing use of non-Unix forms of #!cmd . This is intended for a DOS specific hack only.
Reserved for various implementation-specific options. CPython currently defines the following possible values:
-X faulthandler to enable faulthandler ;
-X showrefcount to output the total reference count and number of used memory blocks when the program finishes or after each statement in the interactive interpreter. This only works on debug builds .
-X tracemalloc to start tracing Python memory allocations using the tracemalloc module. By default, only the most recent frame is stored in a traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a traceback limit of NFRAME frames. See the tracemalloc.start() for more information.
-X importtime to show how long each import takes. It shows module name, cumulative time (including nested imports) and self time (excluding nested imports). Note that its output may be broken in multi-threaded application. Typical usage is python3 -X importtime -c ‘import asyncio’ . See also PYTHONPROFILEIMPORTTIME .
-X dev : enable Python Development Mode , introducing additional runtime checks that are too expensive to be enabled by default.
-X utf8 enables the Python UTF-8 Mode . -X utf8=0 explicitly disables Python UTF-8 Mode (even when it would otherwise activate automatically).
-X pycache_prefix=PATH enables writing .pyc files to a parallel tree rooted at the given directory instead of to the code tree. See also PYTHONPYCACHEPREFIX .
-X warn_default_encoding issues a EncodingWarning when the locale-specific default encoding is used for opening files. See also PYTHONWARNDEFAULTENCODING .
-X no_debug_ranges disables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks. See also PYTHONNODEBUGRANGES .
-X frozen_modules determines whether or not frozen modules are ignored by the import machinery. A value of “on” means they get imported and “off” means they are ignored. The default is “on” if this is an installed Python (the normal case). If it’s under development (running from the source tree) then the default is “off”. Note that the “importlib_bootstrap” and “importlib_bootstrap_external” frozen modules are always used, even if this flag is set to “off”.
It also allows passing arbitrary values and retrieving them through the sys._xoptions dictionary.
Changed in version 3.2: The -X option was added.
New in version 3.3: The -X faulthandler option.
New in version 3.4: The -X showrefcount and -X tracemalloc options.
New in version 3.6: The -X showalloccount option.
New in version 3.7: The -X importtime , -X dev and -X utf8 options.
New in version 3.8: The -X pycache_prefix option. The -X dev option now logs close() exceptions in io.IOBase destructor.
Changed in version 3.9: Using -X dev option, check encoding and errors arguments on string encoding and decoding operations.
The -X showalloccount option has been removed.
New in version 3.10: The -X warn_default_encoding option.
Deprecated since version 3.9, removed in version 3.10: The -X oldparser option.
New in version 3.11: The -X no_debug_ranges option.
New in version 3.11: The -X frozen_modules option.
New in version 3.11: The -X int_max_str_digits option.
1.1.4. Options you shouldn’t use¶
Reserved for use by Jython.
1.2. Environment variables¶
These environment variables influence Python’s behavior, they are processed before the command-line switches other than -E or -I. It is customary that command-line switches override environmental variables where there is a conflict.
Change the location of the standard Python libraries. By default, the libraries are searched in prefix /lib/python version and exec_prefix /lib/python version , where prefix and exec_prefix are installation-dependent directories, both defaulting to /usr/local .
When PYTHONHOME is set to a single directory, its value replaces both prefix and exec_prefix . To specify different values for these, set PYTHONHOME to prefix : exec_prefix .
Augment the default search path for module files. The format is the same as the shell’s PATH : one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.
In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.
The default search path is installation dependent, but generally begins with prefix /lib/python version (see PYTHONHOME above). It is always appended to PYTHONPATH .
An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options . The search path can be manipulated from within a Python program as the variable sys.path .
If this is set to a non-empty string, don’t prepend a potentially unsafe path to sys.path : see the -P option for details.
New in version 3.11.
If this is set to a non-empty string, it overrides the sys.platlibdir value.
New in version 3.9.
If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in interactive mode. The file is executed in the same namespace where interactive commands are executed so that objects defined or imported in it can be used without qualification in the interactive session. You can also change the prompts sys.ps1 and sys.ps2 and the hook sys.__interactivehook__ in this file.
Raises an auditing event cpython.run_startup with the filename as the argument when called on startup.
If this is set to a non-empty string it is equivalent to specifying the -O option. If set to an integer, it is equivalent to specifying -O multiple times.
If this is set, it names a callable using dotted-path notation. The module containing the callable will be imported and then the callable will be run by the default implementation of sys.breakpointhook() which itself is called by built-in breakpoint() . If not set, or set to the empty string, it is equivalent to the value “pdb.set_trace”. Setting this to the string “0” causes the default implementation of sys.breakpointhook() to do nothing but return immediately.
New in version 3.7.
If this is set to a non-empty string it is equivalent to specifying the -d option. If set to an integer, it is equivalent to specifying -d multiple times.
If this is set to a non-empty string it is equivalent to specifying the -i option.
This variable can also be modified by Python code using os.environ to force inspect mode on program termination.
If this is set to a non-empty string it is equivalent to specifying the -u option.
If this is set to a non-empty string it is equivalent to specifying the -v option. If set to an integer, it is equivalent to specifying -v multiple times.
If this is set, Python ignores case in import statements. This only works on Windows and macOS.
If this is set to a non-empty string, Python won’t try to write .pyc files on the import of source modules. This is equivalent to specifying the -B option.
If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in __pycache__ directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.
New in version 3.8.
If this variable is not set or set to random , a random value is used to seed the hashes of str and bytes objects.
If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.
Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.
The integer must be a decimal number in the range [0,4294967295]. Specifying the value 0 will disable hash randomization.
New in version 3.2.3.
If this variable is set to an integer, it is used to configure the interpreter’s global integer string conversion length limitation .
New in version 3.11.
If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax encodingname:errorhandler . Both the encodingname and the :errorhandler parts are optional and have the same meaning as in str.encode() .
For stderr, the :errorhandler part is ignored; the handler will always be ‘backslashreplace’ .
Changed in version 3.4: The encodingname part is now optional.
Changed in version 3.6: On Windows, the encoding specified by this variable is ignored for interactive console buffers unless PYTHONLEGACYWINDOWSSTDIO is also specified. Files and pipes redirected through the standard streams are not affected.
If this is set, Python won’t add the user site-packages directory to sys.path .
PEP 370 – Per user site-packages directory
Defines the user base directory , which is used to compute the path of the user site-packages directory and Distutils installation paths for python setup.py install —user .
PEP 370 – Per user site-packages directory
If this environment variable is set, sys.argv[0] will be set to its value instead of the value got through the C runtime. Only works on macOS.
This is equivalent to the -W option. If set to a comma separated string, it is equivalent to specifying -W multiple times, with filters later in the list taking precedence over those earlier in the list.
The simplest settings apply a particular action unconditionally to all warnings emitted by a process (even those that are otherwise ignored by default):
If this environment variable is set to a non-empty string, faulthandler.enable() is called at startup: install a handler for SIGSEGV , SIGFPE , SIGABRT , SIGBUS and SIGILL signals to dump the Python traceback. This is equivalent to -X faulthandler option.
New in version 3.3.
If this environment variable is set to a non-empty string, start tracing Python memory allocations using the tracemalloc module. The value of the variable is the maximum number of frames stored in a traceback of a trace. For example, PYTHONTRACEMALLOC=1 stores only the most recent frame. See the tracemalloc.start() for more information.
New in version 3.4.
If this environment variable is set to a non-empty string, Python will show how long each import takes. This is exactly equivalent to setting -X importtime on the command line.
New in version 3.7.
If this environment variable is set to a non-empty string, enable the debug mode of the asyncio module.
New in version 3.4.
Set the Python memory allocators and/or install debug hooks.
Set the family of memory allocators used by Python:
malloc : use the malloc() function of the C library for all domains ( PYMEM_DOMAIN_RAW , PYMEM_DOMAIN_MEM , PYMEM_DOMAIN_OBJ ).
pymalloc : use the pymalloc allocator for PYMEM_DOMAIN_MEM and PYMEM_DOMAIN_OBJ domains and use the malloc() function for the PYMEM_DOMAIN_RAW domain.
debug : install debug hooks on top of the default memory allocators .
malloc_debug : same as malloc but also install debug hooks.
pymalloc_debug : same as pymalloc but also install debug hooks.
Changed in version 3.7: Added the "default" allocator.
New in version 3.6.
If set to a non-empty string, Python will print statistics of the pymalloc memory allocator every time a new pymalloc object arena is created, and on shutdown.
This variable is ignored if the PYTHONMALLOC environment variable is used to force the malloc() allocator of the C library, or if Python is configured without pymalloc support.
Changed in version 3.6: This variable can now also be used on Python compiled in release mode. It now has no effect if set to an empty string.
If set to a non-empty string, the default filesystem encoding and error handler mode will revert to their pre-3.6 values of ‘mbcs’ and ‘replace’, respectively. Otherwise, the new defaults ‘utf-8’ and ‘surrogatepass’ are used.
This may also be enabled at runtime with sys._enablelegacywindowsfsencoding() .
New in version 3.6: See PEP 529 for more details.
If set to a non-empty string, does not use the new console reader and writer. This means that Unicode characters will be encoded according to the active console code page, rather than using utf-8.
This variable is ignored if the standard streams are redirected (to files or pipes) rather than referring to console buffers.
New in version 3.6.
If set to the value 0 , causes the main Python command line application to skip coercing the legacy ASCII-based C and POSIX locales to a more capable UTF-8 based alternative.
If this variable is not set (or is set to a value other than 0 ), the LC_ALL locale override environment variable is also not set, and the current locale reported for the LC_CTYPE category is either the default C locale, or else the explicitly ASCII-based POSIX locale, then the Python CLI will attempt to configure the following locales for the LC_CTYPE category in the order listed before loading the interpreter runtime:
If setting one of these locale categories succeeds, then the LC_CTYPE environment variable will also be set accordingly in the current process environment before the Python runtime is initialized. This ensures that in addition to being seen by both the interpreter itself and other locale-aware components running in the same process (such as the GNU readline library), the updated setting is also seen in subprocesses (regardless of whether or not those processes are running a Python interpreter), as well as in operations that query the environment rather than the current C locale (such as Python’s own locale.getdefaultlocale() ).
Configuring one of these locales (either explicitly or via the above implicit locale coercion) automatically enables the surrogateescape error handler for sys.stdin and sys.stdout ( sys.stderr continues to use backslashreplace as it does in any other locale). This stream handling behavior can be overridden using PYTHONIOENCODING as usual.
For debugging purposes, setting PYTHONCOERCECLOCALE=warn will cause Python to emit warning messages on stderr if either the locale coercion activates, or else if a locale that would have triggered coercion is still active when the Python runtime is initialized.
Also note that even when locale coercion is disabled, or when it fails to find a suitable target locale, PYTHONUTF8 will still activate by default in legacy ASCII-based locales. Both features must be disabled in order to force the interpreter to use ASCII instead of UTF-8 for system interfaces.
New in version 3.7: See PEP 538 for more details.
If this environment variable is set to a non-empty string, enable Python Development Mode , introducing additional runtime checks that are too expensive to be enabled by default.
New in version 3.7.
If set to 1 , enable the Python UTF-8 Mode .
If set to 0 , disable the Python UTF-8 Mode .
Setting any other non-empty string causes an error during interpreter initialisation.
New in version 3.7.
If this environment variable is set to a non-empty string, issue a EncodingWarning when the locale-specific default encoding is used.
New in version 3.10.
If this variable is set, it disables the inclusion of the tables mapping extra location information (end line, start column offset and end column offset) to every instruction in code objects. This is useful when smaller code objects and pyc files are desired as well as suppressing the extra visual location indicators when the interpreter displays tracebacks.
New in version 3.11.
1.2.1. Debug-mode variables¶
If set, Python will print threading debug info into stdout.
Deprecated since version 3.10, will be removed in version 3.12.
If set, Python will dump objects and reference counts still alive after shutting down the interpreter.
Need Python configured with the —with-trace-refs build option.
If set, Python will dump objects and reference counts still alive after shutting down the interpreter into a file called FILENAME.
Как запустить код на Python?
В одной из предыдущих статей рассказывалось, как установить Python на операционные системы Windows и Linux. Этот материал посвящён запуску и первоначальной работе с «Пайтоном». Будут рассмотрены два основных способа запустить его: интерпретация строк исходного кода, вводимого с помощью клавиатуры (интерактивный режим), а также исполнение файлов с кодом (пакетный режим). Отдельный разговор пойдёт про особенности запуска программы и кода Python в Windows и Linux. Материал предназначен для начинающих.
Язык программирования «Пайтон» является интерпретируемым. В этом контексте можно сказать, что кроме самой программы, пользователю ещё нужен и специальный инструмент, обеспечивающий её запуск.
Вернувшись на несколько шагов назад, следует напомнить, что языки программирования бывают: — компилируемыми. С высокоуровневого языка код переводится в машинный с учётом конкретной платформы. Далее распространение происходит в качестве бинарного файла (чаще всего). Запускаться такая программа может без дополнительных программных средств (необходимые библиотеки следует оставить за рамками данного обсуждения). Наиболее распространёнными компилируемыми языками программирования являются C++ и C; — интерпретируемыми. В этом случае выполнение программы осуществляется интерпретатором с последующим распространением в виде исходного кода. Самый популярный язык из этой категории — общеизвестный «Питон» или «Пайтон» (Python).
Запуск кода Python: интерактивный режим в CMD
Python способен функционировать в 2-х режимах: — пакетный; — интерактивный.
Пользователям Windows можно проверить интерактивный режим работы с кодом с помощью командной строки (CMD, command line interpreter — интерпретатор командной строки). Открыв командную строку, следует набрать следующую команду:
Итогом станет запуск «Пайтона» в интерактивном режиме. Далее программа станет ждать ввод последующих команд (commands) от пользователя. Вот, как это может выглядеть:
Программа готова к запуску кода. Прекрасный пример — использование классического приветствия, в которое можно внести минимальные изменения: print(«Привет, OTUS!») . В таком коде внутри скобок пользователь может написать и другие фразы.
Зелёная стрелка — это команда, красная — результат. По коду видно, что программа отработала без затруднений.
Но возможности «Пайтона» выходят далеко за пределы стандартного «хэллоуворлда». Его без проблем можно использовать и в качестве калькулятора, выполняя вычисления.
А при подключении соответствующих библиотек, эти вычисления могут быть весьма сложны и мало уступят специализированным пакетам Matlab.
Далее следует выйти из интерактивного режима, набрав простую команду exit() .
Запуск Python: интерактивный режим в IDLE
При установке языка программирования Python в комплекте с ним идёт IDLE. Это интегрированная среда разработки, подобная по своей сути интерпретатору, который запущен интерактивно. Отличие — расширенный набор возможностей. Среди таких возможностей: — отладка; — просмотр объектов; — подсветка синтаксиса и прочие.
Чтобы запустить IDLE в Windows, следует перейти в меню «Пуск», где можно без проблем найти нужный инструмент:
После запуска пользователь увидит следующую среду:
В ней можно тоже полноценно работать с кодом.
Если же разговор идёт про Linux, то в этой операционной системе IDLE-оболочка по дефолту отсутствует, поэтому придётся её инсталлировать. Для Python 3.4 это будет выглядеть так:
Итогом станет загрузка IDLE на персональный компьютер пользователя. Запустить оболочку тоже несложно:
Выглядеть среда будет следующим образом:
Как запустить приложение Python в пакетном режиме?
Бывает, у пользователя уже есть Python-файлы с расширением .py. Их тоже можно запустить через командную строку. Для этого вызывается интерпретатор Python, а в качестве аргумента передаётся соответствующий файл.
Давайте продемонстрируем это на практике. Откройте блокнот и поместите туда уже знакомые строки кода:
Сохраните файл под именем example.py. Пусть он будет сохранен на диске C (можно выбрать и другую директорию на усмотрение пользователя).
Теперь откройте командную строку, перейдите в соответствующую директорию и можете запускать файл:
Красная стрелка — переход в нужную директорию, синяя — команда для запуска «Питона» в пакетном режиме, зелёная — итоговый результат. Всё просто.
Делаем выводы:
- Чтобы запустить «Пайтон» в интерактивном режиме, надо набрать в командной строке (cmd) имя интерпретатора — python (иногда это python3) либо запустить интегрированную среду разработки IDLE.
- Чтобы выполнить запуск в пакетном режиме, надо ввести в командной строке имя интерпретатора, плюс имя файла. В нашем случае это python.example.py .
Для закрепления материала настоятельно рекомендуется повторить всё вышеописанное самостоятельно.
Execute a Command Prompt Command from Python
Need to execute a Command Prompt command from Python?
If so, depending on your needs, you may use either of the two methods below to a execute a Command Prompt command from Python:
(1) CMD /K – execute a command and then remain:
(2) CMD /C – execute a command and then terminate:
Still not sure how to apply the above methods in Python?
Let’s then review few examples to better understand how to execute a Command Prompt command from Python.
Methods to Execute a Command Prompt Command from Python
Method 1 (CMD /K): Execute a command and then remain
To see how to apply the first method in practice, let’s review a simple example where we’ll execute a simple command in Python to:
- Display the current date in the Command Prompt
- The Command Prompt will remain opened following the execution of the command
You may then apply the following code in Python to achieve the above goals:
Once you run the code in Python, you’ll get the date in the command prompt:
Now what if you want to execute multiple command prompt commands from Python?
If that’s the case, you can insert the ‘&’ symbol (or other symbols, such as ‘&&’ for instance) in between the commands.
For example, what if you want to display all the characters in the command prompt in green and display the current date?
You can then use the following syntax in Python:
You’ll now see the current date displayed in green:
Note that for more complex commands, you may find it useful to run a batch file from Python.
Method 2 (CMD /C): Execute a command and then terminate
For this method, you can execute the same commands as reviewed under the first method, only this time the Command Prompt will be closed following the execution of the commands.
For example, you may apply the following code in Python to change the color of all characters to green:
In this case, the command will still get executed, but you may not be able to see it on your monitor.
In general, you can get a useful legend with further information by typing the command below in the Command Prompt: