Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Thursday, September 10, 2015

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 installing gnureadline

I was getting the following error gen trying to install gnureadline via pip:

collect2: error: ld returned 1 exit status

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_root/gnureadline/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-1_fHxP-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip_build_root/gnureadline
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/lib/python2.7/dist-packages/pip/__main__.py", line 5, in <module>
    exit = run()
  File "/usr/lib/python2.7/dist-packages/pip/runner.py", line 12, in run
    return pip.main()
  File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 235, in main
    return command.main(cmd_args)
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 161, in main
    text = '\n'.join(complete_log)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 66: ordinal not in range(128)

Turns out that is an issue generated by the use of older versions of pip: https://github.com/pypa/pip/issues/2667

The the version of pip in my server was 1.5.4 so I updated it:

sudo python -m pip install --upgrade pip
Downloading/unpacking pip from https://pypi.python.org/packages/py2.py3/p/pip/pip-7.1.2-py2.py3-none-any.whl#md5=5ff9fec0be479e4e36df467556deed4d
  Downloading pip-7.1.2-py2.py3-none-any.whl (1.1MB): 1.1MB downloaded
Installing collected packages: pip
  Found existing installation: pip 1.5.4
    Not uninstalling pip at /usr/lib/python2.7/dist-packages, owned by OS
Successfully installed pip
Cleaning up...

Mine was a new server so I installed some needed common libs: http://stackoverflow.com/questions/31508762/exception-using-pip-install

sudo apt-get install libffi-dev libssl-dev libxml2-dev libxslt1-dev libncurses5-dev

Then I tried to install gnureadline again and everything worked fine :)

Monday, July 13, 2015

Error installing MySQL-python on OSX

Tring to install mysql-python:

sudo python -m pip install MySQL-python



I was getting the error:

    sh: mysql_config: command not found

Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "/Applications/XAMPP/xamppfiles/htdocs/associate-fork-jhon-venv/build/MySQL-python/setup.py", line 17, in <module>

    metadata, options = get_config()

  File "setup_posix.py", line 43, in get_config

    libs = mysql_config("libs_r")

  File "setup_posix.py", line 25, in mysql_config

    raise EnvironmentError("%s not found" % (mysql_config.path,))

EnvironmentError: mysql_config not found



I solved the issue running:

brew install mysql


Reference:

Monday, January 19, 2015

Python: ImportError: No module named mandrill

I installed mandrill using pip:

    (venv)Jhons-MacBook-Pro:venv jhonjairoroa87$ pip install mandrill

I got this result:

    Downloading/unpacking mandrill
    Downloading mandrill-1.0.57.tar.gz
    Running setup.py (path:/private/var/folders/x3/st96cn215h915kqwlcrmtspw0000gn/T/pip_build_jhonjairoroa87/mandrill/setup.py) egg_info for package mandrill
    Requirement already satisfied (use --upgrade to upgrade): requests>=0.13.2 in /usr/local/lib/python2.7/site-packages (from mandrill)
    Requirement already satisfied (use --upgrade to upgrade): docopt==0.4.0 in /usr/local/lib/python2.7/site-packages (from mandrill)
    Installing collected packages: mandrill
    Running setup.py install for mandrill
    changing mode of build/scripts-2.7/mandrill from 644 to 755
    changing mode of build/scripts-2.7/sendmail.mandrill from 644 to 755
    changing mode of /usr/local/bin/mandrill to 755
    changing mode of /usr/local/bin/sendmail.mandrill to 755
    Successfully installed mandrill
    Cleaning up...


But when I try to use it, fails:

    (venv)Jhons-MacBook-Pro:venv jhonjairoroa87$ python
    Python 2.7.6 (default, Sep  9 2014, 15:04:36)
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import mandrill
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named mandrill
    >>>
    >>> import sendmail.mandrill
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: No module named sendmail.mandrill


I solved it by uninstalling it

     pip uninstall mandrill

and reinstalling it using the python -m option:

    sudo python -m pip install mandrill

Now it works perfectly.

    (venv)Jhons-MacBook-Pro:python_mandrill jhonjairoroa87$ python
    Python 2.7.6 (default, Sep  9 2014, 15:04:36)
    [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import mandrill
    >>>


Reference:
http://stackoverflow.com/questions/28032356/importerror-no-module-named-mandrill/28032480

Wednesday, January 14, 2015

Python: "command python setup.py egg_info failed with error code 1" while trying to install psycopg2

Using MacOSX I was trying to install psycopg2 by using the command,

sudo pip install psycopg2

And I was getting this error:

command python setup.py egg_info failed with error code 1

I solved the issue by installing http://brew.sh/ and running following commands:

brew install python
brew install postgres

References:
http://stackoverflow.com/questions/5420789/how-to-install-psycopg2-with-pip-on-python

Sunday, October 19, 2014

python - PIP : ImportError: cannot import name IncompleteRead

I got the error:

ImportError: cannot import name IncompleteRead

The solution was reinstalling pip:

sudo easy_install freeze
sudo apt-get remove python-pip
sudo apt-get autoremove
wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py --no-check-certificate
sudo python get-pip.py

Resource:

http://suanfazu.com/discussion/140/pip-install-importerror-cannot-import-name-incompleteread/p1

Monday, September 29, 2014

Python nested classes json encoder


Json pickle will do the trick : http://jsonpickle.github.io/

## import lib
import jsonpickle

## create class
class Thing(object):
    def __init__(self, name):
        self.name = name

## create class instance
obj = Thing('Awesome')

## from obj to json string
frozen = jsonpickle.encode(obj)

## from json string to obj
thawed = jsonpickle.decode(frozen)

Wednesday, October 31, 2012

Python: delete element from dict

Use del:

dict2 = {"key1":"value1","key2":"value2","key3":"value3"}

print "############### print before del#################"
for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)
    
