Python to Debian package: Simple, Easy and Fast

Packaging python script to Debian follows strict instructions, using the following instructions, most of the steps can be skipped hence making it easy and fast.
If you like video go to https://www.youtube.com/watch?v=a9GzDZB5VeU. This video doesn't show setup.py file creating which is required, but excluding that portion everything is same as below.

Lets convert this mymood.py into deb package.

import time
def analyze():
    try:
        print '\nHello! I am Dr.Psycho, your mood analyzer:)'
        print 'Answer me:'
        time.sleep(2)
        answer_list = []
        def validate_ans(ans):
           try:
               ans = int(ans)
               print ans
               if ans not in [1, 2]:
                   print 'Enter 1 or 2\n'
                   return None
               elif ans == 1:
                   return ans
               elif ans == 2:
                   return 0
           except Exception:
               print 'Enter 1 or 2\n'
               return None
        print '\nHow many questions can you answer?'
        print '1. More than 20\n2. Less than 10'
        ans = raw_input()
        while True:
            ans = validate_ans(ans)
            if ans != None:
                break
            ans = raw_input()
        answer_list.append(ans)
        print '\nYou are the worst thing ever existed?'
        print '1. Nope\n2. Kind of'
        ans = raw_input()
        while True:
            ans = validate_ans(ans)
            if ans != None:
                break
            ans = raw_input()
        answer_list.append(ans)
        print '\nAre you searching for meaning of life?'
        print '1. I dont\n2. Yes, I will find it some day'
        ans = raw_input()
        while True:
            ans = validate_ans(ans)
            if ans != None:
                break
            ans = raw_input()
        answer_list.append(ans)
        print '\nLast question. Do you feel happy if everyone died except you?'
        print '1. Not at all \n2. Oh yes'
        ans = raw_input()
        while True:
            ans = validate_ans(ans)
            if ans != None:
                break
            ans = raw_input()
        answer_list.append(ans)
        print '\nHow does this yet another question feel?'
        print '1. smiling\n2. *******\n'
        ans = raw_input()
        while True:
            ans = validate_ans(ans)
            if ans != None:
                break
            ans = raw_input()
        answer_list.append(ans)
        score = sum(answer_list)
        if score == 0:
            mood_status = 'You are totally messed up, Better consult psychiatrist'
        elif score == 1:
            mood_status = 'Very frustrated'
        elif score == 3:
            mood_status = 'Bored and depressed'
        elif score in [3, 4]:
            mood_status = 'Normal'
        elif score == 5:
            mood_status = 'Enlightened'
        print '\nDr. Psycho thanks for your patience. \nYour mood: %s' % mood_status
    except KeyboardInterrupt:
        print '\nBye :('

Project Structure:

mymood
  debian
    changelog
    compat
    control
    rules
    copyright
  mymood
    __init__.py
    mymood.py
    command_line.py
  README.md
  setup.py

Don't create the above structure, it will be created as you go through below steps.

1. Creating mymood and its sub directories:

$mkdir mymood
$cd mymood
$mkdir debian
$mkdir mymood

2. Setting up mymood/mymood directory:

Goto mymood/mymood directory and paste mymood.py script as shown in project structure.

Within mymood/mymood create __init__.py

$touch __init__.py

Within mymood/mymood directory create command_line.py. setup.py needs this to run script from bash just by typing mymood.

$vim command_line.py

copy the following into command_line.py

from mymood import analyze
def main():
    analyze()

3. Python's setup.py file creation:

Create a setup.py file in mymood directory as shown in project structure above.

The below code is simple and minimal setup.py for mymood, copy and change as you require.

from setuptools import setup
setup(name='mymood',
  version='0.1',
  description='your mood analyzer',
  author='mp',
  author_email='hello@micropyramid.com',
  license='MIT',
  packages=['mymood'],
  entry_points = {
    'console_scripts': ['mymood=mymood.command_line:main'],
    },
  zip_safe=False)

Console scripts is used to run the script from terminal. So from bash you can just type mymood and run the script.

4. Setting up debian directory

$mkdir debian

Devscripts package is needed to create changelog file.

$cd debian
$sudo apt-get install devscripts
$dch --create

Now edit the file as follows:

mymood (1.0) UNRELEASED; urgency=medium
* Initial release. (Closes: #XXXXXX)
-- druuu <druuu@gmail.com>  Wed, 10 Feb 2016 15:33:03 +0530

5. Create copyright, compat, control and rules files in debian directory.

$touch compat
$touch copyright
$touch control
$touch rules

the control file looks like:

Source: mymood
Section: python
Priority: optional
Maintainer: druuu, <druuu@gmail.com>
Build-Depends: debhelper (>= 7),
Standards-Version: 3.9.2

Package: mymood
Architecture: all
Section: python
Depends: python, ${misc:Depends}, ${python:Depends}
Description: simple mood checker
mymood is a simple mood checker.
It analyze the mood by simple questions.

So this file lists dependencies, package description. The description is of two types, short and long.

Short is "simple mood checker' and the long 'mymood is a simple mood checker. It analyze the mood by simple questions'.

In the long description it should not exceed 80characters per line.

The rules file:

#!/usr/bin/make -f
%:
  dh $@ --with python2

Note that you have python2 or python3 based on your script, dont just put python.

Also not that you use tab before dh, not spaces

The other files can be left empty.

6. Finally lets create a deb package.

Goto mymood top level direcotry and build package.

mymood     <-- you should be inside this directory
  debian
    changelog
    compat
    control
    rules
    copyright
  mymood
    __init__.py
    mymood.py
    command_line.py
  README.md
  setup.py

$fakeroot dpkg-buildpackage -b

This should create the following structure:

mymood_1.0_all.deb      <--success! we got deb package
mymood_1.0_amd64.changes
mymood
  build
  debian
    tmp
      DEBIAN
        etc..
      usr
        etc..
    changelog
    compat
    control
    rules
    copyright
    debhelper.log
    files
    substvars
  mymood
    __init__.py
    mymood.py
    command_line.py
  mymood.egg-info
  README.md
  setup.py

As you can see we get mymood_1.0_all.deb package wich can be installed by "ubuntu software center".

Ubuntu Software Center is recomended as it automatically installs dependencies

or

simply

$sudo dpkg -i mymood_1.0_all.deb     <-- this command throws errors if dependencies not satisfied. Use ubuntu softare center.

Most of the above steps are from http://fosshelp.blogspot.in/2014/04/how-to-create-debian-package-for-python.html

Video for the above fosshelp blog post: https://www.youtube.com/watch?v=a9GzDZB5VeU.

Posted On 11 February 2016 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
Unit testing with selenium-python

Unit testing with selenium-python. Unit test case example to test the front-end

Continue Reading...
Tips to choose the best custom software development company

Choosing the best company for your software development needs is the most important step. This blog explains you tips to outsource custom software development services.

Continue Reading...
WSGI explanation with simple APP

The main goal of WSGI is to facilitate easy interconnection of servers and web frameworks/applications. WSGI defines a standerd API for web servers(uWSGI, Twisted, Gunicorn) …

Continue Reading...
Understanding self and __init__ method in python Class.

Understand self and __init__ method in python Class?
Before understanding the "self" and "__init__" methods in python class, it's very helpful if we have the idea …

Continue Reading...
List of python class special methods or magic methods

python class special methods or magic methods. magic methods allow us to override or add the default functionality of python objects. One of the biggest …

Continue Reading...
Building and Parsing XML Document using Python

Creating XML document with required elements, Then Parsing it using Python to generate a serialized form of its contents.

Continue Reading...
Working with python collections Counter

Python collections - Counter is to count the frequency of character, OrderedDict is to track the order of the contents in which they are added …

Continue Reading...
Python to Debian package: Simple, Easy and Fast

Packaging python script to debian follows strict instructions, using the following instructions, most of the steps can be skipped hence making it easy and fast.
If …

Continue Reading...
Sending SMS, MMS using Twilio.

A simple Tutorial on sending SMS and MMS in python using Twilio. In this tutorial you will learn how to send SMS, MMS and checking …

Continue Reading...
Customize and Embed Vimeo Videos using Python Requests.

Using python requests and vimeo endpoints it becomes very easy and simple to upload our videos and customize them.

Vimeo Access token:
1. Create an …

Continue Reading...
Getting Started with the IPython Notebook

IPython is a set of tools developed to make it easier for the programmers to work with Python and data. IPython provides extensions to the …

Continue Reading...
Python Arrow To Show Human Friendly Time

Arrow is a python library and command-line tool to genrerate, manipulate dates, times, timestamps.
use of arrow:
With the use of arrow, we can also create, manipulate, …

Continue Reading...
Working with python collections part 1

Python Collections - named tuple is to access by the names specified and deque is to append and pop the elements from both sides of …

Continue Reading...
Building Documentation with readthedocs

In this blog, I'm going to explain you how to write the Sphinx docs using reStructuredText to host in the Read the Docs.

Installing Sphinx

Continue Reading...
Create excel file, Insert image, Draw Bar Graphs in excel files in python using xlsxwriter

Xlsxwriter is a python module through which we can write data to Excel 2007+ XLSX file format. In this blog post we learn to write …

Continue Reading...
Integrate Twitter Social API into Django App

Integrating Twitter sign in (OAuth) in Django App, which includes
1. Capturing username via Twitter Login
2. Updating authenticated user current status on twitter(tweets).

Continue Reading...
How to implement Case Insensitive CSV DictReader in python

In general use cases we upload the CSV files to the system to store huge amount of data by uploading single file. For example in …

Continue Reading...
Python using yield and generators.

Generators are memory efficient. They allow us to code with minimum intermediate arguments, less data structures. Generators are of two types, generator expressions and generator …

Continue Reading...
Introduction to Object Oriented Programming with Python 3

Introduction to Object Oriented Programming with Python

Continue Reading...
Python Coding Techniques and Programming Practices

Coding techniques and programming practices are one of the features of a professional programmer. While writing code to solve a problem programmer should make simple …

Continue Reading...
FABRIC – LEARNING PART 2

Using Fabric, we can develop interactive script for ec2 region, ec2 flavour amazon web services. For this, you need aws account, security group, key pair, …

Continue Reading...
Generating PDF Files in Python using xhtml2pdf

There are many ways for generating PDF in python. In this post I will be presenting PDF files generation with xhtml2pdf.

xhtml2pdf: xhtml2pdf is a …

Continue Reading...
Using Python xlwt generating CSV writer and Excel files

In most of the cases, you need to export the data from your database to different formats. In this post I will show you how …

Continue Reading...
How to access development server publicly using Localtunnel

We do need to expose our local server to hit call-back URLs while programming with other APIs. There is a tool called local tunnel from …

Continue Reading...
How to generate PDF Files from HTML In Python using PDFKIT

There are many approches for generating PDF in python. pdfkit is one of the better approache as, it renders HTML into PDF with various image …

Continue Reading...
Converting Audio and Video files using FFMPEG Tool

FFMPEG is a command-line tool that converts audio or video to required formats, which handle multimedia data. It can also capture and encode in real-time.

Continue Reading...
Python Web Scraping with Beautiful soup

Download all One Piece animation series episodes by scraping site using BeautifulSoup python library.

Continue Reading...
Publishing Python Modules with PIP via PyPi

We'll install so many packages in our day to day python development. Now in this blog post, we'll try to know how to create our …

Continue Reading...
Programming with python: Decorators

Python decorators supports aspect-oriented programming. It is used to add or modify code in functions or classes. Using decorators will provide security, tracing, looking ..etc …

Continue Reading...
Vim for Python Web Development

Having a good environment setup is important for effective, fast and easy coding. We have different IDE's like eclipse, pycharm, sublime etc.. which are powerful …

Continue Reading...
Understanding Python Properties

Python Properties is a class for managing class attributes in Python. Property( ) is a built-in function that creates and returns a property object

Syntax:
attribute_name …

Continue Reading...
QRCode generation in python

A Quick Response code(QRCode) is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules …

Continue Reading...
Understanding Audio Quality: Bit Rate, Sample Rate

Audio Quality is the accuracy and enjoyability of the audio which the user can listen from an electronic device. Audio quality depends upon the bit …

Continue Reading...
Programming with python Descriptors (_get_, _set_, _delete_) - MicroPyramid

Python descriptors are object attributes that are only invoked for new style of classes. Python descriptors comes under the category of meta programming(code that manipulates …

Continue Reading...
Debugging in Python

When something goes wrong with your code instead of using standard debugging techniques such as print statements use debugging tools. I found two great tools …

Continue Reading...
Python development environment on windows

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of …

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties