Archive
python setup.py uninstall
Problem
Sometimes you need to install a software with “python setup.py install“. However, if you want to get rid of it, there is no “python setup.py uninstall” or “python setup.py remove”. Stupid, but true.
Solution
I found the solution here. In short:
# install: $ (sudo) python setup.py install # uninstall: $ pip freeze | grep PATTERN_BASED_ON_PACKAGE_NAME # then remove with pip: $ (sudo) pip uninstall PACKAGE_NAME
[django] virtualenvwrapper with Python 3
Problem
Django 1.7 came out ten days ago. If you look at the updated poll tutorial, you will notice that it’s written for Python 3! So far I’ve used Python 2 only, so I thought I would redo this tutorial for two reasons: (1) learn about migrations, and (2) start using Python 3.
For my Django projects I use virtualenvwrapper to manage my virtual environments, so the first question was: how to create a Python 3 virt. env. with virtualenvwrapper?
Well, maybe my installation got corrupted somehow, but I ran into this problem:
$ mkvirtualenv -p `which python3` tmpenv
Running virtualenv with interpreter /usr/bin/python3
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in <module>
import base64
File "/usr/lib/python3.4/base64.py", line 9, in <module>
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
if not enabled():
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Original exception was:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in <module>
import base64
File "/usr/lib/python3.4/base64.py", line 9, in <module>
import re
File "/usr/lib/python3.4/re.py", line 324, in <module>
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in <module>
from copy_reg import *
ImportError: No module named 'copy_reg'
Solution
I posted this question to reddit (see here) and I found the following solution:
First, install pip3:
sudo apt-get install python3-pip sudo pip3 install virtualenvwrapper
Then, add the following lines to your .bashrc:
export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/workspace # customize if needed export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv source /usr/local/bin/virtualenvwrapper.sh
Try if it works for you. In my case, I had to edit the file “/usr/local/bin/virtualenv“. I changed its first line to
#!/usr/bin/env python3
The consequence of changing the first line was that creating Python 3 environments became the default, but at least it works now.
Create a Python 3 virt. env.:
mktmpenv
Create a Python 2 virt. env.:
mktmpenv -p `which python2`
If you use the command “virtualenv“, it will also create Python 3 environments by default. Thus, “virtualenv myproject3” will be a Python 3 env., while “virtualenv -p python2 myproject2” will be a Python 2 env.
rotate a matrix
Rotate clockwise:
rotated = zip(*original[::-1])
Rotate counterclockwise:
rotated_ccw = zip(*original)[::-1]
I found this trick in this thread.
print a text by specifying the width via a variable
Problem
You want to print a text using a certain width that you want to specify via a variable. Running example:
$ ./test.py Width: 10 ' World' Width: 20 ' World'
Solution
for _ in range(2):
width = int(raw_input("Width: "))
print("'{0:>{w}}'".format("World", w=width))
The sign ‘>‘ can be omitted. It simply means “align to the right”.
Tip from here.
Django show_urls formatter
Today I wrote a little script to beautify the output of the command “manage.py show_urls“. The script is available on GitHub here. For more info, visit the previous GitHub link.
Screenshots
Normal usage:
$ ./manage.py show_urls
Adding the beautifier:
$ ./manage.py show_urls | fmt.py
awesome Python
“awesome-python is a curated list of awesome Python frameworks, libraries and software. Inspired by awesome-php.”
Have you ever wondered what kind of packages to use for geolocation for instance? Here you will find the answer.
The good thing is that the libraries are put in categories.
built-in Python modules you should know
Here is an interesting thread about built-in modules that you should know: http://redd.it/28yo37 . If you wonder how to improve your Python knowledge, check ’em out.
In the thread some useful 3rd party modules are also listed.
call a function by knowing its name as a string
Problem
I want to call a function but its name is stored in a string. How to do that?
Solution
I wanted to create a menu where the user can select which entry to call. It looks like this:
(1)[r] radio (2)[ctd] create temp. directory -------- [m] menu [q] <
In Python I stored it like this:
menu = OrderedDict()
menu[(1, 'r')] = ('radio', 'apps.radio.radio_player')
menu[(2, 'ctd')] = ('create temp. directory', 'apps.temp_folder.create_temp_folder')
That is, if the user selects “1“, then apps.radio.radio_player() must be called.
Here is the method that can call the appropriate function:
import importlib
def start_app(val):
"""
Call a function by name (string).
Tip from here: http://stackoverflow.com/questions/3061 .
"""
_, to_call = val
function_string = to_call # ex.: 'apps.radio.radio_player'
mod_name, func_name = function_string.rsplit('.', 1)
mod = importlib.import_module(mod_name)
func = getattr(mod, func_name)
func()
The tip is from here.
extract all links from a file
Problem
You want to extract all links (URLs) from a text file.
Solution
def extract_urls(fname):
with open(fname) as f:
return re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', f.read())
Is a file binary?
Problem
I want to process all text files in a folder recursively. (Actually, I want to extract all URLs from them). However, their extensions are not necessarily .txt. How to separate text files from binary files?
Solution
In this thread I found a solution. Here is my slightly modified version:
def is_binary(fname):
"""
Return true if the given filename is binary.
found at http://stackoverflow.com/questions/898669
"""
CHUNKSIZE = 1024
with open(fname, 'rb') as f:
while True:
chunk = f.read(CHUNKSIZE)
if '\0' in chunk: # found null byte
return True
if len(chunk) < CHUNKSIZE:
break # done
return False
If it finds a '\0' character, then the file is considered to be binary. Note that it will also classify UTF-16-encoded text files as “binary”.



You must be logged in to post a comment.