del dict2["key2"]

print "############### print after del#################"
for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)

Resource:
http://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary

Python: validate if attribute is a instance method


Use type() or isinstance() functions:

# test.py

import types

class Person():
    def __init__(self,fistname,lastname):
        self.fistname = fistname
        self.lastname = lastname
        
    def run(self):
        print "run"
        
    def jump(self):
        print "jump"

myPerson = Person("jack","smith")
for name in dir(myPerson):
    print "name: %s" % (name)
    myAttrib = getattr(myPerson, name)
    print "myAttrib: %s" % (myAttrib)    
    print "(type(myAttrib)) == types.MethodType: %s" % ((type(myAttrib)) == types.MethodType)
    print "isinstance(myAttrib, types.MethodType: %s" % (isinstance(myAttrib, types.MethodType))
   
Result:


C:\Users\John\Desktop>python test.py
name: __doc__
myAttrib: None
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: __init__
myAttrib: <bound method Person.__init__ of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: __module__
myAttrib: __main__
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: fistname
myAttrib: jack
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: jump
myAttrib: <bound method Person.jump of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True
name: lastname
myAttrib: smith
(type(myAttrib)) == types.MethodType: False
isinstance(myAttrib, types.MethodType: False
name: run
myAttrib: <bound method Person.run of <__main__.Person instance at 0x004F85F8>>
(type(myAttrib)) == types.MethodType: True
isinstance(myAttrib, types.MethodType: True

Resources:
http://stackoverflow.com/questions/624926/how-to-detect-whether-a-python-variable-is-a-function
http://docs.python.org/2/library/types.html
http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python


Python: iterate dict

dict2 = {"key1":"value1","key2":"value2","key3":"value3"}

for k in dict2.keys():
    myValue = dict2[k]
    print "key: %s , value: %s" % (k,myValue)

Result:


C:\Users\John\Desktop>python test.py
key: key3 , value: value3
key: key2 , value: value2
key: key1 , value: value1


Resource:
http://stackoverflow.com/questions/6332691/python-dictionary-iteration


Friday, August 10, 2012

Python: Split a string into array with each character

use list() mehod:


numbers = "342"
lst = list(numbers)
print lst // ['3','4','2']

Reference:
http://ubuntuforums.org/showthread.php?t=541931

Python: iterate for loop backwards

use reversed() method:


>>> array=[0,10,20,40]
>>> for i in reversed(array):
...     print i

reference:
http://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python

Monday, July 30, 2012

Python: split string by given separator

use .split() method:


myString = "1-2-3-4-5-6-7-8"
mySplittedStringArray = myString.split('-')
print mySplittedStringArray # ['1', '2', '3', '4', '5', '6', '7', '8']


Resource:
http://www.tutorialspoint.com/python/string_split.htm
http://jolthgs.wordpress.com/2012/02/12/metodos-join-y-split-en-python/

Tuesday, July 24, 2012

Python: Pass a method as a parameter


def method1():
    return 'hello world'


def method2(methodToRun):
    result = methodToRun()
    return result


method2(method1)


Reference:
http://stackoverflow.com/questions/706721/how-do-i-pass-a-method-as-a-parameter-in-python

Python: weird SyntaxError: invalid syntax

The code was apparently normal:

def myFunctionTestOK():
   return "hi there ok"

def myFunctionTestFail():
   return "hi there fail"

and the error was:

Traceback (most recent call last):  
  File "C:\mytest.py", line 5
    return "hi there fail"
                          ^
SyntaxError: invalid syntax

I was using the Pydev Eclipse Plugin. After a lot of time trying to identify the error I decide to open the file using Notepad ++ http://notepad-plus-plus.org/

clicking in the 'show all characters' button:


I found out that there was missing a (LF) just after the line return "hi there fail":




so I put the cursor just after "hi there fail" and pressed enter:




And finally deleted the line with the single (CR):




Now everything works smoothly.

Python: UnicodeEncodeError: 'ascii' codec can't encode character in position : ordinal not in range(128)

If you get this error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Use the .encode() method instead of using str():


a = u'bats\u00E0'
print a # batsà
print str(a) # UnicodeEncodeError: 'ascii' codec can't encode ...
print a.encode('utf-8') # batsà


Reference:
http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20

Monday, July 23, 2012

Python: try except generic exception

   try:
       myInt = int ("100000A") # throws exception
       #myInt = int ("100000") # doesn't throw exception
       print "myInt:" , myInt
   except Exception, e:
       print "My Error: " , str(e)

Resource:
http://www.daniweb.com/software-development/python/threads/169976/python-try...except-printing-exception

Monday, November 14, 2011

Python: Private Variables and Methods


# Demonstrates private variables and methods


class Critter(object):
    """A virtual pet"""
    def __init__(self, name, mood):
        print "A new critter has been born!"
        self.name = name            # public attribute
        self.__mood = mood          # private attribute


    def talk(self):
        print "\nI'm", self.name
        print "Right now I feel", self.__mood, "\n"


    def __private_method(self):
        print "This is a private method."


    def public_method(self):
        print "This is a public method."
        self.__private_method()


# main
crit = Critter(name = "Poochie", mood = "happy")
crit.talk()
crit.public_method()


Source:
http://www.java2s.com/Code/Python/Class/Demonstratesprivatevariablesandmethods.htm