CMS written in Python


Содержание

Python Django CMS — FeinCMS

Python CMS

Не буду углубляться в терминологию, думаю что те кто зашел на мой блог и так прекрасно осведомлены о том что такое CMS. Для всех веб разработчиков всегда существует дилема выбора готовой CMS или написания своей собственной. Поскольку я не занимаюсь созданием сайтов в промышленных масштабах, то пытаюсь найти нечто готовое, изучить и по-возможности переиспользовать. В моем подходе есть недостатки, так как редко получается найти на 100% подходящее решение и зачастую кода больше чем необходимо. Но этот подход, с чем невозможно поспорить, увеличивает скорость разработки и улучшает кругозор, потому что исследуется чужой код. В основном, в работе я использую Django Framework. Но появилась необходимость в системе управления статическими страницами, для которой встроенное приложение django static pages уже недостаточно. Держать Django приложение для простого 10 страничного сайта, это неразумно, хоть я в итоге и делаю теперь так, в угоде других приоритетов, несколько сайтов на одной CMS, правильный шаблонизатор с наследованием. Но изначально хотелось что-нибудь поменьше, а также более юзерфрэндли для конечных пользователей. Так чтобы пользователь без лишних вопросов мог добавить страничку, отредактировать ее в tinymce или добавить видео из youtube лего и бысто. В общем набор как всегда взаимоисключающих требований. Но первое и самое важное для меня — это обязательно язык программирования Python. И в данном сегменте я нашел более 10 хороших вариантов, для изучения:

  1. Django CMS — основан на django
  2. PyLucid — основан на django
  3. Mezzanine — основан на django
  4. Pinax — основан на django
  5. Merengue — основан на django
  6. FeinCMS — основан на django
  7. DjangoLFC — быстрая CMS на django
  8. Plone — большой Zope основанный
  9. Kotti — основано на Pyramid
  10. Quokka project — основан на Flask (база данных MongoDB)
  11. Skeletonz
  12. NiVE
  13. ikaaro
  14. wagtail
  15. bottle — вообще micro cms

Сразу выбрал DjangoCMS, но она меня не впечатлила, осталась такой же как и была 10 лет назад и как всегда с ней установилось 100500 пакетов, дизайн меня не впечатлил, сложно обучать человека работать с админкой, Kotti — абсолютно другой подход и совершенно не известная для меня технология (обязательно к этому еще вернусь), Quokka пожалуй одна из лучших систем на сегодняшний день, очень удачная для пользователя, не перегруженная, современная, лишенная недостатков концепции фундамента, в виде больших фреймворков. Но есть одно но — это база данных MongoDB, если бы была база данных PostgreSQL то я бы выбрал её. После изучения каждого из вариантов, времени осталось мало и я решил — выберу что-нибудь более ли менее стабильное, то что я знаю, не перегруженное, и поскольку выяснилось, что Django cms приложение — Django cms приложению рознь мой выбор пал на FeinCMS.

О ней я сегодня и напишу.

FeinCMS

CMS написанная на Python, основана на Django, а в Django есть коровья сила — это значит, что при установке CMS у нас будут все бесчисленные возможности фреймворка Django. Библиотека содержит множество готовых решений для повседневных задач веб разработчика, позволяет быстро стартовать, а язык разработки гарантирует вам хорошую поддерживаемость кода. FeinCMS — это больше, чем система управления контентом (не только благодаря Django). Например, FeinCMS позволяет определить свои типы содержимого (Content Type), таким образом CMS представляется уже системой разработки веб приложений. В админке же есть все необходимое прямо из коробки для управления пользовательским контентом.

Важно! Принципы установки FeinCMS теже, что и у любого другого Django приложения. Это руководство будет также полезно для начинающих знакомиться с фреймворком Django.

К плюсам FeinCMS можно отнести также наличие, отнюдь не исчерпывающей, но официальной документации на readthedocs.org

Подготовка к установке FeinCMS

Необходимо обновить операционную систему. Все команды выполеняются под привелегированной учетной записью (от root)

Далее установим необходимые библиотеки необходимые для работы Python и для установки его модулей

Установка FeinCMS

Настроим виртуальное окружении, чтобы безопасно для системы установить FeinCMS со всеми зависимостями.

Активируем виртуальное окружение

На сегодня 5 апреля 2015 у FeinCMS существуют проблемы с django 1.8, поэтому перед установкой cms следует установить django 1.7, остальные зависимости подтянутся вместе с FeinCMS.

Установим модуль для работы с базой данных в моем случае это PostgreSQL (для MySQL mysql-python )

Подготовка FeinCMS

Для запуска FeinCMS необходимо создать Django проект, в настройках которого прописать приложение feincms.

Необходимо создать пользовательское приложение cms

Изменим файл настроек Django в соостветствии с приложениями

Внесем изменения в кортеж INSTALLED_APPS , добавим feincms приложения и cms :

Необходимо изменить настройку базы данных

Для запуска необходимо удалить или закомментировать строчку security в кортеже MIDDLEWARE_CLASSES

Подправим директорию поиска тэмплейтов:

Для работы нужно urls.py привести к виду

Создание базы данных

Для работы FeinCMS требуются модели. Это отличие этой CMS от других. Поэтому прежде чем создать базу данных необходимо создать модели.

Полное описание Page модуля FeinCMS в документации

Инициализируем базу данных

Создание темплейта

Нуобходима директория для хранения темплейтов

Отредактируем темплейт модели, которую мы создали выше

Тестируем приложение

Запустим тестовый Django сервер

Заходим в Django админку и создаем страницы на основе нашей модели

Спасибо за внимание! Статья обязательно будет обновляться в соответствии с вашими комментариями. Да, еще, ;) если статья была вам полезна, щелкните по рекламе.

Python CMS to create a v > Ask Question

Is anyone aware of a open source CMS written in python using which I can make a site like YouTube?

closed as not constructive by Kris, fresskoma, user647772, Craig Ringer, Simone Carletti Oct 8 ’12 at 11:24

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for gu >If this question can be reworded to fit the rules in the help center, please edit the question.

6 Answers 6

Django is a good Python Framework, as well as CherryPy and Pylons. However, a framework is not a CMS.

An open source video CMS would be: Media Core

Here is some info about how YouTube is build:

Platform:

  1. Apache
  2. Python
  3. Linux (SuSe)
  4. MySQL
  5. psyco, a dynamic python->C compiler
  6. lighttpd for video instead of Apache

Webservers:

  1. NetScalar is used for load balancing and caching static content.
  2. Run Apache with mod_fast_cgi.
  3. Requests are routed for handling by a Python application server.
  4. Application server talks to various databases and other informations sources to get all the data and formats the html page.
  5. Can usually scale web tier by adding more machines.
  6. The Python web code is usually NOT the bottleneck, it spends most of its time blocked on RPCs.
  7. Python allows rapid flexible development and deployment. This is critical given the competition they face.
  8. Usually less than 100 ms page service times.
  9. Use psyco, a dynamic python->C compiler that uses a JIT compiler approach to optimize inner loops.
  10. For high CPU intensive activities like encryption, they use C extensions.
  11. Some pre-generated cached HTML for expensive to render blocks.
  12. Row level caching in the database.
  13. Fully formed Python objects are cached.
  14. Some data are calculated and sent to each application so the values are cached in local memory. This is an underused strategy. The fastest cache is in your application server and it doesn’t take much time to send precalculated data to all your servers. Just have an agent that watches for changes, precalculates, and sends.

Video serving:

Costs include bandwidth, hardware, and power consumption.

Each video hosted by a mini-cluster. Each video is served by more than one machine.

Using a a cluster means:

  • More disks serving content which means more speed.
  • Headroom. If a machine goes down others can take over.
  • There are online backups.

Servers use the lighttpd web server for video:

  • Apache had too much overhead.
  • Uses epoll to wait on multiple fds.
  • Switched from single process to multiple process configuration to handle more connections.

Most popular content is moved to a CDN (content delivery network):

  • CDNs replicate content in multiple places. There’s a better chance of content being closer to the user, with fewer hops, and content will run over a more friendly network.
  • CDN machines mostly serve out of memory because the content is so popular there’s little thrashing of content into and out of memory.

Less popular content (1-20 views per day) uses YouTube servers in various colo sites.

  • There’s a long tail effect. A video may have a few plays, but lots of videos are being played. Random disks blocks are being accessed.
  • Caching doesn’t do a lot of good in this scenario, so spending money on more cache may not make sense. This is a very interesting point. If you have a long tail product caching won’t always be your performance savior.
  • Tune RAID controller and pay attention to other lower level issues to help.
  • Tune memory on each machine so there’s not too much and not too little.

Is It Worth Creating a CMS in Python?

How to choose the best technology for creating a CMS? We will help you decide which factors you should consider before making a decision and we will analyze if the Python programming language is a good option.

Building an intuitive and easy-to-use CMS is a challenging project. And this challenge starts with choosing the right technology.

Let’s start from the beginning.

What is a CMS?

A content management system — better known as a CMS — is a kind of software that’s designed for the creation and modification of digital content. Among its wide variety of features, it usually offers publishing options, version control, search engine optimization, access control, and different design templates. It streamlines the content creation and publishing processes by providing a simple user interface that supports your marketing strategy, without requiring any advanced technical knowledge from users.

What factors should you pay attention to when choosing a technology to build a CMS?

Core functionality and managing assets

A good CMS should provide multiple handy out-of-the-box functionalities; this will make working with content easier and more robust. It should also allow for easy asset management.

User interaction

The CMS should be intuitive and user friendly; it should provide self-explanatory ways to manage content and even add new subpages.

SEO

A good CMS should be prepared for SEO. The page structure, meta tags, and other auto-generated content have to be SEO-friendly.

Integration with other systems


The CMS should be a place gathering in one spot different external services and providers necessary for your business to function, such as payment gateways or social media integrations.

Popularity

It’s super important to choose a technology which is backed by a large community, offers lots of integrations and extensions along with easy-to-find manuals.

Experts

You need to have access to a broad market of IT specialists who will help you create your ideal team and be able to fill in any rotation gaps.

Performance

The selected technology should start performing right out of the box, and be easy to install and deploy without bearing additional expenses on external support.

Cloud storage

Security

It’s safer to select a full-fledged technology — one that has already been tested in many different areas and is supported by a community that deals with any new bugs.

All of these factors appear to be outstanding in Python development.

Python’s superpowers in general

According to the TIOBE Index, Python is the fastest growing programming language these days. It is an extremely popular, general-purpose language heavily used by some of the biggest players in the world like Google, Facebook, Spotify, and Netflix. Being user-friendly and easy-to-work-with makes it highly efficient to not only find experienced employees but also to train new ones.

Why is Python a good language of choice for creating a CMS?

1. Maturity

Python has two big players in the world of CMSs: Wagtail and Django CMS. Both are well-tested and mature, quality solutions, with a large community of customers, editors and — above all — developers who are constantly working on new features and releasing updates and bug fixes. This is important because it makes the software even more functional and reliable.

2. Ease of use and speed

Python frameworks are easy to adapt and convert into a tailor-made CMS, while at the same time act like building blocks for programming. This is extremely helpful when it comes to fast delivery with a limited team, as you can have a lot of functions, like contact forms, WYSIWYG editor or page hierarchy without coding, since they are already implemented.

3. Prebuilt admin dashboard

Both Wagtail and Django CMS are built on top of the Django framework which comes with a prebuilt admin dashboard. This is a huge advantage in terms of the speed of developing a CMS that has a built-in space for admins to manage content, users, and so on. You can get a sneak peek by clicking on the links: DjangoCMS/Wagtail.

4. Advanced and ready-to-use features

The biggest advantages of Python frameworks include: simplicity of deployment, the availability of cloud solutions (like AWS, GCP or Heroku) and a lot of single-click tools that make it possible to establish proper CI/CD pipelines for high degrees of automation in the process of delivering new code. These and many other things guarantee that your product will be well-tested and resistant to time.

What is crucial from business perspective?

All of these points are not only significant for devs, but also crucial from a business perspective.

  • When you use a mature and relatively secure framework backed by so many experts, you don’t have to spend a lot of time and money on any additional support.
  • You also have more specialized developers to choose from. Looking for someone to fill a vacancy is not so problematic.
  • The ease of use and many built-in features already available in the framework make development go much faster. It’s also more efficient and less costly.
  • The further development of your CMS also becomes simpler, so you can think about unwinding its full potential, making it as made-to-measure as possible.

Remember: if you don’t adjust the technology required for building a CMS properly, this may result in a lengthier development and very poor support in the case of a critical situation. There’s also a big chance that you will be dramatically limited by its functions, so scaling may be a nightmare. You might spend a lot of money on solving problems that wouldn’t have occurred if you had just selected a better option.

This is why creating a Python-based CMS may be the safest alternative.

Powerful examples of CMSs

And here are some powerful examples of other CMSs — besides Wagtail and Django CMS — that also prove this point.

1. Mezzanine

This is a BSD-licensed, Django-based CMS, which is highly flexible and extendable. It features an intuitive, consistent interface for managing content and provides a great level of support for its users. This platform is also really efficient because most of its functions are available by default.

2. Ikaaro

This is a comprehensive, multilingual app — highly configurable with a wide range of capabilities, including high level modules, like forums or wikis. It features access control, metadata, intuitive document management, and much more.

3. Kotti

This CMS is not only super simple to use, but also provides automated workflows, a great level of security, and data hierarchies that are pretty easy to understand. It includes a user-friendly interface, so it’s easy for a user to navigate through the content. Moreover, it’s been translated to many languages, is highly customizable, and very scalable.

Wrap-up

So, is it worth creating a CMS in Python? Definitely, yes. Of course, choosing the right technology should always be based on your individual goals, strategy, and the nature of your project. There’s no single solution that is perfect for everything. However, we might assist you in finding the most adequate one.

If you need any help regarding this issue — let us know, and we’ll figure out the best option for you together.

Looking for a static Blog/CMS written in python

I’m looking for a static Blog/CMS written Python.

The features of my ideal one are:

  • WYSIWYG editing or alternatively a powerful flavour of markdown
  • No need of building posts/pages
  • Flexible and resilient to changes of themes and templates, I don’t want to spend all day fixing a broken site after changing look and feel.
  • Tags
  • Free and Open Source Software
  • Able to Self Hosting, I mean not public cloud based
  • It would be great if has a calendar
  • I have no problem of edit posts/pages by hand, but only as an other way of editing
  • Ideal for python beginners, I don’t wanna to spend all of my day searching how to fix a template..

jcms 1.2.1

pip install jcms Copy PIP instructions

Last released: Nov 24, 2020

This is a cms written in Django and made by JCB Development

Statistics

View statistics for this project via Libraries.io, or by using Google BigQuery

License: MIT License (MIT)

Tags cms, admin, development, content, management, system

Maintainers

Classifiers

  • Development Status
    • 5 — Production/Stable
  • Framework
    • Django :: 2.0
  • Intended Audience
    • Developers
  • License
    • OSI Approved :: MIT License
  • Programming Language
    • Python :: 3.5
  • Topic
    • Internet :: WWW/HTTP :: Site Management

Project description

Jcms is an easy to use cms for Django(python)

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.

The only thing that you need to have installed is pip. But if you haven’t this means you are also not using django which you should.

Jcms is easy to install. First you install it via pip

Now you can add Jcms to INSTALLED_APPS in your settings file.

After this you need to add the urls to your urls.py. You can replace admin with everything you want.

«`python
from django.conf.urls import path, include

urlpatterns = [
path(‘admin/’, include(‘jcms.urls’)),
]
«`

Now to add a user you can do this via the commandline. Find more on this in the [documentation of Django](https://docs.djangoproject.com/en/1.11/topics/auth/default/)

Now go to your site’s url and do the /admin/ (or if you have chosen another path type that). You can now log in with the credentials you just created.

## Before using
### Be aware of the following things
There can only be one model with the same name

These model names are in use:
— User
— Group
— Option

You can add menu items and urls to jcms. This means that the urls you add are connected to the Jcms app.

What you first have to do is add the jcms.py file to the app. The file structure of the app is underneath

«`
practice-app
jcms.py
migrations
static
templates
other-folders
«`

Everything for jcms can be done in the jcms.py file.

> You can disable the warning for each setting if you don’t want to add it by adding this to jcms.py
«`python
from jcms.components import NoConfig

### Adding crud views

«`python
from jcms.generators import CMSGenerator
from jcmstest.models import Test, PK

urlpatterns = [
CMSGenerator(Test, [‘type’, ‘value’, ‘content’], [‘type’, ‘value’]),
CMSGenerator(PK, [‘name’], [‘name’])
]
«`

The following options can be given:
— **model** = The model this crud is for
— **create_edit_list** = This is an array of items which you can create and edit in these views
— **list_fields** = This is a list of fields of the model which are shown in the list view

CMSGenerator makes the following views:
— Create. Viewname is $Create
— Edit. Viewname is $Edit
— List. Viewname is $List
— Delete. Viewname is $Delete

### Adding api views

This is a basic example of a api view for jcms.

«`python
from jcms.generators import APIGenerator
from jcmstest.models import Test

Required variables are:
— **model** = model used for the api
— **basis_fields** = default fields that the api uses to serialize
— **lookup_field** = The field that is used for the retrieving of a single object

The options you can give to APIGenerator are:
— **methods** = A list that has the methods that are allowed ([see below](#methods))
— **method_fields** = A dict that has the fields for each method

Цукерберг рекомендует:  Задаем стиль сайта в зависимости от погоды

#### methods
— **overview** = Gets the models by a GET request to /api/$. You can also filter on these fields using query parameters. If no overview fields are given is goes back to the basis fields
— **create** = Creates a model by a POST request to /api/$
— **update** = Updates a model by a PUT for a full update and a PATCH for partial update to /api/$/$
— **retrieve** = Gets the model by GET request to /api/$/$
— **delete** = Deletes a model by DELETE request to /api/$/$
— **lookup_field** = Field used for the $-detail view

For every each option (overview, create, update, retrieve, delete) you can pass certain fields if you don’t want to use the basic ones. You can pass them in the dict object of method_fields

The names for the views are:
— all or overview and create = $-list
— all or update, retrieve and delete = $-detail

### Making the menu items

First you need to create a menu_item.py in the jcms.py file.


«`python
from jcms.models import GenericMenuItem, SingleMenuItem
from jcmstest.models import Test, PK

menu_item = GenericMenuItem(‘Test’, [
SingleMenuItem(‘Test’, ‘testList’),
SingleMenuItem(‘PK’, ‘pkList’),
])
«`

You can give the following options:
* name = The name seen on the menu item
* items = List of the menu item. This HAS to be a SingleMenuItem Object.
* slug = The slug used in the url. The slug is optional

### Adding your menu item to jcms

The last step is to add the menu item to jcms. You can do this by going to your django settings and adding this line.

«`python
JCMS_APPS = [‘practice-app’]
«`

This are only the apps that should be in Jcms.

The icons you can use are =:
— add
— delete
— dropdown-caret
— edit
— groups
— hamburger
— home
— logout
— options
— standard-menu-item
— users
— cancel

These are the template tags that you can use that are in Jcms

Awesome Python

A curated list of awesome Python frameworks, libraries, software and resources.

Admin Panels

Libraries for administrative interfaces.

  • ajenti — The admin panel your servers deserve.
  • django-grappelli — A jazzy skin for the Django Admin-Interface.
  • django-jet — Modern responsive template for the Django admin interface with improved functionality.
  • django-suit — Alternative Django Admin-Interface (free only for Non-commercial use).
  • django-xadmin — Drop-in replacement of Django admin comes with lots of goodies.
  • flask-admin — Simple and extensible administrative interface framework for Flask.
  • flower — Real-time monitor and web admin for Celery.
  • wooey — A Django app which creates automatic web UIs for Python scripts.

Algorithms and Design Patterns

Python implementation of algorithms and design patterns.

  • algorithms — Minimal examples of data structures and algorithms in Python.
  • PyPattyrn — A simple yet effective library for implementing common design patterns.
  • python-patterns — A collection of design patterns in Python.
  • sortedcontainers — Fast, pure-Python implementation of SortedList, SortedDict, and SortedSet types.

Audio

Libraries for manipulating audio and its metadata.

  • Audio
    • audioread — Cross-library (GStreamer + Core Audio + MAD + FFmpeg) audio decoding.
    • dejavu — Audio fingerprinting and recognition.
    • mingus — An advanced music theory and notation package with MIDI file and playback support.
    • pyAudioAnalysis — Audio feature extraction, classification, segmentation and applications.
    • pydub — Manipulate audio with a simple and easy high level interface.
    • TimeSide — Open web audio processing framework.
  • Metadata
    • beets — A music library manager and MusicBrainz tagger.
    • eyeD3 — A tool for working with audio files, specifically MP3 files containing ID3 metadata.
    • mutagen — A Python module to handle audio metadata.
    • tinytag — A library for reading music meta data of MP3, OGG, FLAC and Wave files.

Authentication

Libraries for implementing authentications schemes.

  • OAuth
    • authlib — JavaScript Object Signing and Encryption draft implementation.
    • django-allauth — Authentication app for Django that «just works.»
    • django-oauth-toolkit — OAuth 2 goodies for Django.
    • oauthlib — A generic and thorough implementation of the OAuth request-signing logic.
    • python-oauth2 — A fully tested, abstract interface to creating OAuth clients and servers.
    • python-social-auth — An easy-to-setup social authentication mechanism.
  • JWT
    • pyjwt — JSON Web Token implementation in Python.
    • python-jose — A JOSE implementation in Python.
    • python-jwt — A module for generating and verifying JSON Web Tokens.

Build Tools

Compile software from source code.

  • BitBake — A make-like build tool for embedded Linux.
  • buildout — A build system for creating, assembling and deploying applications from multiple parts.
  • PlatformIO — A console tool to build code with different development platforms.
  • pybuilder — A continuous build tool written in pure Python.
  • SCons — A software construction tool.

Built-in Classes Enhancement

Libraries for enhancing Python built-in classes.

  • dataclasses — (Python standard library) Data classes.
  • attrs — Replacement for __init__ , __eq__ , __repr__ , etc. boilerplate in class definitions.
  • bidict — Efficient, Pythonic bidirectional map data structures and related functionality..
  • Box — Python dictionaries with advanced dot notation access.
  • DottedDict — A library that provides a method of accessing lists and dicts with a dotted path notation.

Content Management Systems.

  • wagtail — A Django content management system.
  • django-cms — An Open source enterprise CMS based on the Django.
  • feincms — One of the most advanced Content Management Systems built on Django.
  • Kotti — A high-level, Pythonic web application framework built on Pyramid.
  • mezzanine — A powerful, consistent, and flexible content management platform.
  • plone — A CMS built on top of the open source application server Zope.
  • quokka — Flexible, extensible, small CMS powered by Flask and MongoDB.

Caching

Libraries for caching data.

  • beaker — A WSGI middleware for sessions and caching.
  • django-cache-machine — Automatic caching and invalidation for Django models.
  • django-cacheops — A slick ORM cache with automatic granular event-driven invalidation.
  • dogpile.cache — dogpile.cache is next generation replacement for Beaker made by same authors.
  • HermesCache — Python caching library with tag-based invalidation and dogpile effect prevention.
  • pylibmc — A Python wrapper around the libmemcached interface.
  • python-diskcache — SQLite and file backed cache backend with faster lookups than memcached and redis.

ChatOps Tools

Libraries for chatbot development.

  • errbot — The easiest and most popular chatbot to implement ChatOps.

Code Analysis

Tools of static analysis, linters and code quality checkers. Also see awesome-static-analysis.

  • Code Analysis
    • coala — Language independent and easily extendable code analysis application.
    • code2flow — Turn your Python and JavaScript code into DOT flowcharts.
    • prospector — A tool to analyse Python code.
    • pycallgraph — A library that visualises the flow (call graph) of your Python application.
  • Code Linters
    • flake8 — A wrapper around pycodestyle , pyflakes and McCabe.
    • pylint — A fully customizable source code analyzer.
    • pylama — A code audit tool for Python and JavaScript.
  • Code Formatters
    • black — The uncompromising Python code formatter.
    • yapf — Yet another Python code formatter from Google.
  • Static Type Checkers
    • mypy — Check variable types during compile time.
    • pyre-check — Performant type checking.
  • Static Type Annotations Generators
    • MonkeyType — A system for Python that generates static type annotations by collecting runtime types

Command-line Interface Development

Libraries for building command-line applications.

  • Command-line Application Development
    • cement — CLI Application Framework for Python.
    • click — A package for creating beautiful command line interfaces in a composable way.
    • cliff — A framework for creating command-line programs with multi-level commands.
    • clint — Python Command-line Application Tools.
    • docopt — Pythonic command line arguments parser.
    • python-fire — A library for creating command line interfaces from absolutely any Python object.
    • python-prompt-toolkit — A library for building powerful interactive command lines.
  • Terminal Rendering
    • asciimatics — A package to create full-screen text UIs (from interactive forms to ASCII animations).
    • bashplotlib — Making basic plots in the terminal.
    • colorama — Cross-platform colored terminal text.
    • tqdm — Fast, extensible progress bar for loops and CLI.

Command-line Tools

Useful CLI-based tools for productivity.

  • Productivity Tools
    • cookiecutter — A command-line utility that creates projects from cookiecutters (project templates).
    • doitlive — A tool for live presentations in the terminal.
    • howdoi — Instant coding answers via the command line.
    • PathPicker — Select files out of bash output.
    • percol — Adds flavor of interactive selection to the traditional pipe concept on UNIX.
    • thefuck — Correcting your previous console command.
    • tmuxp — A tmux session manager.
    • try — A dead simple CLI to try out python packages — it’s never been easier.
  • CLI Enhancements
    • httpie — A command line HTTP client, a user-friendly cURL replacement.
    • kube-shell — An integrated shell for working with the Kubernetes CLI.
    • mycli — A Terminal Client for MySQL with AutoCompletion and Syntax Highlighting.
    • pgcli — Postgres CLI with autocompletion and syntax highlighting.
    • saws — A Supercharged aws-cli.

Compatibility

Libraries for migrating from Python 2 to 3.

  • python-future — The missing compatibility layer between Python 2 and Python 3.
  • python-modernize — Modernizes Python code for eventual Python 3 migration.
  • six — Python 2 and 3 compatibility utilities.

Computer Vision

Libraries for computer vision.

  • OpenCV — Open Source Computer Vision Library.
  • pytesseract — Another wrapper for Google Tesseract OCR.
  • SimpleCV — An open source framework for building computer vision applications.

Concurrency and Parallelism

Libraries for concurrent and parallel execution. Also see awesome-asyncio.

  • concurrent.futures — (Python standard library) A high-level interface for asynchronously executing callables.
  • multiprocessing — (Python standard library) Process-based parallelism.
  • eventlet — Asynchronous framework with WSGI support.
  • gevent — A coroutine-based Python networking library that uses greenlet.
  • uvloop — Ultra fast implementation of asyncio event loop on top of libuv .
  • scoop — Scalable Concurrent Operations in Python.

Configuration

Libraries for storing and parsing configuration options.

  • configobj — INI file parser with validation.
  • configparser — (Python standard library) INI file parser.
  • profig — Config from multiple formats with value conversion.
  • python-decouple — Strict separation of settings from code.

Cryptography

  • cryptography — A package designed to expose cryptographic primitives and recipes to Python developers.
  • paramiko — The leading native Python SSHv2 protocol library.

  • passlib — Secure password storage/hashing library, very high level.
  • pynacl — Python binding to the Networking and Cryptography (NaCl) library.

Data Analysis

Libraries for data analyzing.

  • Blaze — NumPy and Pandas interface to Big Data.
  • Open Mining — Business Intelligence (BI) in Pandas interface.
  • Orange — Data mining, data visualization, analysis and machine learning through visual programming or scripts.
  • Pandas — A library providing high-performance, easy-to-use data structures and data analysis tools.
  • Optimus — Agile Data Science Workflows made easy with PySpark.

Data Validation

Libraries for validating data. Used for forms in many cases.

  • Cerberus — A lightweight and extensible data validation library.
  • colander — Validating and deserializing data obtained via XML, JSON, an HTML form post.
  • jsonschema — An implementation of JSON Schema for Python.
  • schema — A library for validating Python data structures.
  • Schematics — Data Structure Validation.
  • valideer — Lightweight extensible data validation and adaptation library.
  • voluptuous — A Python data validation library.

Data Visualization

Libraries for visualizing data. Also see awesome-javascript.

  • Altair — Declarative statistical visualization library for Python.
  • Bokeh — Interactive Web Plotting for Python.
  • bqplot — Interactive Plotting Library for the Jupyter Notebook
  • Dash — Built on top of Flask, React and Plotly aimed at analytical web applications.
    • awesome-dash
  • ggplot — Same API as ggplot2 for R.
  • Matplotlib — A Python 2D plotting library.
  • Pygal — A Python SVG Charts Creator.
  • PyGraphviz — Python interface to Graphviz.
  • PyQtGraph — Interactive and realtime 2D/3D/Image plotting and science/engineering widgets.
  • Seaborn — Statistical data visualization using Matplotlib.
  • VisPy — High-performance scientific visualization based on OpenGL.

Database

Databases implemented in Python.

  • pickleDB — A simple and lightweight key-value store for Python.
  • tinydb — A tiny, document-oriented database.
  • ZODB — A native object database for Python. A key-value and object graph database.

Database Drivers

Libraries for connecting and operating databases.

  • MySQL — awesome-mysql
    • mysqlclient — MySQL connector with Python 3 support (mysql-python fork).
    • PyMySQL — A pure Python MySQL driver compatible to mysql-python.
  • PostgreSQL — awesome-postgres
    • psycopg2 — The most popular PostgreSQL adapter for Python.
    • queries — A wrapper of the psycopg2 library for interacting with PostgreSQL.
  • Other Relational Databases
    • pymssql — A simple database interface to Microsoft SQL Server.
  • NoSQL Databases
    • cassandra-driver — The Python Driver for Apache Cassandra.
    • happybase — A developer-friendly library for Apache HBase.
    • kafka-python — The Python client for Apache Kafka.
    • py2neo — Python wrapper client for Neo4j’s restful interface.
    • pymongo — The official Python client for MongoDB.
    • redis-py — The Python client for Redis.
  • Asynchronous Clients
    • motor — The async Python driver for MongoDB.
    • Telephus — Twisted based client for Cassandra.
    • txpostgres — Twisted based asynchronous driver for PostgreSQL.
    • txRedis — Twisted based client for Redis.

Date and Time

Libraries for working with dates and times.

  • Chronyk — A Python 3 library for parsing human-written times and dates.
  • dateutil — Extensions to the standard Python datetime module.
  • delorean — A library for clearing up the inconvenient truths that arise dealing with datetimes.
  • moment — A Python library for dealing with dates/times. Inspired by Moment.js.
  • Pendulum — Python datetimes made easy.
  • PyTime — A easy-use Python module which aims to operate date/time/datetime by string.
  • pytz — World timezone definitions, modern and historical. Brings the tz database into Python.
  • when.py — Providing user-friendly functions to help perform common date and time actions.
  • maya — Datetimes for Humans.

Debugging Tools

Libraries for debugging code.

  • pdb-like Debugger
    • ipdb — IPython-enabled pdb.
    • pdb++ — Another drop-in replacement for pdb.
    • pudb — A full-screen, console-based Python debugger.
    • wdb — An improbable web debugger through WebSockets.
  • Tracing
    • lptrace — strace for Python programs.
    • manhole — Debugging UNIX socket connections and present the stacktraces for all threads and an interactive prompt.
    • pyringe — Debugger capable of attaching to and injecting code into Python processes.
    • python-hunter — A flexible code tracing toolkit.
  • Profiler
    • line_profiler — Line-by-line profiling.
    • memory_profiler — Monitor Memory usage of Python code.
    • profiling — An interactive Python profiler.
    • py-spy — A sampling profiler for Python programs. Written in Rust.
    • pyflame — A ptracing profiler For Python.
    • vprof — Visual Python profiler.
  • Others
    • icecream — Inspect variables, expressions, and program execution with a single, simple function call.
    • django-debug-toolbar — Display various debug information for Django.
    • django-devserver — A drop-in replacement for Django’s runserver.
    • flask-debugtoolbar — A port of the django-debug-toolbar to flask.
    • pyelftools — Parsing and analyzing ELF files and DWARF debugging information.

Deep Learning

Frameworks for Neural Networks and Deep Learning. Also see awesome-deep-learning.

  • caffe — A fast open framework for deep learning..
  • keras — A high-level neural networks library and capable of running on top of either TensorFlow or Theano.
  • mxnet — A deep learning framework designed for both efficiency and flexibility.
  • pytorch — Tensors and Dynamic neural networks in Python with strong GPU acceleration.
  • SerpentAI — Game agent framework. Use any video game as a deep learning sandbox.
  • tensorflow — The most popular Deep Learning framework created by Google.
  • Theano — A library for fast numerical computation.

DevOps Tools

Software and libraries for DevOps.

  • ansible — A radically simple IT automation platform.
  • cloudinit — A multi-distribution package that handles early initialization of a cloud instance.
  • cuisine — Chef-like functionality for Fabric.
  • docker-compose — Fast, isolated development environments using Docker.
  • fabric — A simple, Pythonic tool for remote execution and deployment.
  • fabtools — Tools for writing awesome Fabric files.
  • honcho — A Python clone of Foreman, for managing Procfile-based applications.
  • OpenStack — Open source software for building private and public clouds.
  • pexpect — Controlling interactive programs in a pseudo-terminal like GNU expect.
  • psutil — A cross-platform process and system utilities module.
  • saltstack — Infrastructure automation and management system.
  • supervisor — Supervisor process control system for UNIX.

Distributed Computing

Frameworks and libraries for Distributed Computing.

  • Batch Processing
    • PySpark — Apache Spark Python API.
    • dask — A flexible parallel computing library for analytic computing.
    • luigi — A module that helps you build complex pipelines of batch jobs.
    • mrjob — Run MapReduce jobs on Hadoop or Amazon Web Services.
    • Ray — A system for parallel and distributed Python that unifies the machine learning ecosystem.
  • Stream Processing
    • faust — A stream processing library, porting the ideas from Kafka Streams to Python.
    • streamparse — Run Python code against real-time streams of data via Apache Storm.

Distribution

Libraries to create packaged executables for release distribution.

  • dh-virtualenv — Build and distribute a virtualenv as a Debian package.
  • Nuitka — Compile scripts, modules, packages to an executable or extension module.
  • py2app — Freezes Python scripts (Mac OS X).
  • py2exe — Freezes Python scripts (Windows).
  • PyInstaller — Converts Python programs into stand-alone executables (cross-platform).
  • pynsist — A tool to build Windows installers, installers bundle Python itself.

Documentation

Libraries for generating project documentation.

  • sphinx — Python Documentation generator.
    • awesome-sphinxdoc
  • pdoc — Epydoc replacement to auto generate API documentation for Python libraries.
  • pycco — The literate-programming-style documentation generator.

Downloader

Libraries for downloading.

  • s3cmd — A command line tool for managing Amazon S3 and CloudFront.
  • s4cmd — Super S3 command line tool, good for higher performance.
  • you-get — A YouTube/Youku/Niconico video downloader written in Python 3.
  • youtube-dl — A small command-line program to download videos from YouTube.

E-commerce

Frameworks and libraries for e-commerce and payments.

  • alipay — Unofficial Alipay API for Python.
  • Cartridge — A shopping cart app built using the Mezzanine.
  • django-oscar — An open-source e-commerce framework for Django.
  • django-shop — A Django based shop system.
  • merchant — A Django app to accept payments from various payment processors.
  • money — Money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange.
  • python-currencies — Display money format and its filthy currencies.
  • forex-python — Foreign exchange rates, Bitcoin price index and currency conversion.
  • saleor — An e-commerce storefront for Django.
  • shoop — An open source E-Commerce platform based on Django.

Editor Plugins and IDEs

  • Emacs
    • elpy — Emacs Python Development Environment.
  • Sublime Text
    • anaconda — Anaconda turns your Sublime Text 3 in a full featured Python development IDE.
    • SublimeJEDI — A Sublime Text plugin to the awesome auto-complete library Jedi.
  • Vim
    • jedi-vim — Vim bindings for the Jedi auto-completion library for Python.
    • python-mode — An all in one plugin for turning Vim into a Python IDE.
    • YouCompleteMe — Includes Jedi-based completion engine for Python.
  • Visual Studio
    • PTVS — Python Tools for Visual Studio.


  • Visual Studio Code
    • Python — The official VSCode extension with rich support for Python.
  • IDE
    • PyCharm — Commercial Python IDE by JetBrains. Has free community edition available.
    • spyder — Open Source Python IDE.

Email

Libraries for sending and parsing email.

  • envelopes — Mailing for human beings.
  • flanker — A email address and Mime parsing library.
  • imbox — Python IMAP for Humans.
  • inbox.py — Python SMTP Server for Humans.
  • lamson — Pythonic SMTP Application Server.
  • Marrow Mailer — High-performance extensible mail delivery framework.
  • modoboa — A mail hosting and management platform including a modern and simplified Web UI.
  • Nylas Sync Engine — Providing a RESTful API on top of a powerful email sync platform.
  • yagmail — Yet another Gmail/SMTP client.

Environment Management

Libraries for Python version and virtual environment management.

  • pyenv — Simple Python version management.
  • pipenv — Python Development Workflow for Humans.
  • poetry — Python dependency management and packaging made easy.
  • virtualenv — A tool to create isolated Python environments.

Files

Libraries for file manipulation and MIME type detection.

  • mimetypes — (Python standard library) Map filenames to MIME types.
  • path.py — A module wrapper for os.path.
  • pathlib — (Python standard library) An cross-platform, object-oriented path library.
  • PyFilesystem2 — Python’s filesystem abstraction layer.
  • python-magic — A Python interface to the libmagic file type identification library.
  • Unipath — An object-oriented approach to file/directory operations.
  • watchdog — API and shell utilities to monitor file system events.

Foreign Function Interface

Libraries for providing foreign function interface.

  • cffi — Foreign Function Interface for Python calling C code.
  • ctypes — (Python standard library) Foreign Function Interface for Python calling C code.
  • PyCUDA — A Python wrapper for Nvidia’s CUDA API.
  • SWIG — Simplified Wrapper and Interface Generator.

Forms

Libraries for working with forms.

  • Deform — Python HTML form generation library influenced by the formish form generation library.
  • django-bootstrap3 — Bootstrap 3 integration with Django.
  • django-bootstrap4 — Bootstrap 4 integration with Django.
  • django-crispy-forms — A Django app which lets you create beautiful forms in a very elegant and DRY way.
  • django-remote-forms — A platform independent Django form serializer.
  • WTForms — A flexible forms validation and rendering library.

Functional Programming

Functional Programming with Python.

  • Coconut — Coconut is a variant of Python built for simple, elegant, Pythonic functional programming.
  • CyToolz — Cython implementation of Toolz: High performance functional utilities.
  • fn.py — Functional programming in Python: implementation of missing features to enjoy FP.
  • funcy — A fancy and practical functional tools.
  • Toolz — A collection of functional utilities for iterators, functions, and dictionaries.

GUI Development

Libraries for working with graphical user interface applications.

  • curses — Built-in wrapper for ncurses used to create terminal GUI applications.
  • Eel — A library for making simple Electron-like offline HTML/JS GUI apps.
  • enaml — Creating beautiful user-interfaces with Declaratic Syntax like QML.
  • Flexx — Flexx is a pure Python toolkit for creating GUI’s, that uses web technology for its rendering.
  • Gooey — Turn command line programs into a full GUI application with one line.
  • kivy — A library for creating NUI applications, running on Windows, Linux, Mac OS X, Android and iOS.
  • pyglet — A cross-platform windowing and multimedia library for Python.
  • PyGObject — Python Bindings for GLib/GObject/GIO/GTK+ (GTK+3).
  • PyQt — Python bindings for the Qt cross-platform application and UI framework.
  • PySimpleGUI — Wrapper for tkinter, Qt, WxPython and Remi.
  • pywebview — A lightweight cross-platform native wrapper around a webview component.
  • Tkinter — Tkinter is Python’s de-facto standard GUI package.
  • Toga — A Python native, OS native GUI toolkit.
  • urwid — A library for creating terminal GUI applications with strong support for widgets, events, rich colors, etc.
  • wxPython — A blending of the wxWidgets C++ class library with the Python.

Game Development

Awesome game development libraries.

  • Cocos2d — cocos2d is a framework for building 2D games, demos, and other graphical/interactive applications.
  • Harfang3D — Python framework for 3D, VR and game development.
  • Panda3D — 3D game engine developed by Disney.
  • Pygame — Pygame is a set of Python modules designed for writing games.
  • PyOgre — Python bindings for the Ogre 3D render engine, can be used for games, simulations, anything 3D.
  • PyOpenGL — Python ctypes bindings for OpenGL and it’s related APIs.
  • PySDL2 — A ctypes based wrapper for the SDL2 library.
  • RenPy — A Visual Novel engine.

Geolocation

Libraries for geocoding addresses and working with latitudes and longitudes.

  • django-countries — A Django app that provides a country field for models and forms.
  • GeoDjango — A world-class geographic web framework.
  • GeoIP — Python API for MaxMind GeoIP Legacy Database.
  • geojson — Python bindings and utilities for GeoJSON.
  • geopy — Python Geocoding Toolbox.
  • pygeoip — Pure Python GeoIP API.

HTML Manipulation

Libraries for working with HTML and XML.

  • BeautifulSoup — Providing Pythonic idioms for iterating, searching, and modifying HTML or XML.
  • bleach — A whitelist-based HTML sanitization and text linkification library.
  • cssutils — A CSS library for Python.
  • html5lib — A standards-compliant library for parsing and serializing HTML documents and fragments.
  • lxml — A very fast, easy-to-use and versatile library for handling HTML and XML.
  • MarkupSafe — Implements a XML/HTML/XHTML Markup safe string for Python.
  • pyquery — A jQuery-like library for parsing HTML.
  • untangle — Converts XML documents to Python objects for easy access.
  • WeasyPrint — A visual rendering engine for HTML and CSS that can export to PDF.
  • xmldataset — Simple XML Parsing.
  • xmltodict — Working with XML feel like you are working with JSON.

HTTP Clients

Libraries for working with HTTP.

  • grequests — requests + gevent for asynchronous HTTP requests.
  • httplib2 — Comprehensive HTTP client library.
  • requests — HTTP Requests for Humans™.
  • treq — Python requests like API built on top of Twisted’s HTTP client.
  • urllib3 — A HTTP library with thread-safe connection pooling, file post support, sanity friendly.

Hardware

Libraries for programming with hardware.

  • ino — Command line toolkit for working with Arduino.
  • keyboard — Hook and simulate global keyboard events on Windows and Linux.
  • mouse — Hook and simulate global mouse events on Windows and Linux.
  • Pingo — Pingo provides a uniform API to program devices like the Raspberry Pi, pcDuino, Intel Galileo, etc.
  • PyUserInput — A module for cross-platform control of the mouse and keyboard.
  • scapy — A brilliant packet manipulation library.
  • wifi — A Python library and command line tool for working with WiFi on Linux.

Image Processing

Libraries for manipulating images.

  • hmap — Image histogram remapping.
  • imgSeek — A project for searching a collection of images using visual similarity.
  • nude.py — Nudity detection.
  • pagan — Retro identicon (Avatar) generation based on input string and hash.
  • pillow — Pillow is the friendly PIL fork.
  • pyBarcode — Create barcodes in Python without needing PIL.
  • pygram — Instagram-like image filters.
  • python-qrcode — A pure Python QR Code generator.
  • Quads — Computer art based on quadtrees.
  • scikit-image — A Python library for (scientific) image processing.
  • thumbor — A smart imaging service. It enables on-demand crop, re-sizing and flipping of images.
  • wand — Python bindings for MagickWand, C API for ImageMagick.

Implementations

Implementations of Python.

  • CPython — Default, most widely used implementation of the Python programming language written in C.
  • Cython — Optimizing Static Compiler for Python.
  • CLPython — Implementation of the Python programming language written in Common Lisp.
  • Grumpy — More compiler than interpreter as more powerful CPython2.7 replacement (alpha).
  • IronPython — Implementation of the Python programming language written in C#.
  • Jython — Implementation of Python programming language written in Java for the JVM.
  • MicroPython — A lean and efficient Python programming language implementation.
  • Numba — Python JIT compiler to LLVM aimed at scientific Python.
  • PeachPy — x86-64 assembler embedded in Python.
  • Pyjion — A JIT for Python based upon CoreCLR.
  • PyPy — A very fast and compliant implementation of the Python language.
  • Pyston — A Python implementation using JIT techniques.
  • Stackless Python — An enhanced version of the Python programming language.

Interactive Interpreter

Interactive Python interpreters (REPL).

  • bpython — A fancy interface to the Python interpreter.
  • Jupyter Notebook (IPython) — A rich toolkit to help you make the most out of using Python interactively.
    • awesome-jupyter
  • ptpython — Advanced Python REPL built on top of the python-prompt-toolkit.

Internationalization

Libraries for working with i18n.

  • Babel — An internationalization library for Python.
  • PyICU — A wrapper of International Components for Unicode C++ library (ICU).

Job Scheduler

Libraries for scheduling jobs.

  • APScheduler — A light but powerful in-process task scheduler that lets you schedule functions.
  • django-schedule — A calendaring app for Django.
  • doit — A task runner and build tool.
  • gunnery — Multipurpose task execution tool for distributed systems with web-based interface.
  • Joblib — A set of tools to provide lightweight pipelining in Python.
  • Plan — Writing crontab file in Python like a charm.
  • schedule — Python job scheduling for humans.
  • Spiff — A powerful workflow engine implemented in pure Python.
  • TaskFlow — A Python library that helps to make task execution easy, consistent and reliable.
  • Airflow — Airflow is a platform to programmatically author, schedule and monitor workflows.

Logging

Libraries for generating and working with logs.

  • Eliot — Logging for complex & distributed systems.
  • logbook — Logging replacement for Python.
  • logging — (Python standard library) Logging facility for Python.
  • raven — Python client for Sentry, a log/error tracking, crash reporting and aggregation platform for web applications.

Machine Learning

Libraries for Machine Learning. Also see awesome-machine-learning.

  • H2O — Open Source Fast Scalable Machine Learning Platform.
  • Metrics — Machine learning evaluation metrics.
  • NuPIC — Numenta Platform for Intelligent Computing.
  • scikit-learn — The most popular Python library for Machine Learning.
  • Spark ML — Apache Spark’s scalable Machine Learning library.
  • vowpal_porpoise — A lightweight Python wrapper for Vowpal Wabbit.
  • xgboost — A scalable, portable, and distributed gradient boosting library.

Microsoft Windows

Python programming on Microsoft Windows.

  • Python(x,y) — Scientific-applications-oriented Python Distribution based on Qt and Spyder.
  • pythonlibs — Unofficial Windows binaries for Python extension packages.
  • PythonNet — Python Integration with the .NET Common Language Runtime (CLR).
  • PyWin32 — Python Extensions for Windows.
  • WinPython — Portable development environment for Windows 7/8.

Miscellaneous

Useful libraries or tools that don’t fit in the categories above.

  • blinker — A fast Python in-process signal/event dispatching system.
  • boltons — A set of pure-Python utilities.
  • itsdangerous — Various helpers to pass trusted data to untrusted environments.
  • pluginbase — A simple but flexible plugin system for Python.
  • tryton — A general purpose business framework.

Natural Language Processing

Libraries for working with human languages.

  • General
    • gensim — Topic Modelling for Humans.
    • langid.py — Stand-alone language identification system.
    • nltk — A leading platform for building Python programs to work with human language data.
    • pattern — A web mining module for the Python.
    • polyglot — Natural language pipeline supporting hundreds of languages.
    • pytext — A natural language modeling framework based on PyTorch.
    • PyTorch-NLP — A toolkit enabling rapid deep learning NLP prototyping for research.
    • spacy — A library for industrial-strength natural language processing in Python and Cython.
    • stanfordnlp — The Stanford NLP Group’s official Python library, supporting 50+ languages.
  • Chinese
    • jieba — The most popular Chinese text segmentation library.
    • pkuseg-python — A toolkit for Chinese word segmentation in various domains.
    • snownlp — A library for processing Chinese text.
    • funNLP — A collection of tools and datasets for Chinese NLP.

Network Virtualization

Tools and libraries for Virtual Networking and SDN (Software Defined Networking).

  • mininet — A popular network emulator and API written in Python.
  • pox — A Python-based SDN control applications, such as OpenFlow SDN controllers.


Networking

Libraries for networking programming.

  • asyncio — (Python standard library) Asynchronous I/O, event loop, coroutines and tasks.
    • awesome-asyncio
  • pulsar — Event-driven concurrent framework for Python.
  • pyzmq — A Python wrapper for the ZeroMQ message library.
  • Twisted — An event-driven networking engine.
  • napalm — Cross-vendor API to manipulate network devices.

News Feed

Libraries for building user’s activities.

  • django-activity-stream — Generating generic activity streams from the actions on your site.
  • Stream Framework — Building newsfeed and notification systems using Cassandra and Redis.

Libraries that implement Object-Relational Mapping or data mapping techniques.

  • Relational Databases
    • Django Models — A part of Django.
    • SQLAlchemy — The Python SQL Toolkit and Object Relational Mapper.
      • awesome-sqlalchemy
    • dataset — Store Python dicts in a database — works with SQLite, MySQL, and PostgreSQL.
    • orator — The Orator ORM provides a simple yet beautiful ActiveRecord implementation.
    • peewee — A small, expressive ORM.
    • pony — ORM that provides a generator-oriented interface to SQL.
    • pydal — A pure Python Database Abstraction Layer.
  • NoSQL Databases
    • hot-redis — Rich Python data types for Redis.
    • mongoengine — A Python Object-Document-Mapper for working with MongoDB.
    • PynamoDB — A Pythonic interface for Amazon DynamoDB.
    • redisco — A Python Library for Simple Models and Containers Persisted in Redis.

Package Management

Libraries for package and dependency management.

  • pip — The Python package and dependency manager.
    • PyPI
    • pip-tools — A set of tools to keep your pinned Python dependencies fresh.
  • conda — Cross-platform, Python-agnostic binary package manager.

Package Repositories

Local PyPI repository server and proxies.

  • warehouse — Next generation Python Package Repository (PyPI).
  • bandersnatch — PyPI mirroring tool provided by Python Packaging Authority (PyPA).
  • devpi — PyPI server and packaging/testing/release tool.
  • localshop — Local PyPI server (custom packages and auto-mirroring of pypi).

Permissions

Libraries that allow or deny users access to data or functionality.

  • django-guardian — Implementation of per object permissions for Django 1.2+
  • django-rules — A tiny but powerful app providing object-level permissions to Django, without requiring a database.

Processes

Libraries for starting and communicating with OS processes.

  • delegator.py — Subprocesses for Humans™ 2.0.
  • sarge — Yet another wrapper for subprocess.
  • sh — A full-fledged subprocess replacement for Python.

Queue

Libraries for working with event and task queues.

  • celery — An asynchronous task queue/job queue based on distributed message passing.
  • huey — Little multi-threaded task queue.
  • mrq — Mr. Queue — A distributed worker task queue in Python using Redis & gevent.
  • rq — Simple job queues for Python.

Recommender Systems

Libraries for building recommender systems.

  • annoy — Approximate Nearest Neighbors in C++/Python optimized for memory usage.
  • fastFM — A library for Factorization Machines.
  • implicit — A fast Python implementation of collaborative filtering for implicit datasets.
  • libffm — A library for Field-aware Factorization Machine (FFM).
  • lightfm — A Python implementation of a number of popular recommendation algorithms.
  • spotlight — Deep recommender models using PyTorch.
  • Surprise — A scikit for building and analyzing recommender systems.
  • tensorrec — A Recommendation Engine Framework in TensorFlow.

RESTful API

Libraries for developing RESTful APIs.

  • Django
    • django-rest-framework — A powerful and flexible toolkit to build web APIs.
    • django-tastypie — Creating delicious APIs for Django apps.
  • Flask
    • eve — REST API framework powered by Flask, MongoDB and good intentions.
    • flask-api-utils — Taking care of API representation and authentication for Flask.
    • flask-api — Browsable Web APIs for Flask.
    • flask-restful — Quickly building REST APIs for Flask.
    • flask-restless — Generating RESTful APIs for database models defined with SQLAlchemy.
  • Pyramid
    • cornice — A RESTful framework for Pyramid.
  • Framework agnostic
    • apistar — A smart Web API framework, designed for Python 3.
    • falcon — A high-performance framework for building cloud APIs and web app backends.
    • hug — A Python 3 framework for cleanly exposing APIs.
    • restless — Framework agnostic REST framework based on lessons learned from Tastypie.
    • ripozo — Quickly creating REST/HATEOAS/Hypermedia APIs.
    • sandman — Automated REST APIs for existing database-driven systems.

Robotics

Libraries for robotics.

  • PythonRobotics — This is a compilation of various robotics algorithms with visualizations.
  • rospy — This is a library for ROS (Robot Operating System).

RPC Servers

  • SimpleJSONRPCServer — This library is an implementation of the JSON-RPC specification.
  • SimpleXMLRPCServer — (Python standard library) Simple XML-RPC server implementation, single-threaded.
  • zeroRPC — zerorpc is a flexible RPC implementation based on ZeroMQ and MessagePack.

Science

Libraries for scientific computing. Also see Python-for-Scientists

  • astropy — A community Python library for Astronomy.
  • bcbio-nextgen — Providing best-practice pipelines for fully automated high throughput sequencing analysis.
  • bccb — Collection of useful code related to biological analysis.
  • Biopython — Biopython is a set of freely available tools for biological computation.
  • cclib — A library for parsing and interpreting the results of computational chemistry packages.
  • Colour — Implementing a comprehensive number of colour theory transformations and algorithms.
  • NetworkX — A high-productivity software for complex networks.
  • NIPY — A collection of neuroimaging toolkits.
  • NumPy — A fundamental package for scientific computing with Python.
  • Open Babel — A chemical toolbox designed to speak the many languages of chemical data.
  • ObsPy — A Python toolbox for seismology.
  • PyDy — Short for Python Dynamics, used to assist with workflow in the modeling of dynamic motion.
  • PyMC — Markov Chain Monte Carlo sampling toolkit.
  • QuTiP — Quantum Toolbox in Python.
  • RDKit — Cheminformatics and Machine Learning Software.
  • SciPy — A Python-based ecosystem of open-source software for mathematics, science, and engineering.
  • statsmodels — Statistical modeling and econometrics in Python.
  • SymPy — A Python library for symbolic mathematics.
  • Zipline — A Pythonic algorithmic trading library.
  • SimPy — A process-based discrete-event simulation framework.

Libraries and software for indexing and performing search queries on data.

  • elasticsearch-py — The official low-level Python client for Elasticsearch.
  • elasticsearch-dsl-py — The official high-level Python client for Elasticsearch.
  • django-haystack — Modular search for Django.
  • pysolr — A lightweight Python wrapper for Apache Solr.
  • whoosh — A fast, pure Python search engine library.

Serialization

Libraries for serializing complex data types

  • marshmallow — A lightweight library for converting complex objects to and from simple Python datatypes.
  • pysimdjson — A Python bindings for simdjson.
  • python-rapidjson — A Python wrapper around RapidJSON.

Serverless Frameworks

Frameworks for developing serverless Python code.

  • python-lambda — A toolkit for developing and deploying Python code in AWS Lambda.
  • Zappa — A tool for deploying WSGI applications on AWS Lambda and API Gateway.

Specific Formats Processing

Libraries for parsing and manipulating specific text formats.

  • General
    • tablib — A module for Tabular Datasets in XLS, CSV, JSON, YAML.
  • Office
    • openpyxl — A library for reading and writing Excel 2010 xlsx/xlsm/xltx/xltm files.
    • pyexcel — Providing one API for reading, manipulating and writing csv, ods, xls, xlsx and xlsm files.
    • python-docx — Reads, queries and modifies Microsoft Word 2007/2008 docx files.
    • python-pptx — Python library for creating and updating PowerPoint (.pptx) files.
    • unoconv — Convert between any document format supported by LibreOffice/OpenOffice.
    • XlsxWriter — A Python module for creating Excel .xlsx files.
    • xlwings — A BSD-licensed library that makes it easy to call Python from Excel and vice versa.
    • xlwt / xlrd — Writing and reading data and formatting information from Excel files.
  • PDF
    • PDFMiner — A tool for extracting information from PDF documents.
    • PyPDF2 — A library capable of splitting, merging and transforming PDF pages.
    • ReportLab — Allowing Rapid creation of rich PDF documents.
  • Markdown
    • Mistune — Fastest and full featured pure Python parsers of Markdown.
    • Python-Markdown — A Python implementation of John Gruber’s Markdown.
  • YAML
    • PyYAML — YAML implementations for Python.

  • CSV
    • csvkit — Utilities for converting to and working with CSV.
  • Archive
    • unp — A command line tool that can unpack archives easily.

Static Site Generator

Static site generator is a software that takes some text + templates as input and produces HTML files on the output.

  • mkdocs — Markdown friendly documentation generator.
  • pelican — Static site generator that supports Markdown and reST syntax.
  • lektor — An easy to use static CMS and blog engine.
  • nikola — A static website and blog generator.

Tagging

Libraries for tagging items.

Template Engine

Libraries and tools for templating and lexing.

  • Jinja2 — A modern and designer friendly templating language.
  • Genshi — Python templating toolkit for generation of web-aware output.
  • Mako — Hyperfast and lightweight templating for the Python platform.

Testing

Libraries for testing codebases and generating test data.

  • Testing Frameworks
    • pytest — A mature full-featured Python testing tool.
    • hypothesis — Hypothesis is an advanced Quickcheck style property based testing library.
    • nose2 — The successor to nose , based on `unittest2.
    • Robot Framework — A generic test automation framework.
    • unittest — (Python standard library) Unit testing framework.
  • Test Runners
    • green — A clean, colorful test runner.
    • mamba — The definitive testing tool for Python. Born under the banner of BDD.
    • tox — Auto builds and tests distributions in multiple Python versions
  • GUI / Web Testing
    • locust — Scalable user load testing tool written in Python.
    • PyAutoGUI — PyAutoGUI is a cross-platform GUI automation Python module for human beings.
    • Selenium — Python bindings for Selenium WebDriver.
    • sixpack — A language-agnostic A/B Testing framework.
    • splinter — Open source tool for testing web applications.
  • Mock
    • mock — (Python standard library) A mocking and patching library.
    • doublex — Powerful test doubles framework for Python.
    • freezegun — Travel through time by mocking the datetime module.
    • httmock — A mocking library for requests for Python 2.6+ and 3.2+.
    • httpretty — HTTP request mock tool for Python.
    • mocket — A socket mock framework with gevent/asyncio/SSL support.
    • responses — A utility library for mocking out the requests Python library.
    • VCR.py — Record and replay HTTP interactions on your tests.
  • Object Factories
    • factory_boy — A test fixtures replacement for Python.
    • mixer — Another fixtures replacement. Supported Django, Flask, SQLAlchemy, Peewee and etc.
    • model_mommy — Creating random fixtures for testing in Django.
  • Code Coverage
    • coverage — Code coverage measurement.
  • Fake Data
    • mimesis — is a Python library that help you generate fake data.
    • fake2db — Fake database generator.
    • faker — A Python package that generates fake data.
    • radar — Generate random datetime / time.

Text Processing

Libraries for parsing and manipulating plain texts.

  • General
    • chardet — Python 2/3 compatible character encoding detector.
    • difflib — (Python standard library) Helpers for computing deltas.
    • ftfy — Makes Unicode text less broken and more consistent automagically.
    • fuzzywuzzy — Fuzzy String Matching.
    • Levenshtein — Fast computation of Levenshtein distance and string similarity.
    • pangu.py — Paranoid text spacing.
    • pyfiglet — An implementation of figlet written in Python.
    • pypinyin — Convert Chinese hanzi (漢字) to pinyin (拼音).
    • textdistance — Compute distance between sequences with 30+ algorithms.
    • unidecode — ASCII transliterations of Unicode text.
  • Slugify
    • awesome-slugify — A Python slugify library that can preserve unicode.
    • python-slugify — A Python slugify library that translates unicode to ASCII.
    • unicode-slugify — A slugifier that generates unicode slugs with Django as a dependency.
  • Unique identifiers
    • hashids — Implementation of hashids in Python.
    • shortuuid — A generator library for concise, unambiguous and URL-safe UUIDs.
  • Parser
    • ply — Implementation of lex and yacc parsing tools for Python.
    • pygments — A generic syntax highlighter.
    • pyparsing — A general purpose framework for generating parsers.
    • python-nameparser — Parsing human names into their individual components.
    • python-phonenumbers — Parsing, formatting, storing and validating international phone numbers.
    • python-user-agents — Browser user agent parser.
    • sqlparse — A non-validating SQL parser.

Third-party APIs

Libraries for accessing third party services APIs. Also see List of Python API Wrappers and Libraries.

  • apache-libcloud — One Python library for all clouds.
  • boto3 — Python interface to Amazon Web Services.
  • django-wordpress — WordPress models and views for Django.
  • facebook-sdk — Facebook Platform Python SDK.
  • google-api-python-client — Google APIs Client Library for Python.
  • gspread — Google Spreadsheets Python API.
  • twython — A Python wrapper for the Twitter API.

URL Manipulation

Libraries for parsing URLs.

  • furl — A small Python library that makes parsing and manipulating URLs easy.
  • purl — A simple, immutable URL class with a clean API for interrogation and manipulation.
  • pyshorteners — A pure Python URL shortening lib.
  • webargs — A friendly library for parsing HTTP request arguments with built-in support for popular web frameworks.

Video

Libraries for manipulating video and GIFs.

  • moviepy — A module for script-based movie editing with many formats, including animated GIFs.
  • scikit-video — Video processing routines for SciPy.

WSGI Servers

WSGI-compatible web servers.

  • bjoern — Asynchronous, very fast and written in C.
  • gunicorn — Pre-forked, partly written in C.
  • uWSGI — A project aims at developing a full stack for building hosting services, written in C.
  • waitress — Multi-threaded, powers Pyramid.
  • werkzeug — A WSGI utility library for Python that powers Flask and can easily be embedded into your own projects.

Web Asset Management

Tools for managing, compressing and minifying website assets.

  • django-compressor — Compresses linked and inline JavaScript or CSS into a single cached file.
  • django-pipeline — An asset packaging library for Django.
  • django-storages — A collection of custom storage back ends for Django.
  • fanstatic — Packages, optimizes, and serves static file dependencies as Python packages.
  • fileconveyor — A daemon to detect and sync files to CDNs, S3 and FTP.
  • flask-assets — Helps you integrate webassets into your Flask app.
  • webassets — Bundles, optimizes, and manages unique cache-busting URLs for static resources.

Web Content Extracting

Libraries for extracting web contents.

  • html2text — Convert HTML to Markdown-formatted text.
  • lassie — Web Content Retrieval for Humans.
  • micawber — A small library for extracting rich content from URLs.
  • newspaper — News extraction, article extraction and content curation in Python.
  • python-readability — Fast Python port of arc90’s readability tool.
  • requests-html — Pythonic HTML Parsing for Humans.
  • sumy — A module for automatic summarization of text documents and HTML pages.
  • textract — Extract text from any document, Word, PowerPoint, PDFs, etc.
  • toapi — Every web site provides APIs.

Web Crawling

Libraries to automate web scraping.

  • cola — A distributed crawling framework.
  • feedparser — Universal feed parser.
  • grab — Site scraping framework.
  • MechanicalSoup — A Python library for automating interaction with websites.
  • pyspider — A powerful spider system.
  • robobrowser — A simple, Pythonic library for browsing the web without a standalone web browser.
  • scrapy — A fast high-level screen scraping and web crawling framework.
  • portia — Visual scraping for Scrapy.

Web Frameworks

Full stack web frameworks.

  • Django — The most popular web framework in Python.
    • awesome-django
  • Flask — A microframework for Python.
    • awesome-flask
  • Masonite — The modern and developer centric Python web framework.
  • Pyramid — A small, fast, down-to-earth, open source Python web framework.
    • awesome-pyramid
  • Sanic — Web server that’s written to go fast.
  • Vibora — Fast, efficient and asynchronous Web framework inspired by Flask.
  • Tornado — A Web framework and asynchronous networking library.

WebSocket

Libraries for working with WebSocket.

  • autobahn-python — WebSocket & WAMP for Python on Twisted and asyncio.
  • crossbar — Open-source Unified Application Router (Websocket & WAMP for Python on Autobahn).
  • django-channels — Developer-friendly asynchrony for Django.
  • django-socketio — WebSockets for Django.
  • WebSocket-for-Python — WebSocket client and server library for Python 2 and 3 as well as PyPy.

Services

Online tools and APIs to simplify development.

Continuous Integration

  • CircleCI — A CI service that can run very fast parallel testing.
  • Travis CI — A popular CI service for your open source and private projects. (GitHub only)
  • Vexor CI — A continuous integration tool for private apps with pay-per-minute billing model.
  • Wercker — A Docker-based platform for building and deploying applications and microservices.

Code Quality

  • Codacy — Automated Code Review to ship better code, faster.
  • Codecov — Code coverage dashboard.
  • CodeFactor — Automated Code Review for Git.
  • Landscape — Hosted continuous Python code metrics.
  • PEP 8 Speaks — GitHub integration to review code style.

Resources

Where to discover new Python libraries.

Podcasts

Twitter

Websites

Weekly

Contributing

Your contributions are always welcome! Please take a look at the contribution guidelines first.

I will keep some pull requests open if I’m not sure whether those libraries are awesome, you could vote for them by adding :+1: to them. Pull requests will be merged when their votes reach 20.

If you have any question about this opinionated list, do not hesitate to contact me @vinta on Twitter or open an issue on GitHub.

vedavrata

Антон Кузнецов (Ведаврат) — Мастер Тантра-Джйотиша

Антон Кузнецов Ведаврат (Vedavrat) — Мастер и Учитель науки Тантра-Джйотиш [Ведическая астрология]

Правильно ли я понимаю, что если мне нужна CMS на Питоне, то я могу взять в качестве готовой, например, такую как Plone, потому что иерархия такая «Python -> Zope -> Content Management Framework (CMF) -> Plone» .
[то есть на Python написан Zope; из Zope сделали CMF; а на CMF создан Plone, да?]

И что можете сказать о Plone вообще.

А о django?
Ведь django — это уже законченная CMS верхнего уровня?

Что можете сказать о следущих системах:
* Web.py
* Pyjamas
* web2py
* Pylons
* CherryPy
* Silva
* icoya
.

Что из них CMS, а что Framework-и.
Чем следует пользоваться? А чем нет? И почему?

Django CMS Обучение

пятница, 24 августа 2012 г.

Python Примеры программ

Запуск Python из консоли командной строки и выход из него.

1. Пуск > Все программы > Стандартные > Командная строка
2. Далее в «черном квадрате» командной строки набираете:

и нажимаете Enter.

Это команда смены директории. В результате вы попадете в папку Python27, в которую был установлен ваш Python. Если при установке вы ничего не меняли, то в таком случае Python был установлен на диск С.

Python27 это версия программы. Цифры могут быть разные в зависимости от вашей версии.

3. Далее вводите в командную строку

и нажимаете Enter. В результате Python начнет работать.

4. Для того, чтобы выйти из Python, находясь в консоли нажмите Ctrl + Z и затем нажмите Enter.

Запуск из консоли программы, написанной на языке Python и хранящейся в отдельном файле на жестком диске.

Из консоли вы можете запустить программу, написанную на языке Python, код которой хранится в отдельном файле на жестком диске. (Python при этом запускать не надо.) Для этого в консоли наберите команду

cd C:\Путь до папки с вашим файлом\

и нажмите Enter.

В результате вы перейдете в папку, в которой хранится ваш файл с программой.

Наберите в консоли название вашего файла, например

my_programm.py
(или python my_programm.py)

и нажмите Enter.

В результате, код программы из файла будет выполнен и ваша программа запустится из консоли.

Так же вы можете запустить вашу программу, написанную на языке Python, перетаскиванием иконки файла с кодом программы в окно консоли командной строки. При этом в командной строке автоматически появится путь до файла. После этого нажмите Enter и ваша программа запустится. Python при этом запускать не надо.

Команды Python.

Для отделения команд друг от друга в Python используются обязательные переходы на следующую строку и отступы перед командами в виде 4-х пробелов.

# — это однострочный комментарий.
# Многострочных комментариев в Python нет.
# Для многострочных комментариев каждую строку
# необходимо начинать с символа #.

# Ниже расположен код, который обеспечивает правильную обработку
# русских букв в коде вашей программы.
# Без этого кода возникнет ошибка и программа не запустится.
# Данный код должен размещаться в самом начале вашего файла с программой.

+ # это символ сложения
— # это символ вычитания
* # это символ умножения
/ # это символ деления
% # это символ получения остатка от деления

# это символ больше чем
= # это символ больше чем или равно этому
== # это символ равно
!= # это символ неравно

and # это символ логического и
or # это символ логического или
not # это символ логического не

# Создание переменных и действия над ними.

cars = 100.0
drivers = 30.0
cars_without_drivers = cars — drivers
car_color = «Красный»
boat_color = «Синий»
what_color = «Какой цвет у машины? %r»
water = True
gas = False

# Вывод текста на экран.

print «Данный текст будет выведен на экран.»
print ‘В коде программы можно использовать как двойные, так и одинарные кавычки.’
print gas
print «Результат вычисления равен: «, (100 — 50 + 10) / 60 * 30
print «Два меньше, чем пять? «, 2 \\ Обратная косая черта (\) \’ Одинарная кавычка (‘) \» Двойная кавычка («) \a ASCII Bell (BEL) \b ASCII Backspace (BS) \f ASCII Formfeed (FF) \n ASCII Linefeed (LF) \N Character named name in the Unicode database (Unicode only) \r ASCII Переход на следующую строку \t ASCII Табуляция \uxxxx Character with 16-bit hex value xxxx (Unicode only) \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) \v ASCII Vertical Tab (VT) \ooo Character with octal value ooo \xhh Character with hex value hh

# Ввод данных из консоли и запись их в переменные.

print «Сколько вам лет?»
age = raw_input()
print «Какой у вас рост?»
height = raw_input()
print «Какой у вас вес?»
weight = raw_input()
print «Вам %r лет, ваш рост %r сантиметров и ваш вес равен %r килограмм.» % (age, height, weight)
print «Данные из консоли берутся как строки. Поэтому используется форматер %r»
print «Для преобразования вводимых данных в числа воспользуйтесь следующим кодом:»
digits = int(raw_input())
print «%d — это числовые данные» % digits
# Стоит избегать использование просто функции input() для ввода данных, из-за того, что она не всегда работает правильно.
name = raw_input («Как вас зовут? «)
print name

# Подстановка значений в программу при её запуске из консоли

Перенесите в ваш файл следующий код:

from sys import argv

script, first, second, third = argv

print «Вызван script: «, script
print «Ваша перевая переменная это: «, first
print «Ваша вторая переменная это: «, second
print «Ваша третья переменная это: «, third

Введите в консоли имя вашего файла и список модулей:
my_programm.py first 2nd 3rd
и нажмите Enter.

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

# Чтение содержимого текстового файла и вывод его на экран.

Создайте текстовый файл с именем sample.txt и поместите его в папку с вашей программой my_programm.py.

В файл sample.txt вставьте следующий текст:

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

Далее откройте файл с вашей программой и введите в него следующий код:

from sys import argv

script, filename = argv

print «Мы открываем файл %r и выводим из него следующий текст:» % filename
print txt.read()

Теперь откройте консоль и запустите вашу программу с параметром соотвествующим имени вашего файла с текстом (sample.txt):

В результате выполнения вашей программы содержимое файла sample.txt будет выведено на экран.

# Чтение и запись данных в файлы

Основные команды чтения и записи данных в файлы:
read() — читает содержимое файла, которое может быть также присвоено переменной.
readline() — считывает только одну строку из файла.
truncate() — удаляет все содержимое из файла.
write(«текстовое содержимое») — записывает текстовое содержимое в файл.
close() — закрывает файл. (Аналогично команде File->Save.. в вашем текстовом редакторе.)

Запустите вашу программу my_programm.py, вставив в неё следующий код:

filename = raw_input («Введите имя файла:»)
target = open (filename, «w») # «w» означает открыть файл с разрешением на запись

print «Сейчас мы удалим все содержимое из файла %r.» % filename
target.truncate()

line1 = raw_input(«Строка 1:»)
line2 = raw_input(«Строка 2:»)
line3 = raw_input(«Строка 3:»)

print «Теперь мы запишем в файл введенные строки.»

target.write(line1)
target.write(«\n»)
target.write(line2)
target.write(«\n»)
target.write(line3)
target.write(«\n»)

print «Далее мы закроем файл.»

Парамеры функции open()
«r» — открыть файл только для чтения.
«w» — открыть файл для записи.
«a» — открыть файл для добавления в него нового фрагмента.

# Копирование содержимого из одного файла в другой файл.

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print «Сейчас мы скопируем содержимое из файла %r в файл %r.» % (from_file, to_file)

first_file = open(from_file)
file_content = open_from_file.read()

print «Содержимое копируемого файла занимает %d байт.» % len(file_content)

print «Существует ли файл, в который мы будем вставлять содержимое? %r» % exists(to_file)

second_file = open(to_file, ‘w’)
second_file.write(file_content)

print «Копирование успешно завершено.»

При запуске программы из коносли добавьте имя любого файла, из которого будет скопировано содержимое, и имя любого файла, в который оно будет вставлено:

my_programm.py copy.txt paste.txt

the_count = [1, 2, 3, 4, 5]
fruits = [‘apples’, ‘oranges’, ‘pears’, ‘apricots’]
change = [1, ‘pennies’, 2, ‘dimes’, 3, ‘quarters’]
change[0] = ‘one’
print change[0]
print the_count

# Хэш — массивы — словари

cities = <
‘CA’: ‘San Francisco’,
‘MI’: ‘Detroit’,
‘FL’: ‘Jacksonville’
>

# Добавим еще значения в массив.
cities[‘NY’] = ‘New York’
cities[‘OR’] = ‘Portland’

# Выведем некотрые значения из массива на экран.
print «NY — это: «, cities[‘NY’]
print «OR — это: «, cities[‘OR’]

for abbrev, city in cities.items():
print «%s соотвествует городу %s» % (abbrev, city)

city = cities.get(‘Texas’, None)

if not city:
print «Простите, но Texas нет в массиве.»

Learn Python Programming

Python is a powerful multi-purpose programming language created by Guido van Rossum.

It has simple easy-to-use syntax, making it the perfect language for someone trying to learn computer programming for the first time.

This is a comprehensive guide on how to get started in Python, why you should learn it and how you can learn it.

However, if you have knowledge of other programming languages and want to quickly get started with Python, visit Python tutorial page.

Learn Python programming from the ease of your phone.


Python Tutorials

Introduction

Flow Control

Functions

Datatypes

File Handling

Object & Class

Additional Tutorials

Get latest updates, articles and tutorials on Python programming.

You have successfully subscribed to our Python newsletter.

What is Python (Programming)? — The Basics

Before getting started, lets get familiarized with the language first.

Python is a general-purpose language. It has wide range of applications from Web development (like: Django and Bottle), scientific and mathematical computing (Orange, SymPy, NumPy) to desktop graphical user Interfaces (Pygame, Panda3D).

The syntax of the language is clean and length of the code is relatively short. It’s fun to work in Python because it allows you to think about the problem rather than focusing on the syntax.

More information on Python Language:

History of Python

Python is a fairly old language created by Guido Van Rossum. The design began in the late 1980s and was first released in February 1991.

Why Python was created?

In late 1980s, Guido Van Rossum was working on the Amoeba distributed operating system group. He wanted to use an interpreted language like ABC (ABC has simple easy-to-understand syntax) that could access the Amoeba system calls. So, he decided to create a language that was extensible. This led to design of a new language which was later named Python.

Why the name Python?

No. It wasn’t named after a dangerous snake. Rossum was fan of a comedy series from late seventies. The name «Python» was adopted from the same series «Monty Python’s Flying Circus».

Release Dates of Different Versions

Version Release Data
Python 1.0 (first standard release)
Python 1.6 (Last minor version)
January 1994
September 5, 2000
Python 2.0 (Introduced list comprehensions)
Python 2.7 (Last minor version)
October 16, 2000
July 3, 2010
Python 3.0 (Emphasis on removing duplicative constructs and module)
Python 3.5 (Last updated version)
December 3, 2008
September 13, 2015

Features of Python Programming

  1. A simple language which is easier to learn
    Python has a very simple and elegant syntax. It’s much easier to read and write Python programs compared to other languages like: C++, Java, C#. Python makes programming fun and allows you to focus on the solution rather than syntax.
    If you are a newbie, it’s a great choice to start your journey with Python.
  2. Free and open-source
    You can freely use and distribute Python, even for commercial use. Not only can you use and distribute softwares written in it, you can even make changes to the Python’s source code.
    Python has a large community constantly improving it in each iteration.
  3. Portability
    You can move Python programs from one platform to another, and run it without any changes.
    It runs seamlessly on almost all platforms including Windows, Mac OS X and Linux.
  4. Extensible and Embeddable
    Suppose an application requires high performance. You can easily combine pieces of C/C++ or other languages with Python code.
    This will give your application high performance as well as scripting capabilities which other languages may not provide out of the box.
  5. A high-level, interpreted language
    Unlike C/C++, you don’t have to worry about daunting tasks like memory management, garbage collection and so on.
    Likewise, when you run Python code, it automatically converts your code to the language your computer understands. You don’t need to worry about any lower-level operations.
  6. Large standard libraries to solve common tasks
    Python has a number of standard libraries which makes life of a programmer much easier since you don’t have to write all the code yourself. For example: Need to connect MySQL database on a Web server? You can use MySQLdb library using import MySQLdb .
    Standard libraries in Python are well tested and used by hundreds of people. So you can be sure that it won’t break your application.
  7. Object-oriented
    Everything in Python is an object. Object oriented programming (OOP) helps you solve a complex problem intuitively.
    With OOP, you are able to divide these complex problems into smaller sets by creating objects.

Applications of Python

Web Applications

You can create scalable Web Apps using frameworks and CMS (Content Management System) that are built on Python. Some of the popular platforms for creating Web Apps are: Django, Flask, Pyramid, Plone, Django CMS.

Sites like Mozilla, Reddit, Instagram and PBS are written in Python.

Scientific and Numeric Computing

There are numerous libraries available in Python for scientific and numeric computing. There are libraries like: SciPy and NumPy that are used in general purpose computing. And, there are specific libraries like: EarthPy for earth science, AstroPy for Astronomy and so on.

Also, the language is heavily used in machine learning, data mining and deep learning.

Creating software Prototypes

Python is slow compared to compiled languages like C++ and Java. It might not be a good choice if resources are limited and efficiency is a must.

However, Python is a great language for creating prototypes. For example: You can use Pygame (library for creating games) to create your game’s prototype first. If you like the prototype, you can use language like C++ to create the actual game.

Good Language to Teach Programming

Python is used by many companies to teach programming to kids and newbies.

It is a good language with a lot of features and capabilities. Yet, it’s one of the easiest language to learn because of its simple easy-to-use syntax.

Reasons to Choose Python as First Language

  1. Simple Elegant Syntax

Programming in Python is fun. It’s easier to understand and write Python code. Why? The syntax feels natural. Take this source code for an example:
Even if you have never programmed before, you can easily guess that this program adds two numbers and prints it.
Not overly strict

You don’t need to define the type of a variable in Python. Also, it’s not necessary to add semicolon at the end of the statement.

Python enforces you to follow good practices (like proper indentation). These small things can make learning much easier for beginners.
Expressiveness of the language

Python allows you to write programs having greater functionality with fewer lines of code. Here’s a link to the source code of Tic-tac-toe game with a graphical interface and a smart computer opponent in less than 500 lines of code. This is just an example. You will be amazed how much you can do with Python once you learn the basics.
Great Community and Support

Python has a large supporting community. There are numerous active forums online which can be handy if you are stuck. Some of them are:

  • Learn Python subreddit
  • Google Forum for Python
  • Python Questions — Stack Overflow

Run Python on Your Operating System

You will find the easiest way to run Python on your computer (Windows, Mac OS X or Linux) in this section.

Install and Run Python in Mac OS X

  1. Go to Download Python page on the official site and click Download Python 3.6.0 (You may see different version name).
  2. When the download is complete, open the package and follow the instructions. You will see «The installation was successful» message when Python is successfully installed.
  3. It’s recommended to download a good text editor before you get started. If you are a beginner, I suggest you to download Sublime Text. It’s free.
  4. The installation process is straight forward. Run the Sublime Text Disk Image file you downloaded and follow the instructions.
  5. Open Sublime Text and go to File > New File (Shortcut: Cmd+N). Then, save (Cmd+S or File > Save) the file with .py extension like: hello.py or first-program.py
  6. Write the code and save it again. For starters, you can copy the code below: This simple program outputs «Hello, World!»
  7. Go to Tool > Build (Shortcut: Cmd + B). You will see the output at the bottom of Sublime Text.Congratulations, you’ve successfully run your first Python program.

Install and Run Python in Linux (Ubuntu)

  1. Install the following dependencies:
  2. Go to Download Python page on the official site and click Download Python 3.6.0 (You may see different version name).
  3. In the terminal, go to the directory where the file is downloaded and run the command: This will extract your zipped file. Note: The filename will be different if you’ve downloaded a different version. Use the appropriate filename.
  4. Go to the extracted directory.
  5. Issue the following commands to compile Python source code on your Operating system.
  6. We recommend you to install Sublime Text if you are a newbie. To install Sublime Text in Ubuntu (on 14.04). Issue following commands.
  7. Open Sublime text. To create a new file, go to File > New File (Shortcut: Ctrl+N).
  8. Save the file with .py file extension like: hello.py or first-program.py
  9. Write the code and save it (Ctrl+S or File > Save) . For starters, you can copy the code below: This simple program outputs «Hello, World!»
  10. Go to Tool > Build (Shortcut: Ctrl+B). You will see the output at the bottom of Sublime Text. Congratulations, you’ve successfully run your first Python program.

Install and Run Python in Windows

  1. Go to Download Python page on the official site and click Download Python 3.6.0 (You may see different version name).
  2. When the download is completed, double-click the file and follow the instructions to install it.
    When Python is installed, a program called IDLE is also installed along with it. It provides graphical user interface to work with Python.
  3. Open IDLE, copy the following code below and press enter.
  4. To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).
  5. Write Python code (you can copy the code below for now) and save (Shortcut: Ctrl+S) with .py file extension like: hello.py or your-first-program.py
  6. Go to Run > Run module (Shortcut: F5) and you can see the output. Congratulations, you’ve successfully run your first Python program.

Your First Python Program

Often, a program called «Hello, World!» is used to introduce a new programming language to beginners. A «Hello, World!» is a simple program that outputs «Hello, World!».

However, Python is one of the easiest language to learn, and creating «Hello, World!» program is as simple as writing print(«Hello, World!») . So, we are going to write a different program.

Program to Add Two Numbers

How this program works?

Line 1: # Add two numbers

Any line starting with # in Python programming is a comment.

Comments are used in programming to describe the purpose of the code. This helps you as well as other programmers to understand the intent of the code. Comments are completely ignored by compilers and interpreters.

Here, num1 is a variable. You can store a value in a variable. Here, 3 is stored in this variable.

Similarly, 5 is stored in num2 variable.

Line 4: sum = num1+num2

The variables num1 and num2 are added using + operator. The result of addition is then stored in another variable sum .

Line 5: print(sum)

The print() function prints the output to the screen. In our case, it prints 8 on the screen.

Few Important Things to Remember

To represent a statement in Python, newline (enter) is used. The use of semicolon at the end of the statement is optional (unlike languages like C/C++, PHP). In fact, it’s recommended to omit semicolon at the end of the statement in Python.

Instead of curly braces < >, indentations are used to represent a block.

Teach Yourself to Code in Python

Learn Python from Programiz

Programiz offers dozens of Python tutorials and examples to help you learn Python programming from scratch.

Our tutorials are designed for beginners who do not have any prior knowledge of Python (or, any other programming languages). Each tutorial is written in depth with examples and detailed explanation.

We also encourage you to try our examples and run it. Once you understand the program, modify it and try to create something new. This is the best way to learn programming.

If you are serious about learning programming, you should get yourself a good book.

Granted, reading a programming book takes a lot of time and patience. But, you will get the big picture of programming concepts in the book which you may not find elsewhere.

Think Python: How to Think Like a Computer Scientist

If you have never programmed before, this book is for you. This book assumes that you have very little knowledge of programming and will provide everything you need to get started with Python.

Don’t skip the exercises provided in each chapter.

Starting out With Python

A well-written book with a lot of examples.

This book is easy to understand even for complete beginners. Since, the content is well organized, it’s a good book to have for future reference.

Effective Python: 59 Specific Ways to Write Better Python

Python is easy to get started with. However, there are many awesome features you may not be aware of, and hidden pitfalls you want to avoid.

«Effective Python» helps you to utilize the power of Python in the right way. Want to write robust, efficient and maintainable code in Python? You should definitely give this book a try.

Final Words

Python is a terrific language. The syntax is simple and code length is short which makes is easy to understand and write.

If you are getting started in programming, Python is an awesome choice. You will be amazed how much you can do in Python once you know the basics.

It’s easy to overlook the fact that Python is a powerful language. Not only is it good for learning programming, it’s also a good language to have in your arsenal. Change your idea into a prototype or create games or get started with data Science, Python can help you in everything to get started.

Python CMS

Powerful CMS. Zero headache.

Drop our API-based CMS into your Python app in minutes.

«Best CMS on the market»

ButterCMS is an API-based CMS that integrates with Python apps in minutes. Use ButterCMS with Flask, Django, or other Python apps to build CMS-powered apps quickly. Butter is great for blogs, dynamic pages, and more.

Above is quick video of integrating Butter’s Pages API into an application.

Butter’s API slides right into our apps and lets us avoid having yet another WordPress site.

Daniel, Founder of Collective Idea

Marketers love Butter

  • SEO Landing Pages
  • Customer Case Studies
  • Company News & Updates
  • Events + Webinar Pages
  • Education Center
  • Location Pages
  • and more.

Butter saves you development time

Save thousands of dollars worth of development time with our easy setup.

Integrating Butter into our application took less than an hour and most of that time was spent on design work.

Luke Brean, Legally

Everything you need

  • Custom Page Types
  • Custom Content Modeling
  • Preview changes
  • Media library
  • CDN for assets
  • Testing environment
  • Localization
  • Webhooks

Beautiful admin interface

Easy to use. Easy to customize.

Integrates with Python

Our CMS has a simple content API and drop-in Python SDK.

Butter requires zero maintenance

Never worry about security upgrades, hosting, or performance.

Setup in minutes

Integrating Butter into your Python app is dead simple. Here’s a mini tutorial to get a feel for adding marketing pages to your app. You can also use our Content Fields to do advanced content modeling. For full a integration guide check out our Official Python Guide

First you would set up a new Customer Case Study page type in Butter and create a page. With your page defined, the ButterCMS API will return it in JSON format like this:

To create these pages in our app, we create a route that fetches content for the page by using a URL slug parameter:

About ButterCMS

ButterCMS is an API-based, or «headless», CMS. We’re a hosted service and we maintain all of the infrastructure. For more information on how we compare to a traditional CMS check out API-based CMS vs Traditional CMS.

How do you compare to WordPress?

In short, we offer all the same easy-to-use editing capabilities of WordPress but are significantly easier for developers to setup and maintain. This means you spend less time working on your CMS and more time focusing on things important to your business.

Do you host my templates?

Unlike CMS’s you might be used to, we don’t control or host any of your templates. The design of your app (HTML + CSS) lives in your application along side the rest of your app. Your application calls our Content API and we return your content in JSON format. You can then render this content in any way you’d like.

Can I import my content?

Yep. To import existing content from another platform, simply send us an email.

What kind of database can I use?

No database required! We’re a SaaS CMS or CaaS. You simply call our Content API from your app. We host and maintain all of the CMS infrastructure.

Can I host this?

No, we’re a SaaS CMS or CaaS. You simply call our Content API from your app. We host and maintain all of the CMS infrastructure.

I have other questions

We’re happy to help.

About Python

Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991.

Цукерберг рекомендует:  Визуальный анализ данных с Orange3. Классификационные задачи
Понравилась статья? Поделиться с друзьями:
Все языки программирования для начинающих