Archive for the ‘python’ Category

“import tkinter” fails

April 27, 2016 Leave a comment

Under Manjaro I wanted to use the turtle module but I got this error:

File "", line 1, in <module>
    import turtle
  File "/usr/lib/python2.7/lib-tk/", line 107, in <module>
    import Tkinter as TK
  File "/usr/lib/python2.7/lib-tk/", line 39, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ImportError: cannot open shared object file: No such file or directory


sudo pacman -S tk
Categories: python Tags: , , ,

Installing a Flask webapp on a Digital Ocean (or Linode, etc.) Ubuntu box

March 26, 2016 Leave a comment

How to install a Flask webapp on a Digital Ocean VPS that has Ubuntu Linux on it:

This writing of mine appeared in Import Python Weekly Newsletter No. 65.

gunicorn from upstart fails to start

March 17, 2016 1 comment

Today I was trying to put together these: ubuntu + nginx + gunicorn + start gunicorn from upstart + flask + virtualenv. After a whole afternoon, I managed to do it. I will write a detailed post about it, but now I just want to concentrate on one part, which was the most problematic.

I wanted to start gunicorn from upstart. So I issued the following command:

$ sudo service gunicorn start 
gunicorn start/running, process 21415
$ sudo service gunicorn status
gunicorn stop/waiting

Each time I tried to launch it, it failed.

First of all, I didn’t know where the upstart log files were located. I know, it’s lame, but after a few hours I relized that it’d be a good idea to google it… So, the log files are in this folder:


The log of gunicorn is here:


Now, I started to monitor the end of this file in another terminal with “tail -f /var/log/upstart/gunicorn.log“. With this information I could easily find the error. I put here my solution and then I add some explanation:

# /etc/init/gunicorn.conf
description "Gunicorn daemon for a Flask project"

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]

# If the process quits unexpectadly trigger a respawn

setuid demo
setgid demo

. "/home/demo/.virtualenvs/myproj/bin/activate"
cd /home/demo/projects/myproj/api
exec gunicorn --name="my project" --bind= --config /etc/gunicorn.d/ api:app
end script

And you know what caused the problem? Instead of “.” I tried to use “source”. This is what I found in every tutorial. But as it turned out, this script is executed with “/bin/sh“, not with “/bin/bash“, and sh doesn’t know source. Geez…

The normal user on this machine is called “demo“. My Flask project is within a virtual environment. You can create a script block and the steps within are executed with “sh”. So first we “source” the virtual environment, then enter the directory where the Python script to be executed is located (here “api” is the name of the folder, and in there I have a file called ““, which contains the “app” variable). gunicorn is also installed in the virtual environment! You don’t need to install it globally with “sudo“!

Nginx is listening on port 80 and every connection that arrives there are forwarded to this gunicorn instance on port 9000. But I’ll write about it a bit later.

The content of “/etc/gunicorn.d/“:

"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from os import environ

def max_workers():
    return cpu_count() * 2 + 1

max_requests = 1000
worker_class = 'gevent'
workers = max_workers()
Categories: flask, python Tags: , , , ,

pretty JSON output with Flask-RESTful

March 15, 2016 Leave a comment

Flask-RESTful is an awesome way to write REST APIs. In debug mode, its output is nicely indented, easy to read. However, in production mode the JSON is compressed and hard to read.

If debug is False, how to have a nicely formatted output?


from flask import Flask
from flask_restful import Api

app = Flask(__name__)
api = Api(app)

if production:
    print("# running in production mode")
    HOST = ''
    DEBUG = False
    # START: temporary help for the UI developers, remove later
    settings = app.config.get('RESTFUL_JSON', {})
    settings.setdefault('indent', 2)
    settings.setdefault('sort_keys', True)
    app.config['RESTFUL_JSON'] = settings
    # END
    print("# running in development mode")
    DEBUG = True

# ...

if __name__ == '__main__':, host=HOST, port=1234)

Note that here I use the development server shipped with Flask, which is not suitable for real production. So this solution is between development and production.

Categories: flask, python Tags: , , ,

detect duplicate keys in a JSON file

March 6, 2016 Leave a comment

I want to edit a JSON file by hand but I’m afraid that somewhere I introduce a duplicate key by accident. If it happens, then the second key silently overwrites the first one. Example:

$ cat input.json 
    "content": {
        "a": 1,
        "a": 2

Naive approach:

import json

with open("input.json") as f:
    d = json.load(f)


# {'content': {'a': 2}}

If there is a duplicate key, it should fail! But it remains silent and you have no idea that you just lost some data.

I found the solution here.

import json

def dict_raise_on_duplicates(ordered_pairs):
    """Reject duplicate keys."""
    d = {}
    for k, v in ordered_pairs:
        if k in d:
           raise ValueError("duplicate key: %r" % (k,))
           d[k] = v
    return d

def main():
    with open("input.json") as f:
        d = json.load(f, object_pairs_hook=dict_raise_on_duplicates)


Now you get a nice error message:

Traceback (most recent call last):
  File "./", line 28, in <module>
  File "./", line 21, in main
    d = json.load(f, object_pairs_hook=dict_raise_on_duplicates)
  File "/usr/lib64/python3.5/json/", line 268, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib64/python3.5/json/", line 332, in loads
    return cls(**kw).decode(s)
  File "/usr/lib64/python3.5/json/", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python3.5/json/", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
  File "./", line 13, in dict_raise_on_duplicates
    raise ValueError("duplicate key: %r" % (k,))
ValueError: duplicate key: 'a'

If your json file has no duplicates, then the code aboce nicely prints its content.

Categories: python Tags: ,

Fallout 3 Computer Hack

February 1, 2016 Leave a comment

In Fallout 3 there is a minigame where you need to hack computers. I made a simple script to do these hacks easily. Here is a running example:

$ ./ example.txt
Words and scores:
traveling  5
swiveling  5
wandering  4
spreading  4
desperate  3
telephone  3
sterilize  3
deformity  3
september  2
belonging  2

Tip: it's a good idea to start with the word that has the highest score.

Guessed word: traveling
Number of matches: 1
The password is one of these words:  ['desperate', 'september', 'deformity']

Guessed word: desperate
Number of matches: 3
The password is:  deformity

The script can be found on GitHub.

Categories: python Tags: , ,

getting started with Kivy

January 24, 2016 Leave a comment

Kivy is an open source library for developing multi-touch applications. It is cross-platform (Linux/OSX/Windows/Android/iOS) and released under the terms of the MIT License.

It comes with native support for many multi-touch input devices, a growing library of multi-touch aware widgets and hardware accelerated OpenGL drawing. Kivy is designed to let you focus on building custom and highly interactive applications as quickly and easily as possible.” (source)

How to install it in a virtual environment? I could install it but when I wanted to create a basic app, it dropped some error messages (“pygame or sdl missing”).

Instead of Pygame I chose the SDL way. So under Manjaro I had to install globally the following packages:

sudo pacman -S gstreamer sdl2_ttf sdl2_mixer sdl2_image

Maybe gstreamer is not necessary, I’m not sure.

I suggest working with Kivy in a Python 2 virtual environment. Why? If you want to build your app for Android, then you can use the buildozer tool. However, at the moment it doesn’t support Python 3 :( I’m sure it’ll change but at the moment stick with Python 2.

Then, in your virtual environment, install these:

pip install cython
pip install kivy

Let’s try if it works. Activate your virt. env. and launch the Python interpreter in it. Then try this code:

>>> from import App
>>> App().run()

If you get a blank window with black background, then everything is fine.



Get every new post delivered to your Inbox.

Join 115 other followers