Python downloads main py

Используйте __main__.py

Зачем нужен __init__.py знает, наверное, любой питонист, но что насчёт __main__.py? Я видел немало проектов либо рабочих, либо на Github, которые не используют этот магический файл, хотя могли бы сделать свою жизнь проще. На мой взгляд, __main__.py это лучший способ для взаимодействия с питоновскими модулями, состоящими из нескольких файлов.

Но давайте сначала разберёмся: как большинство людей запускают свои скрипты на Python?

Однажды вы напишете программу, которую захотите использовать и как импортируемый модуль, и как инструмент запускаемый из командной строки. Вы скорей всего в курсе, как обычно поступают в этом случае:

if __name__ == '__main__': main(sys.argv)

Когда вы скармливаете скрипт интерпретатору, магическая глобальная переменная __name__ получает значение __main__. Таким образом мы узнаём, что это не импорт, а именно запуск. Например:

И это прекрасно работает для одиночного файла.

Проблема

Но если вы похожи на меня, вы не захотите, чтобы всё ваше приложение теснилось в единственном файле. Разбиение логики по разным файлам упрощает редактирование и поддержку. Например:

. ├── README.me ├── requirements.txt ├── setup.py └── src ├── __init__.py ├── client.py ├── logic.py ├── models.py └── run.py

Но пользователю, который склонировал проект из репозитория будет непонятно — какой из этих файлов главный? Неужели run.py? А может client.py? Где же искать знакомую строку if __name__ == ‘__main__’? Вот здесь-то __main__.py и способен проявить себя.

__main__.py

Файл __main__.py вызывается при запуске проекта с флагом модуля — -m. И это весьма удобно, если код предназначен и для использования в качестве модуля, и для запуска из консоли. Думайте об этом файле, как о месте куда можно класть всё, что вы обычно кладёте внутрь if __name__ == __main__’. Давайте изменим проект из примера выше соответственно:

. ├── README.me ├── requirements.txt ├── setup.py └── myapp ├── __init__.py ├── __main__.py ├── client.py ├── logic.py ├── models.py

И, вуаля! Теперь можно просто запускать проект как обычный модуль.

Читайте также:  Import file in python script

__main__.py будет выполняться автоматически. Это идеальное место для размещения интерфейса командной строки и обработки входных аргументов!

Источник

Download the latest version of Python

Bloomberg logo Meta logo Google logo

All Python releases are Open Source. Historically, most, but not all, Python releases have also been GPL-compatible. The Licenses page details GPL-compatibility and Terms and Conditions.

Sources

For most Unix systems, you must download and compile the source code. The same source code archive can also be used to build the Windows and Mac versions, and is the starting point for ports to all other platforms.

Download the latest Python 3 source.

Alternative Implementations

This site hosts the «traditional» implementation of Python (nicknamed CPython). A number of alternative implementations are available as well.

History

Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum in the Netherlands as a successor of a language called ABC. Guido remains Python’s principal author, although it includes many contributions from others.

Release Schedules

See Status of Python Versions for all an overview of all versions, including unsupported.

Information about specific ports, and developer info

OpenPGP Public Keys

