События и сигналы в pyqt5

Priority and Rules

Priority of configuration parameters, highest to lowest:

  • PyConfig
  • PyPreConfig
  • Configuration files
  • Command line options
  • Environment variables
  • Global configuration variables

Priority of warning options, highest to lowest:

  • PyConfig.warnoptions
  • PySys_AddWarnOption()
  • PyConfig.bytes_warning (add "error::BytesWarning" filter if
    greater than 1, add "default::BytesWarning filter if equals to 1)
  • -W opt command line argument
  • PYTHONWARNINGS environment variable
  • PyConfig.dev_mode (add "default" filter)

Rules on PyConfig parameters:

  • If isolated is non-zero, use_environment and
    user_site_directory are set to 0.
  • If dev_mode is non-zero, allocator is set to "debug",
    faulthandler is set to 1, and "default" filter is added to
    warnoptions. But the PYTHONMALLOC environment variable has the
    priority over dev_mode to set the memory allocator.
  • If base_prefix is not set, it inherits prefix value.
  • If base_exec_prefix is not set, it inherits exec_prefix value.
  • If the python._pth configuration file is present, isolated is
    set to 1 and site_import is set to 0; but site_import is set
    to 1 if python._pth contains import site.

Rules on PyConfig and PyPreConfig parameters:

1. sys.stdin

Python’s module provides us with all three file objects for stdin, stdout, and stderr. For the input file object, we use . This is similar to a file, where you can open and close it, just like any other file.

Let us understand this through a basic example:

import sys

stdin_fileno = sys.stdin

# Keeps reading from stdin and quits only if the word 'exit' is there
# This loop, by default does not terminate, since stdin is open
for line in stdin_fileno:
    # Remove trailing newline characters using strip()
    if 'exit' == line.strip():
        print('Found exit. Terminating the program')
        exit(0)
    else:
        print('Message from sys.stdin: ---> {} <---'.format(line))

Output

Hi
Message from sys.stdin: ---> Hi
 <---
Hello from AskPython
Message from sys.stdin: ---> Hello from AskPython
 <---
exit
Found exit. Terminating the program

The above snippet keeps reading input from and prints the message to the Console () until the word is encountered.

NOTE: We do not normally close the default file object, although it is allowed. So is valid Python code.

Now that we know a little bit about , let us move to .

Более длинный ответ

Вот полная, легко воспроизводимая демонстрация, используя два метода: встроенную функцию, (используйте в Python 2) и . Данные немодифицированы, поэтому обработка является нерабочей.

Для начала давайте создадим файл для ввода:

И используя код, который мы уже видели, мы можем проверить, что мы создали файл:

Вот помощь по из Python 3:

Встроенная функция, ( в Python 2)

Встроенный функции читается со стандартного ввода до новой строки, которая разделяется (дополняя , которая по умолчанию добавляет новую ). Это происходит до тех пор, пока не получит EOF (End Of File), после чего он вызывает .

Таким образом, вот как вы можете использовать в Python 3 (или в Python 2) для чтения из stdin – поэтому мы создаем модуль Python, который мы вызываем stdindemo.py:

И давайте напечатаем его обратно, чтобы убедиться, что это так, как мы ожидаем:

Опять же, считывается до новой строки и, по существу, удаляет ее из строки. добавляет новую строку. Поэтому, пока они оба изменяют ввод, их модификации отменяются. (Таким образом, они по сути друг друга дополняют друг друга).

И когда получает символ конца файла, он вызывает EOFError, который мы игнорируем, а затем выходим из программы.

И в Linux / Unix мы можем подключаться от cat:

Или мы можем просто перенаправить файл из stdin:

Мы также можем выполнить модуль как скрипт:

Вот помощь на встроенном от Python 3:

sys.path¶

The sys module’s path value is a list of strings that specifies the search path for modules. Basically this tells Python what locations to look in when it tries to import a module. According to the Python documentation, sys.path is initialized from an environment variable called PYTHONPATH, plus an installation-dependent default. Let’s give it a try:

>>> import sys
>>> print(sys.path)

This can be very useful for debugging why a module isn’t getting imported. You can also modify the path. Because it’s a list, we can add or delete paths from it. Here’s how to add a path:

>>> sys.path.append("/path/to/my/module")

Handle backward compatibility in the parser

The parser is modified to support multiple versions of the Python
language (grammar).

The current Python parser cannot be easily modified for that. AST and
grammar are hardcoded to a single Python version.

In Python 3.8, compile() has an undocumented
_feature_version to not consider async and await as
keywords.

The latest major language backward incompatible change was Python 3.7
which made async and await real keywords. It seems like Twisted
was the only affected project, and Twisted had a single affected
function (it used a parameter called async).

Handling backward compatibility in the parser seems quite complex, not
only to modify the parser, but also for developers who have to check
which version of the Python language is used.

Add pythonXY_syntax to the __future__ module. It would enable
backward compatibility with Python X.Y syntax, but only for the current
file.

With this option, there is no need to change
sys.implementation.cache_tag to use a different .pyc filename,
since the parser will always produce the same output for the same input
(except for the optimization level).

For example:

from __future__ import python35_syntax

async = 1
await = 2

Installation paths¶

Python uses an installation scheme that differs depending on the platform and on
the installation options. These schemes are stored in under
unique identifiers based on the value returned by .

Every new component that is installed using or a
Distutils-based system will follow the same scheme to copy its file in the right
places.

Python currently supports seven schemes:

  • posix_prefix: scheme for POSIX platforms like Linux or Mac OS X. This is
    the default scheme used when Python or a component is installed.

  • posix_home: scheme for POSIX platforms used when a home option is used
    upon installation. This scheme is used when a component is installed through
    Distutils with a specific home prefix.

  • posix_user: scheme for POSIX platforms used when a component is installed
    through Distutils and the user option is used. This scheme defines paths
    located under the user home directory.

  • nt: scheme for NT platforms like Windows.

  • nt_user: scheme for NT platforms, when the user option is used.

Each scheme is itself composed of a series of paths and each path has a unique
identifier. Python currently uses eight paths:

  • stdlib: directory containing the standard Python library files that are not
    platform-specific.

  • platstdlib: directory containing the standard Python library files that are
    platform-specific.

  • platlib: directory for site-specific, platform-specific files.

  • purelib: directory for site-specific, non-platform-specific files.

  • include: directory for non-platform-specific header files.

  • platinclude: directory for platform-specific header files.

  • scripts: directory for script files.

  • data: directory for data files.

provides some functions to determine these paths.

()

Return a tuple containing all schemes currently supported in
.

()

Return a tuple containing all path names currently supported in
.

(name, scheme, vars, expand)

Return an installation path corresponding to the path name, from the
install scheme named scheme.

name has to be a value from the list returned by .

stores installation paths corresponding to each path name,
for each platform, with variables to be expanded. For instance the stdlib
path for the nt scheme is: .

will use the variables returned by
to expand the path. All variables have default values for each platform so
one may call this function and get the default value.

If scheme is provided, it must be a value from the list returned by
. Otherwise, the default scheme for the current
platform is used.

If vars is provided, it must be a dictionary of variables that will update
the dictionary return by .

If expand is set to , the path will not be expanded using the
variables.

If name is not found, return .

Micro releases

Sometimes, incompatible changes are introduced in micro releases
(micro in major.minor.micro) to fix bugs or security
vulnerabilities. Examples include:

  • Python 3.7.2, compileall and py_compile module: the
    invalidation_mode parameter’s default value is updated to None;
    the SOURCE_DATE_EPOCH environment variable no longer
    overrides the value of the invalidation_mode argument, and
    determines its default value instead.
  • Python 3.7.1, xml modules: the SAX parser no longer processes
    general external entities by default to increase security by default.
  • Python 3.5.2, os.urandom(): on Linux, if the getrandom()
    syscall blocks (the urandom entropy pool is not initialized yet), fall
    back on reading /dev/urandom.
  • Python 3.5.1, sys.setrecursionlimit(): a RecursionError
    exception is now raised if the new limit is too low at the current
    recursion depth.
  • Python 3.4.4, ssl.create_default_context(): RC4 was dropped from
    the default cipher string.
  • Python 3.4.3, http.client: HTTPSConnection now performs all
    the necessary certificate and hostname checks by default.
  • Python 3.4.2, email.message: EmailMessage.is_attachment() is
    now a method instead of a property, for consistency with
    Message.is_multipart().
  • Python 3.4.1, os.makedirs(name, mode=0o777, exist_ok=False):
    Before Python 3.4.1, if exist_ok was True and the directory
    existed, makedirs() would still raise an error if mode did not
    match the mode of the existing directory. Since this behavior was
    impossible to implement safely, it was removed in Python 3.4.1
    (bpo-21082).

Examples of changes made in micro releases which are not backward
incompatible:

  • ssl.OP_NO_TLSv1_3 constant was added to 2.7.15, 3.6.3 and 3.7.0
    for backwards compatibility with OpenSSL 1.0.2.
  • typing.AsyncContextManager was added to Python 3.6.2.
  • The zipfile module accepts a path-like object since Python 3.6.2.
  • loop.create_future() was added to Python 3.5.2 in the asyncio
    module.

No backward compatibility code is needed for these kinds of changes.

Python 3.7 API

Python 3.7 has 4 functions in its C API to initialize and finalize
Python:

  • Py_Initialize(), Py_InitializeEx(): initialize Python
  • Py_Finalize(), Py_FinalizeEx(): finalize Python

Python 3.7 can be configured using ,
, and the following functions:

  • PyImport_AppendInittab()
  • PyImport_ExtendInittab()
  • PyMem_SetAllocator()
  • PyMem_SetupDebugHooks()
  • PyObject_SetArenaAllocator()
  • Py_SetPath()
  • Py_SetProgramName()
  • Py_SetPythonHome()
  • Py_SetStandardStreamEncoding()
  • PySys_AddWarnOption()
  • PySys_AddXOption()
  • PySys_ResetWarnOptions()

There is also a high-level Py_Main() function and
PyImport_FrozenModules variable which can be overridden.

See Initialization, Finalization, and Threads documentation.

Splitting the meanings of sys.prefix

Any virtual environment tool along these lines (which attempts to
isolate site-packages, while still making use of the base Python’s
standard library with no need for it to be symlinked into the virtual
environment) is proposing a split between two different meanings
(among others) that are currently both wrapped up in sys.prefix:
the answers to the questions «Where is the standard library?» and
«Where is the site-packages location where third-party modules should
be installed?»

This split could be handled by introducing a new sys attribute for
either the former prefix or the latter prefix. Either option
potentially introduces some backwards-incompatibility with software
written to assume the other meaning for sys.prefix. (Such
software should preferably be using the APIs in the site and
sysconfig modules to answer these questions rather than using
sys.prefix directly, in which case there is no
backwards-compatibility issue, but in practice sys.prefix is
sometimes used.)

The for sys.prefix describes it as «A string
giving the site-specific directory prefix where the platform
independent Python files are installed,» and specifically mentions the
standard library and header files as found under sys.prefix. It
does not mention site-packages.

Maintaining this documented definition would mean leaving
sys.prefix pointing to the base system installation (which is
where the standard library and header files are found), and
introducing a new value in sys (something like
sys.site_prefix) to point to the prefix for site-packages.
This would maintain the documented semantics of sys.prefix, but
risk breaking isolation if third-party code uses sys.prefix rather
than sys.site_prefix or the appropriate site API to find
site-packages directories.

The most notable case is probably setuptools and its fork
distribute , which mostly use distutils and sysconfig APIs,
but do use sys.prefix directly to build up a list of site
directories for pre-flight checking where pth files can usefully be
placed.

Otherwise, a Google Code Search turns up what appears to be a
roughly even mix of usage between packages using sys.prefix to
build up a site-packages path and packages using it to e.g. eliminate
the standard-library from code-execution tracing.

Although it requires modifying the documented definition of
sys.prefix, this PEP prefers to have sys.prefix point to the
virtual environment (where site-packages is found), and introduce
sys.base_prefix to point to the standard library and Python header
files. Rationale for this choice:

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

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

Adblock
detector