Source and binary executables are signed by the release manager or binary builder using their OpenPGP key. Release files for currently supported releases are signed by the following:

  • Thomas Wouters (3.12.x and 3.13.x source files and tags) (key id: A821E680E5FA6305)
  • Pablo Galindo Salgado (3.10.x and 3.11.x source files and tags) (key id: 64E628F8D684696D)
  • Steve Dower (Windows binaries) (key id: FC62 4643 4870 34E5)
  • Łukasz Langa (3.8.x and 3.9.x source files and tags) (key id: B269 95E3 1025 0568)
  • Ned Deily (macOS binaries, 3.7.x / 3.6.x source files and tags) (key ids: 2D34 7EA6 AA65 421D and FB99 2128 6F5E 1540
  • Larry Hastings (3.5.x source files and tags) (key id: 3A5C A953 F73C 700D)
  • Benjamin Peterson (2.7.z source files and tags) (key id: 04C3 67C2 18AD D4FF and A4135B38)

Release files for older releases which have now reached end-of-life may have been signed by one of the following:

  • Anthony Baxter (key id: 0EDD C5F2 6A45 C816)
  • Georg Brandl (key id: 0A5B 1018 3658 0288)
  • Martin v. Löwis (key id: 6AF0 53F0 7D9D C8D2)
  • Ronald Oussoren (key id: C9BE 28DE E6DF 025C)
  • Barry Warsaw (key ids: 126E B563 A74B 06BF, D986 6941 EA5B BD71, and ED9D77D5)
Читайте также:  Java interface exception method

You can import a person’s public keys from a public keyserver network server you trust by running a command like:

or, in many cases, public keys can also be found at keybase.io. On the version-specific download pages, you should see a link to both the downloadable file and a detached signature file. To verify the authenticity of the download, grab both files and then run this command:

gpg --verify Python-3.6.2.tgz.asc

Note that you must use the name of the signature file, and you should use the one that’s appropriate to the download you’re verifying.

macOS Installer Packages

Installer packages for Python on macOS downloadable from python.org are signed with with an Apple Developer ID Installer certificate.

  • As of Python 3.11.4 and 3.12.0b1 (2023-05-23), release installer packages are signed with certificates issued to the Python Software Foundation (Apple Developer ID BMM5U3QVKW)).
  • Installer packages for previous releases were signed with certificates issued to Ned Deily (DJ3H93M7VJ).

Other Useful Items

  • Looking for 3rd party Python modules? The Package Index has many of them.
  • You can view the standard documentation online, or you can download it in HTML, PostScript, PDF and other formats. See the main Documentation page.
  • Information on tools for unpacking archive files provided on python.org is available.
  • Tip: even if you download a ready-made binary for your platform, it makes sense to also download the source. This lets you browse the standard library (the subdirectory Lib) and the standard collections of demos (Demo) and tools (Tools) that come with it. There’s a lot you can learn from the source!
  • There is also a collection of Emacs packages that the Emacsing Pythoneer might find useful. This includes major modes for editing Python, C, C++, Java, etc., Python debugger interfaces and more. Most packages are compatible with Emacs and XEmacs.

Want to contribute?

Want to contribute? See the Python Developer’s Guide to learn about how Python development is managed.

  • About
    • Applications
    • Quotes
    • Getting Started
    • Help
    • Python Brochure
    • All releases
    • Source code
    • Windows
    • macOS
    • Other Platforms
    • License
    • Alternative Implementations
    • Docs
    • Audio/Visual Talks
    • Beginner’s Guide
    • Developer’s Guide
    • FAQ
    • Non-English Docs
    • PEP Index
    • Python Books
    • Python Essays
    • Diversity
    • Mailing Lists
    • IRC
    • Forums
    • PSF Annual Impact Report
    • Python Conferences
    • Special Interest Groups
    • Python Logo
    • Python Wiki
    • Code of Conduct
    • Community Awards
    • Get Involved
    • Shared Stories
    • Arts
    • Business
    • Education
    • Engineering
    • Government
    • Scientific
    • Software Development
    • Python News
    • PSF Newsletter
    • PSF News
    • PyCon US News
    • News from the Community
    • Python Events
    • User Group Events
    • Python Events Archive
    • User Group Events Archive
    • Submit an Event
    • Developer’s Guide
    • Issue Tracker
    • python-dev list
    • Core Mentorship
    • Report a Security Issue

    Источник

    Saved searches

    Use saved searches to filter your results more quickly

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

    A command-line processor for Python

    regularfry/mainpy

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

    Name already in use

    A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

    Sign In Required

    Please sign in to use Codespaces.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.rst

    A quick and dirty command-line processor. See main.py for more.

    import main import sys def callback(params): print "Called with " + params['foo'].value m = main.mode("run", callback) m.option("foo") m.description="How not to be seen" main.process(sys.argv)

    Usage: # How not to be seen b.py run —foo=

    Most of the work, including:

    • Errors will be caught and redirected to usage messages better
    • Options will have default arguments.
    • The top-level mode will become unnecessary.
    • Non-option arguments will be respected.
    • Param objects will support more information.
    • Cheese will be eaten.

    This code is in the public domain. Do as you will. Feedback and patches are welcome but not required.

    About

    A command-line processor for Python

    Источник

Оцените статью