title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Dynamically attaching a method to an existing Python object generated with swig?
1,382,871
<p>I am working with a Python class, and I don't have write access to its declaration. How can I attach a custom method (such as <strong><code>__str__</code></strong>) to the objects created from that class without modifying the class declaration?</p> <p>EDIT: Thank you for all your answers. I tried them all but they haven't resolved my problem. Here is a minimal example that I hope will clarify the issue. I am using swig to wrap a C++ class, and the purpose is to override the <code>__str__</code> function of <strong>an object</strong> returned by the swig module. I use cmake to build the example:</p> <p><strong>test.py</strong></p> <pre><code>import example ex = example.generate_example(2) def prnt(self): return str(self.x) #How can I replace the __str__ function of object ex with prnt? print ex print prnt(ex) </code></pre> <p><strong>example.hpp</strong></p> <pre><code>struct example { int x; }; example generate_example(int x); </code></pre> <p><strong>example.cpp</strong></p> <pre><code>#include "example.hpp" #include &lt;iostream&gt; example generate_example(int x) { example ex; ex.x = x; return ex; } int main() { example ex = generate_example(2); std::cout &lt;&lt; ex.x &lt;&lt; "\n"; return 1; } </code></pre> <p><strong>example.i</strong></p> <pre><code>%module example %{ #include "example.hpp" %} %include "example.hpp" </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 2.6) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_PATH}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON) swig_add_module(example python example.i example) swig_link_libraries(example ${PYTHON_LIBRARIES}) if(APPLE) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS "${CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS} -flat_namespace") endif(APPLE) </code></pre> <p>To build and run test.py, copy all the files in a directory, and in that directory run</p> <pre><code>cmake . make python test.py </code></pre> <p>This results in the following output:</p> <pre><code>&lt;example.example; proxy of &lt;Swig Object of type 'example *' at 0x10021cc40&gt; &gt; 2 </code></pre> <p>As you can see the swig object has its own <strong>str</strong> function, and that is what I am trying to override. </p>
7
2009-09-05T09:30:59Z
1,382,965
<p>Create a subclass. Example:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; t = datetime.datetime.now() &gt;&gt;&gt; datetime.datetime.__str__ = lambda self: 'spam' ... TypeError: cant set attributes of built-in/extension type 'datetime.datetime' &gt;&gt;&gt; t.__str__ = lambda self: 'spam' ... AttributeError: 'datetime.datetime' object attribute '__str__' is read-only &gt;&gt;&gt; class mydate(datetime.datetime): def __str__(self): return 'spam' &gt;&gt;&gt; myt = mydate.now() &gt;&gt;&gt; print t 2009-09-05 13:11:34.600000 &gt;&gt;&gt; print myt spam </code></pre>
3
2009-09-05T10:22:01Z
[ "python", "class", "dynamic", "methods" ]
Dynamically attaching a method to an existing Python object generated with swig?
1,382,871
<p>I am working with a Python class, and I don't have write access to its declaration. How can I attach a custom method (such as <strong><code>__str__</code></strong>) to the objects created from that class without modifying the class declaration?</p> <p>EDIT: Thank you for all your answers. I tried them all but they haven't resolved my problem. Here is a minimal example that I hope will clarify the issue. I am using swig to wrap a C++ class, and the purpose is to override the <code>__str__</code> function of <strong>an object</strong> returned by the swig module. I use cmake to build the example:</p> <p><strong>test.py</strong></p> <pre><code>import example ex = example.generate_example(2) def prnt(self): return str(self.x) #How can I replace the __str__ function of object ex with prnt? print ex print prnt(ex) </code></pre> <p><strong>example.hpp</strong></p> <pre><code>struct example { int x; }; example generate_example(int x); </code></pre> <p><strong>example.cpp</strong></p> <pre><code>#include "example.hpp" #include &lt;iostream&gt; example generate_example(int x) { example ex; ex.x = x; return ex; } int main() { example ex = generate_example(2); std::cout &lt;&lt; ex.x &lt;&lt; "\n"; return 1; } </code></pre> <p><strong>example.i</strong></p> <pre><code>%module example %{ #include "example.hpp" %} %include "example.hpp" </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 2.6) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_PATH}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON) swig_add_module(example python example.i example) swig_link_libraries(example ${PYTHON_LIBRARIES}) if(APPLE) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS "${CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS} -flat_namespace") endif(APPLE) </code></pre> <p>To build and run test.py, copy all the files in a directory, and in that directory run</p> <pre><code>cmake . make python test.py </code></pre> <p>This results in the following output:</p> <pre><code>&lt;example.example; proxy of &lt;Swig Object of type 'example *' at 0x10021cc40&gt; &gt; 2 </code></pre> <p>As you can see the swig object has its own <strong>str</strong> function, and that is what I am trying to override. </p>
7
2009-09-05T09:30:59Z
1,382,968
<p>This is my answer from <a href="http://stackoverflow.com/questions/357997/does-python-have-something-like-anonymous-inner-classes-of-java/358055#358055">another question</a>:</p> <pre><code>import types class someclass(object): val = "Value" def some_method(self): print self.val def some_method_upper(self): print self.val.upper() obj = someclass() obj.some_method() obj.some_method = types.MethodType(some_method_upper, obj) obj.some_method() </code></pre>
2
2009-09-05T10:23:31Z
[ "python", "class", "dynamic", "methods" ]
Dynamically attaching a method to an existing Python object generated with swig?
1,382,871
<p>I am working with a Python class, and I don't have write access to its declaration. How can I attach a custom method (such as <strong><code>__str__</code></strong>) to the objects created from that class without modifying the class declaration?</p> <p>EDIT: Thank you for all your answers. I tried them all but they haven't resolved my problem. Here is a minimal example that I hope will clarify the issue. I am using swig to wrap a C++ class, and the purpose is to override the <code>__str__</code> function of <strong>an object</strong> returned by the swig module. I use cmake to build the example:</p> <p><strong>test.py</strong></p> <pre><code>import example ex = example.generate_example(2) def prnt(self): return str(self.x) #How can I replace the __str__ function of object ex with prnt? print ex print prnt(ex) </code></pre> <p><strong>example.hpp</strong></p> <pre><code>struct example { int x; }; example generate_example(int x); </code></pre> <p><strong>example.cpp</strong></p> <pre><code>#include "example.hpp" #include &lt;iostream&gt; example generate_example(int x) { example ex; ex.x = x; return ex; } int main() { example ex = generate_example(2); std::cout &lt;&lt; ex.x &lt;&lt; "\n"; return 1; } </code></pre> <p><strong>example.i</strong></p> <pre><code>%module example %{ #include "example.hpp" %} %include "example.hpp" </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 2.6) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_PATH}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON) swig_add_module(example python example.i example) swig_link_libraries(example ${PYTHON_LIBRARIES}) if(APPLE) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS "${CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS} -flat_namespace") endif(APPLE) </code></pre> <p>To build and run test.py, copy all the files in a directory, and in that directory run</p> <pre><code>cmake . make python test.py </code></pre> <p>This results in the following output:</p> <pre><code>&lt;example.example; proxy of &lt;Swig Object of type 'example *' at 0x10021cc40&gt; &gt; 2 </code></pre> <p>As you can see the swig object has its own <strong>str</strong> function, and that is what I am trying to override. </p>
7
2009-09-05T09:30:59Z
1,383,071
<p>Note that using Alex's subclass idea, you can help yourself a little bit more using "<code>from</code> ... <code>import</code> ... <code>as</code>":</p> <pre><code>from datetime import datetime as datetime_original class datetime(datetime_original): def __str__(self): return 'spam' </code></pre> <p>so now the class has the standard name, but different behaviour. </p> <pre><code>&gt;&gt;&gt; print datetime.now() 'spam' </code></pre> <p>Of course, this can be dangerous...</p>
1
2009-09-05T11:13:10Z
[ "python", "class", "dynamic", "methods" ]
Dynamically attaching a method to an existing Python object generated with swig?
1,382,871
<p>I am working with a Python class, and I don't have write access to its declaration. How can I attach a custom method (such as <strong><code>__str__</code></strong>) to the objects created from that class without modifying the class declaration?</p> <p>EDIT: Thank you for all your answers. I tried them all but they haven't resolved my problem. Here is a minimal example that I hope will clarify the issue. I am using swig to wrap a C++ class, and the purpose is to override the <code>__str__</code> function of <strong>an object</strong> returned by the swig module. I use cmake to build the example:</p> <p><strong>test.py</strong></p> <pre><code>import example ex = example.generate_example(2) def prnt(self): return str(self.x) #How can I replace the __str__ function of object ex with prnt? print ex print prnt(ex) </code></pre> <p><strong>example.hpp</strong></p> <pre><code>struct example { int x; }; example generate_example(int x); </code></pre> <p><strong>example.cpp</strong></p> <pre><code>#include "example.hpp" #include &lt;iostream&gt; example generate_example(int x) { example ex; ex.x = x; return ex; } int main() { example ex = generate_example(2); std::cout &lt;&lt; ex.x &lt;&lt; "\n"; return 1; } </code></pre> <p><strong>example.i</strong></p> <pre><code>%module example %{ #include "example.hpp" %} %include "example.hpp" </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code>cmake_minimum_required(VERSION 2.6) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) find_package(PythonLibs) include_directories(${PYTHON_INCLUDE_PATH}) include_directories(${CMAKE_CURRENT_SOURCE_DIR}) set_source_files_properties(example.i PROPERTIES CPLUSPLUS ON) swig_add_module(example python example.i example) swig_link_libraries(example ${PYTHON_LIBRARIES}) if(APPLE) set(CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS "${CMAKE_SHARED_MODULE_CREATE_CXX_FLAGS} -flat_namespace") endif(APPLE) </code></pre> <p>To build and run test.py, copy all the files in a directory, and in that directory run</p> <pre><code>cmake . make python test.py </code></pre> <p>This results in the following output:</p> <pre><code>&lt;example.example; proxy of &lt;Swig Object of type 'example *' at 0x10021cc40&gt; &gt; 2 </code></pre> <p>As you can see the swig object has its own <strong>str</strong> function, and that is what I am trying to override. </p>
7
2009-09-05T09:30:59Z
1,383,646
<p>If you create a wrapper class, this will work with any other class, either built-in or not. This is called "containment and delegation", and it is a common alternative to inheritance:</p> <pre><code>class SuperDuperWrapper(object): def __init__(self, origobj): self.myobj = origobj def __str__(self): return "SUPER DUPER " + str(self.myobj) def __getattr__(self,attr): return getattr(self.myobj, attr) </code></pre> <p>The <code>__getattr__</code> method will delegate all undefined attribute requests on your SuperDuperWrapper object to the contained myobj object. In fact, given Python's dynamic typing, you could use this class to SuperDuper'ly wrap just about anything:</p> <pre><code>s = "hey ho!" sds = SuperDuperWrapper(s) print sds i = 100 sdi = SuperDuperWrapper(i) print sdi </code></pre> <p>Prints:</p> <pre><code>SUPER DUPER hey ho! SUPER DUPER 100 </code></pre> <p>In your case, you would take the returned object from the function you cannot modify, and wrap it in your own SuperDuperWrapper, but you could still otherwise access it just as if it were the base object.</p> <pre><code>print sds.split() ['hey', 'ho!'] </code></pre>
19
2009-09-05T15:51:30Z
[ "python", "class", "dynamic", "methods" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
1,383,009
<p><code>--no-site-packages</code> should, as the name suggests, remove the standard site-packages directory from sys.path. Anything else that lives in the standard Python path will remain there.</p>
11
2009-09-05T10:47:29Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
1,402,050
<p>Eventually I found that, for whatever reason, pip -E was not working. However, if I actually activate the virtualenv, and use easy_install provided by virtualenv to install pip, then use pip directly from within, it seems to work as expected and only show the packages in the virtualenv</p>
21
2009-09-09T20:57:04Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
15,178,877
<p>I know this is a very old question but for those arriving here looking for a solution:</p> <p>Don't forget to <strong>activate the virtualenv</strong> (<code>source bin/activate</code>) before running <code>pip freeze</code>. Otherwise you'll get a list of all global packages.</p>
10
2013-03-02T20:06:48Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
15,887,589
<p>I had a problem like this, until I realized that (long before I had discovered virtualenv), I had gone adding directories to the PYTHONPATH in my .bashrc file. As it had been over a year beforehand, I didn't think of that straight away. </p>
60
2013-04-08T19:46:09Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
19,555,526
<p>A similar problem can occur on Windows if you call scripts directly as <code>script.py</code> which then uses the Windows default opener and opens Python outside the virtual environment. Calling it with <code>python script.py</code> will use Python with the virtual environment.</p>
3
2013-10-24T01:55:56Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
30,939,505
<p>This also seems to happen when you move the virtualenv directory to another directory (on linux), or rename a parent directory.</p>
2
2015-06-19T13:33:11Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
33,244,110
<p>Here's the list of all the pip install <a href="http://pip.readthedocs.org/en/stable/reference/pip_install/#options" rel="nofollow">options</a> - I didn't find any '<code>-E</code>' option, may be older version had it. Below I am sharing a plain english usage and working of <code>virtualenv</code> for the upcoming SO users.</p> <hr> <p>Every thing seems fine, accept activating the <code>virtualenv</code> (<code>foo</code>). All it does is allow us to have multiple (and varying) python environment i.e. various Python versions, or various Django versions, or any other Python package - in case we have a previous version in production and want to test the latest Django release with our application. </p> <p>In short creating and using (activating) virtual environment (<code>virtualenv</code>) makes it possible to run or test our application or simple python scripts with different Python interpreter i.e. Python 2.7 and 3.3 - can be a fresh installation (using <code>--no-site-packages</code> option) or all the packages from existing/last setup (using <code>--system-site-packages</code> option). To use it we have to activate it: </p> <p><code>$ pip install django</code> will install it into the global site-packages, and similarly getting the <code>pip freeze</code> will give names of the global site-packages.</p> <p>while inside the venv dir (foo) executing <code>$ source /bin/activate</code> will activate venv i.e. now anything installed with pip will only be installed in the virtual env, and only now the pip freeze will not give the list of global site-packages python packages. Once activated:</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ cd foo $ source bin/activate (foo)$ pip install django </code></pre> <p><code>(foo)</code> before the <code>$</code> sign indicates we are using a virtual python environment i.e. any thing with pip - install, freeze, uninstall will be limited to this venv, and no effect on global/default Python installation/packages.</p>
0
2015-10-20T18:26:34Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
33,366,748
<p>You have to make sure you are running the <code>pip</code> binary in the virtual environment you created, not the global one.</p> <pre><code>env/bin/pip freeze </code></pre> <hr> <p>See a test:</p> <p>We create the virtualenv with the <code>--no-site-packages</code> option:</p> <pre><code>$ virtualenv --no-site-packages -p /usr/local/bin/python mytest Running virtualenv with interpreter /usr/local/bin/python New python executable in mytest/bin/python Installing setuptools, pip, wheel...done. </code></pre> <p>We check the output of <code>freeze</code> from the newly created <code>pip</code>:</p> <pre><code>$ mytest/bin/pip freeze argparse==1.3.0 wheel==0.24.0 </code></pre> <p>But if we do use the global <code>pip</code>, this is what we get:</p> <pre><code>$ pip freeze ... pyxdg==0.25 ... range==1.0.0 ... virtualenv==13.1.2 </code></pre> <p>That is, all the packages that <code>pip</code> has installed in the whole system. By checking <code>which pip</code> we get (at least in my case) something like <code>/usr/local/bin/pip</code>, meaning that when we do <code>pip freeze</code> it is calling this binary instead of <code>mytest/bin/pip</code>.</p>
7
2015-10-27T11:25:36Z
[ "python", "virtualenv", "pip" ]
virtualenv --no-site-packages and pip still finding global packages?
1,382,925
<p>I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn't seem to.</p> <p>For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.</p> <pre><code>$ virtualenv --no-site-packages foo New python executable in foo/bin/python Installing setuptools............done. $ pip -E foo install Django Requirement already satisfied: Django in /usr/share/pyshared Installing collected packages: Django Successfully installed Django </code></pre> <p>From what I can tell, the <code>pip -E foo install</code> above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?</p> <pre><code>$ pip -E foo freeze 4Suite-XML==1.0.2 BeautifulSoup==3.1.0.1 Brlapi==0.5.3 BzrTools==1.17.0 Django==1.1 ... and so on ... </code></pre> <p>Am I misunderstanding how --no-site-packages is supposed to work? </p>
78
2009-09-05T09:59:17Z
33,851,358
<p>I was having this same problem. The issue for me (on Ubuntu) was that my path name contained <code>$</code>. When I created a virtualenv outside of the $ dir, it worked fine.</p> <p>Weird.</p>
0
2015-11-22T03:42:06Z
[ "python", "virtualenv", "pip" ]
latin-1 to ascii
1,382,998
<p>I have a unicode string with accented latin chars e.g.</p> <pre><code>n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') </code></pre> <p>I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed</p> <p>What is the fastest way to do that, as it needed to be done for matching a long autocomplete dropdown list</p> <p><strong>Conclusion:</strong> As one my criteria is speed, Lennart's 'register your own error handler for unicode encoding/decoding' gives best result (see Alex's answer), speed difference increases further as more and more chars are latin.</p> <p>Here is the translation table I am using, also modified error handler as it need to take care of whole range of un-encoded char from error.start to error.end</p> <pre><code># -*- coding: utf-8 -*- import codecs """ This is more of visual translation also avoiding multiple char translation e.g. £ may be written as {pound} """ latin_dict = { u"¡": u"!", u"¢": u"c", u"£": u"L", u"¤": u"o", u"¥": u"Y", u"¦": u"|", u"§": u"S", u"¨": u"`", u"©": u"c", u"ª": u"a", u"«": u"&lt;&lt;", u"¬": u"-", u"­": u"-", u"®": u"R", u"¯": u"-", u"°": u"o", u"±": u"+-", u"²": u"2", u"³": u"3", u"´": u"'", u"µ": u"u", u"¶": u"P", u"·": u".", u"¸": u",", u"¹": u"1", u"º": u"o", u"»": u"&gt;&gt;", u"¼": u"1/4", u"½": u"1/2", u"¾": u"3/4", u"¿": u"?", u"À": u"A", u"Á": u"A", u"Â": u"A", u"Ã": u"A", u"Ä": u"A", u"Å": u"A", u"Æ": u"Ae", u"Ç": u"C", u"È": u"E", u"É": u"E", u"Ê": u"E", u"Ë": u"E", u"Ì": u"I", u"Í": u"I", u"Î": u"I", u"Ï": u"I", u"Ð": u"D", u"Ñ": u"N", u"Ò": u"O", u"Ó": u"O", u"Ô": u"O", u"Õ": u"O", u"Ö": u"O", u"×": u"*", u"Ø": u"O", u"Ù": u"U", u"Ú": u"U", u"Û": u"U", u"Ü": u"U", u"Ý": u"Y", u"Þ": u"p", u"ß": u"b", u"à": u"a", u"á": u"a", u"â": u"a", u"ã": u"a", u"ä": u"a", u"å": u"a", u"æ": u"ae", u"ç": u"c", u"è": u"e", u"é": u"e", u"ê": u"e", u"ë": u"e", u"ì": u"i", u"í": u"i", u"î": u"i", u"ï": u"i", u"ð": u"d", u"ñ": u"n", u"ò": u"o", u"ó": u"o", u"ô": u"o", u"õ": u"o", u"ö": u"o", u"÷": u"/", u"ø": u"o", u"ù": u"u", u"ú": u"u", u"û": u"u", u"ü": u"u", u"ý": u"y", u"þ": u"p", u"ÿ": u"y", u"’":u"'"} def latin2ascii(error): """ error is protion of text from start to end, we just convert first hence return error.start+1 instead of error.end """ return latin_dict[error.object[error.start]], error.start+1 codecs.register_error('latin2ascii', latin2ascii) if __name__ == "__main__": x = u"¼ éíñ§ÐÌëÑ » ¼ ö ® © ’" print x print x.encode('ascii', 'latin2ascii') </code></pre> <p><strong>Why I return <code>error.start + 1</code>:</strong></p> <p>error object returned can be multiple characters, and we convert only first of these e.g. if I add <code>print error.start, error.end</code> to error handler output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 einSDIeN &gt;&gt; 1/4 o R c ' </code></pre> <p>so in second line we get chars from 2-10 but we convert only 2nd hence return 3 as continue point, if we return error.end output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 e &gt;&gt; 1/4 o R c ' </code></pre> <p>As we can see 2-10 portion has been replaced by a single char. off-course it would be faster to just encode whole range in one go and return error.end, but for demonstration purpose I have kept it simple.</p> <p>see <a href="http://docs.python.org/library/codecs.html#codecs.register_error" rel="nofollow">http://docs.python.org/library/codecs.html#codecs.register_error</a> for more details</p>
13
2009-09-05T10:44:40Z
1,383,014
<p>Without measuring, I would expect that the .translate method of Unicode strings is the fastest solution. You should definitely make your own measurements, though.</p>
0
2009-09-05T10:49:24Z
[ "python", "unicode" ]
latin-1 to ascii
1,382,998
<p>I have a unicode string with accented latin chars e.g.</p> <pre><code>n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') </code></pre> <p>I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed</p> <p>What is the fastest way to do that, as it needed to be done for matching a long autocomplete dropdown list</p> <p><strong>Conclusion:</strong> As one my criteria is speed, Lennart's 'register your own error handler for unicode encoding/decoding' gives best result (see Alex's answer), speed difference increases further as more and more chars are latin.</p> <p>Here is the translation table I am using, also modified error handler as it need to take care of whole range of un-encoded char from error.start to error.end</p> <pre><code># -*- coding: utf-8 -*- import codecs """ This is more of visual translation also avoiding multiple char translation e.g. £ may be written as {pound} """ latin_dict = { u"¡": u"!", u"¢": u"c", u"£": u"L", u"¤": u"o", u"¥": u"Y", u"¦": u"|", u"§": u"S", u"¨": u"`", u"©": u"c", u"ª": u"a", u"«": u"&lt;&lt;", u"¬": u"-", u"­": u"-", u"®": u"R", u"¯": u"-", u"°": u"o", u"±": u"+-", u"²": u"2", u"³": u"3", u"´": u"'", u"µ": u"u", u"¶": u"P", u"·": u".", u"¸": u",", u"¹": u"1", u"º": u"o", u"»": u"&gt;&gt;", u"¼": u"1/4", u"½": u"1/2", u"¾": u"3/4", u"¿": u"?", u"À": u"A", u"Á": u"A", u"Â": u"A", u"Ã": u"A", u"Ä": u"A", u"Å": u"A", u"Æ": u"Ae", u"Ç": u"C", u"È": u"E", u"É": u"E", u"Ê": u"E", u"Ë": u"E", u"Ì": u"I", u"Í": u"I", u"Î": u"I", u"Ï": u"I", u"Ð": u"D", u"Ñ": u"N", u"Ò": u"O", u"Ó": u"O", u"Ô": u"O", u"Õ": u"O", u"Ö": u"O", u"×": u"*", u"Ø": u"O", u"Ù": u"U", u"Ú": u"U", u"Û": u"U", u"Ü": u"U", u"Ý": u"Y", u"Þ": u"p", u"ß": u"b", u"à": u"a", u"á": u"a", u"â": u"a", u"ã": u"a", u"ä": u"a", u"å": u"a", u"æ": u"ae", u"ç": u"c", u"è": u"e", u"é": u"e", u"ê": u"e", u"ë": u"e", u"ì": u"i", u"í": u"i", u"î": u"i", u"ï": u"i", u"ð": u"d", u"ñ": u"n", u"ò": u"o", u"ó": u"o", u"ô": u"o", u"õ": u"o", u"ö": u"o", u"÷": u"/", u"ø": u"o", u"ù": u"u", u"ú": u"u", u"û": u"u", u"ü": u"u", u"ý": u"y", u"þ": u"p", u"ÿ": u"y", u"’":u"'"} def latin2ascii(error): """ error is protion of text from start to end, we just convert first hence return error.start+1 instead of error.end """ return latin_dict[error.object[error.start]], error.start+1 codecs.register_error('latin2ascii', latin2ascii) if __name__ == "__main__": x = u"¼ éíñ§ÐÌëÑ » ¼ ö ® © ’" print x print x.encode('ascii', 'latin2ascii') </code></pre> <p><strong>Why I return <code>error.start + 1</code>:</strong></p> <p>error object returned can be multiple characters, and we convert only first of these e.g. if I add <code>print error.start, error.end</code> to error handler output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 einSDIeN &gt;&gt; 1/4 o R c ' </code></pre> <p>so in second line we get chars from 2-10 but we convert only 2nd hence return 3 as continue point, if we return error.end output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 e &gt;&gt; 1/4 o R c ' </code></pre> <p>As we can see 2-10 portion has been replaced by a single char. off-course it would be faster to just encode whole range in one go and return error.end, but for demonstration purpose I have kept it simple.</p> <p>see <a href="http://docs.python.org/library/codecs.html#codecs.register_error" rel="nofollow">http://docs.python.org/library/codecs.html#codecs.register_error</a> for more details</p>
13
2009-09-05T10:44:40Z
1,383,019
<p><a href="http://docs.python.org/library/string.html#string.maketrans" rel="nofollow">Maketrans</a> (and translate) then convert to ascii:</p> <pre><code>intab = u'áéí' # extend as needed outtab = u'aei' # as well as this one table = maketrans(intab, outtab) text = translate(u"Wikipédia, le projet d’encyclopédie", table) try: temp = unicode(text, "utf-8") fixed = unicodedata.normalize('NFKD', temp).encode('ASCII', action) return fixed except Exception, errorInfo: print errorInfo print "Unable to convert the Unicode characters to xml character entities" raise errorInfo </code></pre> <p>(from <a href="http://techxplorer.com/2006/07/18/converting-unicode-to-ascii-using-python/" rel="nofollow">here</a>)</p>
1
2009-09-05T10:51:27Z
[ "python", "unicode" ]
latin-1 to ascii
1,382,998
<p>I have a unicode string with accented latin chars e.g.</p> <pre><code>n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') </code></pre> <p>I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed</p> <p>What is the fastest way to do that, as it needed to be done for matching a long autocomplete dropdown list</p> <p><strong>Conclusion:</strong> As one my criteria is speed, Lennart's 'register your own error handler for unicode encoding/decoding' gives best result (see Alex's answer), speed difference increases further as more and more chars are latin.</p> <p>Here is the translation table I am using, also modified error handler as it need to take care of whole range of un-encoded char from error.start to error.end</p> <pre><code># -*- coding: utf-8 -*- import codecs """ This is more of visual translation also avoiding multiple char translation e.g. £ may be written as {pound} """ latin_dict = { u"¡": u"!", u"¢": u"c", u"£": u"L", u"¤": u"o", u"¥": u"Y", u"¦": u"|", u"§": u"S", u"¨": u"`", u"©": u"c", u"ª": u"a", u"«": u"&lt;&lt;", u"¬": u"-", u"­": u"-", u"®": u"R", u"¯": u"-", u"°": u"o", u"±": u"+-", u"²": u"2", u"³": u"3", u"´": u"'", u"µ": u"u", u"¶": u"P", u"·": u".", u"¸": u",", u"¹": u"1", u"º": u"o", u"»": u"&gt;&gt;", u"¼": u"1/4", u"½": u"1/2", u"¾": u"3/4", u"¿": u"?", u"À": u"A", u"Á": u"A", u"Â": u"A", u"Ã": u"A", u"Ä": u"A", u"Å": u"A", u"Æ": u"Ae", u"Ç": u"C", u"È": u"E", u"É": u"E", u"Ê": u"E", u"Ë": u"E", u"Ì": u"I", u"Í": u"I", u"Î": u"I", u"Ï": u"I", u"Ð": u"D", u"Ñ": u"N", u"Ò": u"O", u"Ó": u"O", u"Ô": u"O", u"Õ": u"O", u"Ö": u"O", u"×": u"*", u"Ø": u"O", u"Ù": u"U", u"Ú": u"U", u"Û": u"U", u"Ü": u"U", u"Ý": u"Y", u"Þ": u"p", u"ß": u"b", u"à": u"a", u"á": u"a", u"â": u"a", u"ã": u"a", u"ä": u"a", u"å": u"a", u"æ": u"ae", u"ç": u"c", u"è": u"e", u"é": u"e", u"ê": u"e", u"ë": u"e", u"ì": u"i", u"í": u"i", u"î": u"i", u"ï": u"i", u"ð": u"d", u"ñ": u"n", u"ò": u"o", u"ó": u"o", u"ô": u"o", u"õ": u"o", u"ö": u"o", u"÷": u"/", u"ø": u"o", u"ù": u"u", u"ú": u"u", u"û": u"u", u"ü": u"u", u"ý": u"y", u"þ": u"p", u"ÿ": u"y", u"’":u"'"} def latin2ascii(error): """ error is protion of text from start to end, we just convert first hence return error.start+1 instead of error.end """ return latin_dict[error.object[error.start]], error.start+1 codecs.register_error('latin2ascii', latin2ascii) if __name__ == "__main__": x = u"¼ éíñ§ÐÌëÑ » ¼ ö ® © ’" print x print x.encode('ascii', 'latin2ascii') </code></pre> <p><strong>Why I return <code>error.start + 1</code>:</strong></p> <p>error object returned can be multiple characters, and we convert only first of these e.g. if I add <code>print error.start, error.end</code> to error handler output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 einSDIeN &gt;&gt; 1/4 o R c ' </code></pre> <p>so in second line we get chars from 2-10 but we convert only 2nd hence return 3 as continue point, if we return error.end output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 e &gt;&gt; 1/4 o R c ' </code></pre> <p>As we can see 2-10 portion has been replaced by a single char. off-course it would be faster to just encode whole range in one go and return error.end, but for demonstration purpose I have kept it simple.</p> <p>see <a href="http://docs.python.org/library/codecs.html#codecs.register_error" rel="nofollow">http://docs.python.org/library/codecs.html#codecs.register_error</a> for more details</p>
13
2009-09-05T10:44:40Z
1,383,056
<p>The "correct" way to do this is to register your own error handler for unicode encoding/decoding, and in that error handler provide the replacements from è to e and ö to o, etc.</p> <p>Like so:</p> <pre><code># -*- coding: UTF-8 -*- import codecs map = {u'é': u'e', u'’': u"'", # ETC } def asciify(error): return map[error.object[error.start]], error.end codecs.register_error('asciify', asciify) test = u'Wikipédia, le projet d’encyclopédie' print test.encode('ascii', 'asciify') </code></pre> <p>You might also find something in IBM's <a href="http://site.icu-project.org/">ICU</a> library and it's Python bindings <a href="http://pypi.python.org/pypi/PyICU/0.8.1">PyICU</a>, though, it might be less work.</p>
8
2009-09-05T11:06:43Z
[ "python", "unicode" ]
latin-1 to ascii
1,382,998
<p>I have a unicode string with accented latin chars e.g.</p> <pre><code>n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') </code></pre> <p>I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed</p> <p>What is the fastest way to do that, as it needed to be done for matching a long autocomplete dropdown list</p> <p><strong>Conclusion:</strong> As one my criteria is speed, Lennart's 'register your own error handler for unicode encoding/decoding' gives best result (see Alex's answer), speed difference increases further as more and more chars are latin.</p> <p>Here is the translation table I am using, also modified error handler as it need to take care of whole range of un-encoded char from error.start to error.end</p> <pre><code># -*- coding: utf-8 -*- import codecs """ This is more of visual translation also avoiding multiple char translation e.g. £ may be written as {pound} """ latin_dict = { u"¡": u"!", u"¢": u"c", u"£": u"L", u"¤": u"o", u"¥": u"Y", u"¦": u"|", u"§": u"S", u"¨": u"`", u"©": u"c", u"ª": u"a", u"«": u"&lt;&lt;", u"¬": u"-", u"­": u"-", u"®": u"R", u"¯": u"-", u"°": u"o", u"±": u"+-", u"²": u"2", u"³": u"3", u"´": u"'", u"µ": u"u", u"¶": u"P", u"·": u".", u"¸": u",", u"¹": u"1", u"º": u"o", u"»": u"&gt;&gt;", u"¼": u"1/4", u"½": u"1/2", u"¾": u"3/4", u"¿": u"?", u"À": u"A", u"Á": u"A", u"Â": u"A", u"Ã": u"A", u"Ä": u"A", u"Å": u"A", u"Æ": u"Ae", u"Ç": u"C", u"È": u"E", u"É": u"E", u"Ê": u"E", u"Ë": u"E", u"Ì": u"I", u"Í": u"I", u"Î": u"I", u"Ï": u"I", u"Ð": u"D", u"Ñ": u"N", u"Ò": u"O", u"Ó": u"O", u"Ô": u"O", u"Õ": u"O", u"Ö": u"O", u"×": u"*", u"Ø": u"O", u"Ù": u"U", u"Ú": u"U", u"Û": u"U", u"Ü": u"U", u"Ý": u"Y", u"Þ": u"p", u"ß": u"b", u"à": u"a", u"á": u"a", u"â": u"a", u"ã": u"a", u"ä": u"a", u"å": u"a", u"æ": u"ae", u"ç": u"c", u"è": u"e", u"é": u"e", u"ê": u"e", u"ë": u"e", u"ì": u"i", u"í": u"i", u"î": u"i", u"ï": u"i", u"ð": u"d", u"ñ": u"n", u"ò": u"o", u"ó": u"o", u"ô": u"o", u"õ": u"o", u"ö": u"o", u"÷": u"/", u"ø": u"o", u"ù": u"u", u"ú": u"u", u"û": u"u", u"ü": u"u", u"ý": u"y", u"þ": u"p", u"ÿ": u"y", u"’":u"'"} def latin2ascii(error): """ error is protion of text from start to end, we just convert first hence return error.start+1 instead of error.end """ return latin_dict[error.object[error.start]], error.start+1 codecs.register_error('latin2ascii', latin2ascii) if __name__ == "__main__": x = u"¼ éíñ§ÐÌëÑ » ¼ ö ® © ’" print x print x.encode('ascii', 'latin2ascii') </code></pre> <p><strong>Why I return <code>error.start + 1</code>:</strong></p> <p>error object returned can be multiple characters, and we convert only first of these e.g. if I add <code>print error.start, error.end</code> to error handler output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 einSDIeN &gt;&gt; 1/4 o R c ' </code></pre> <p>so in second line we get chars from 2-10 but we convert only 2nd hence return 3 as continue point, if we return error.end output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 e &gt;&gt; 1/4 o R c ' </code></pre> <p>As we can see 2-10 portion has been replaced by a single char. off-course it would be faster to just encode whole range in one go and return error.end, but for demonstration purpose I have kept it simple.</p> <p>see <a href="http://docs.python.org/library/codecs.html#codecs.register_error" rel="nofollow">http://docs.python.org/library/codecs.html#codecs.register_error</a> for more details</p>
13
2009-09-05T10:44:40Z
1,383,721
<p>So here are three approaches, more or less as given or suggested in other answers:</p> <pre><code># -*- coding: utf-8 -*- import codecs import unicodedata x = u"Wikipédia, le projet d’encyclopédie" xtd = {ord(u'’'): u"'", ord(u'é'): u'e', } def asciify(error): return xtd[ord(error.object[error.start])], error.end codecs.register_error('asciify', asciify) def ae(): return x.encode('ascii', 'asciify') def ud(): return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore') def tr(): return x.translate(xtd) if __name__ == '__main__': print 'or:', x print 'ae:', ae() print 'ud:', ud() print 'tr:', tr() </code></pre> <p>Run as main, this emits:</p> <pre><code>or: Wikipédia, le projet d’encyclopédie ae: Wikipedia, le projet d'encyclopedie ud: Wikipedia, le projet dencyclopedie tr: Wikipedia, le projet d'encyclopedie </code></pre> <p>showing clearly that the unicodedata-based approach, while it does have the convenience of not needing a translation map <code>xtd</code>, can't translate all characters properly in an automated fashion (it works for accented letters but not for the reverse-apostrophe), so it would also need some auxiliary step to deal explicitly with those (no doubt before what's now its body).</p> <p>Performance is also interesting. On my laptop with Mac OS X 10.5 and system Python 2.5, quite repeatably:</p> <pre><code>$ python -mtimeit -s'import a' 'a.ae()' 100000 loops, best of 3: 7.5 usec per loop $ python -mtimeit -s'import a' 'a.ud()' 100000 loops, best of 3: 3.66 usec per loop $ python -mtimeit -s'import a' 'a.tr()' 10000 loops, best of 3: 21.4 usec per loop </code></pre> <p><code>translate</code> is surprisingly slow (relative to the other approaches). I believe the issue is that the dict is looked into for every character in the <code>translate</code> case (and most are not there), but only for those few characters that ARE there with the <code>asciify</code> approach.</p> <p>So for completeness here's "beefed-up unicodedata" approach:</p> <pre><code>specstd = {ord(u'’'): u"'", } def specials(error): return specstd.get(ord(error.object[error.start]), u''), error.end codecs.register_error('specials', specials) def bu(): return unicodedata.normalize('NFKD', x).encode('ASCII', 'specials') </code></pre> <p>this gives the right output, BUT:</p> <pre><code>$ python -mtimeit -s'import a' 'a.bu()' 100000 loops, best of 3: 10.7 usec per loop </code></pre> <p>...speed isn't all that good any more. So, if speed matters, it's no doubt worth the trouble of making a complete <code>xtd</code> translation dict and using the <code>asciify</code> approach. When a few extra microseconds per translation are no big deal, one might want to consider the <code>bu</code> approach simply for its convenience (only needs a translation dict for, hopefully few, special characters that don't translate correctly with the underlying unicodedata idea).</p>
15
2009-09-05T16:34:29Z
[ "python", "unicode" ]
latin-1 to ascii
1,382,998
<p>I have a unicode string with accented latin chars e.g.</p> <pre><code>n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') </code></pre> <p>I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed</p> <p>What is the fastest way to do that, as it needed to be done for matching a long autocomplete dropdown list</p> <p><strong>Conclusion:</strong> As one my criteria is speed, Lennart's 'register your own error handler for unicode encoding/decoding' gives best result (see Alex's answer), speed difference increases further as more and more chars are latin.</p> <p>Here is the translation table I am using, also modified error handler as it need to take care of whole range of un-encoded char from error.start to error.end</p> <pre><code># -*- coding: utf-8 -*- import codecs """ This is more of visual translation also avoiding multiple char translation e.g. £ may be written as {pound} """ latin_dict = { u"¡": u"!", u"¢": u"c", u"£": u"L", u"¤": u"o", u"¥": u"Y", u"¦": u"|", u"§": u"S", u"¨": u"`", u"©": u"c", u"ª": u"a", u"«": u"&lt;&lt;", u"¬": u"-", u"­": u"-", u"®": u"R", u"¯": u"-", u"°": u"o", u"±": u"+-", u"²": u"2", u"³": u"3", u"´": u"'", u"µ": u"u", u"¶": u"P", u"·": u".", u"¸": u",", u"¹": u"1", u"º": u"o", u"»": u"&gt;&gt;", u"¼": u"1/4", u"½": u"1/2", u"¾": u"3/4", u"¿": u"?", u"À": u"A", u"Á": u"A", u"Â": u"A", u"Ã": u"A", u"Ä": u"A", u"Å": u"A", u"Æ": u"Ae", u"Ç": u"C", u"È": u"E", u"É": u"E", u"Ê": u"E", u"Ë": u"E", u"Ì": u"I", u"Í": u"I", u"Î": u"I", u"Ï": u"I", u"Ð": u"D", u"Ñ": u"N", u"Ò": u"O", u"Ó": u"O", u"Ô": u"O", u"Õ": u"O", u"Ö": u"O", u"×": u"*", u"Ø": u"O", u"Ù": u"U", u"Ú": u"U", u"Û": u"U", u"Ü": u"U", u"Ý": u"Y", u"Þ": u"p", u"ß": u"b", u"à": u"a", u"á": u"a", u"â": u"a", u"ã": u"a", u"ä": u"a", u"å": u"a", u"æ": u"ae", u"ç": u"c", u"è": u"e", u"é": u"e", u"ê": u"e", u"ë": u"e", u"ì": u"i", u"í": u"i", u"î": u"i", u"ï": u"i", u"ð": u"d", u"ñ": u"n", u"ò": u"o", u"ó": u"o", u"ô": u"o", u"õ": u"o", u"ö": u"o", u"÷": u"/", u"ø": u"o", u"ù": u"u", u"ú": u"u", u"û": u"u", u"ü": u"u", u"ý": u"y", u"þ": u"p", u"ÿ": u"y", u"’":u"'"} def latin2ascii(error): """ error is protion of text from start to end, we just convert first hence return error.start+1 instead of error.end """ return latin_dict[error.object[error.start]], error.start+1 codecs.register_error('latin2ascii', latin2ascii) if __name__ == "__main__": x = u"¼ éíñ§ÐÌëÑ » ¼ ö ® © ’" print x print x.encode('ascii', 'latin2ascii') </code></pre> <p><strong>Why I return <code>error.start + 1</code>:</strong></p> <p>error object returned can be multiple characters, and we convert only first of these e.g. if I add <code>print error.start, error.end</code> to error handler output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 einSDIeN &gt;&gt; 1/4 o R c ' </code></pre> <p>so in second line we get chars from 2-10 but we convert only 2nd hence return 3 as continue point, if we return error.end output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 e &gt;&gt; 1/4 o R c ' </code></pre> <p>As we can see 2-10 portion has been replaced by a single char. off-course it would be faster to just encode whole range in one go and return error.end, but for demonstration purpose I have kept it simple.</p> <p>see <a href="http://docs.python.org/library/codecs.html#codecs.register_error" rel="nofollow">http://docs.python.org/library/codecs.html#codecs.register_error</a> for more details</p>
13
2009-09-05T10:44:40Z
11,955,764
<p>The awesome <a href="http://pypi.python.org/pypi/Unidecode/">unidecode</a> module does this for you:</p> <pre><code>&gt;&gt;&gt; import unidecode &gt;&gt;&gt; n = unicode('Wikipédia, le projet d’encyclopédie','utf-8') &gt;&gt;&gt; unidecode.unidecode(n) "Wikipedia, le projet d'encyclopedie" </code></pre>
6
2012-08-14T15:29:59Z
[ "python", "unicode" ]
latin-1 to ascii
1,382,998
<p>I have a unicode string with accented latin chars e.g.</p> <pre><code>n=unicode('Wikipédia, le projet d’encyclopédie','utf-8') </code></pre> <p>I want to convert it to plain ascii i.e. 'Wikipedia, le projet dencyclopedie', so all acute/accent,cedilla etc should get removed</p> <p>What is the fastest way to do that, as it needed to be done for matching a long autocomplete dropdown list</p> <p><strong>Conclusion:</strong> As one my criteria is speed, Lennart's 'register your own error handler for unicode encoding/decoding' gives best result (see Alex's answer), speed difference increases further as more and more chars are latin.</p> <p>Here is the translation table I am using, also modified error handler as it need to take care of whole range of un-encoded char from error.start to error.end</p> <pre><code># -*- coding: utf-8 -*- import codecs """ This is more of visual translation also avoiding multiple char translation e.g. £ may be written as {pound} """ latin_dict = { u"¡": u"!", u"¢": u"c", u"£": u"L", u"¤": u"o", u"¥": u"Y", u"¦": u"|", u"§": u"S", u"¨": u"`", u"©": u"c", u"ª": u"a", u"«": u"&lt;&lt;", u"¬": u"-", u"­": u"-", u"®": u"R", u"¯": u"-", u"°": u"o", u"±": u"+-", u"²": u"2", u"³": u"3", u"´": u"'", u"µ": u"u", u"¶": u"P", u"·": u".", u"¸": u",", u"¹": u"1", u"º": u"o", u"»": u"&gt;&gt;", u"¼": u"1/4", u"½": u"1/2", u"¾": u"3/4", u"¿": u"?", u"À": u"A", u"Á": u"A", u"Â": u"A", u"Ã": u"A", u"Ä": u"A", u"Å": u"A", u"Æ": u"Ae", u"Ç": u"C", u"È": u"E", u"É": u"E", u"Ê": u"E", u"Ë": u"E", u"Ì": u"I", u"Í": u"I", u"Î": u"I", u"Ï": u"I", u"Ð": u"D", u"Ñ": u"N", u"Ò": u"O", u"Ó": u"O", u"Ô": u"O", u"Õ": u"O", u"Ö": u"O", u"×": u"*", u"Ø": u"O", u"Ù": u"U", u"Ú": u"U", u"Û": u"U", u"Ü": u"U", u"Ý": u"Y", u"Þ": u"p", u"ß": u"b", u"à": u"a", u"á": u"a", u"â": u"a", u"ã": u"a", u"ä": u"a", u"å": u"a", u"æ": u"ae", u"ç": u"c", u"è": u"e", u"é": u"e", u"ê": u"e", u"ë": u"e", u"ì": u"i", u"í": u"i", u"î": u"i", u"ï": u"i", u"ð": u"d", u"ñ": u"n", u"ò": u"o", u"ó": u"o", u"ô": u"o", u"õ": u"o", u"ö": u"o", u"÷": u"/", u"ø": u"o", u"ù": u"u", u"ú": u"u", u"û": u"u", u"ü": u"u", u"ý": u"y", u"þ": u"p", u"ÿ": u"y", u"’":u"'"} def latin2ascii(error): """ error is protion of text from start to end, we just convert first hence return error.start+1 instead of error.end """ return latin_dict[error.object[error.start]], error.start+1 codecs.register_error('latin2ascii', latin2ascii) if __name__ == "__main__": x = u"¼ éíñ§ÐÌëÑ » ¼ ö ® © ’" print x print x.encode('ascii', 'latin2ascii') </code></pre> <p><strong>Why I return <code>error.start + 1</code>:</strong></p> <p>error object returned can be multiple characters, and we convert only first of these e.g. if I add <code>print error.start, error.end</code> to error handler output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 einSDIeN &gt;&gt; 1/4 o R c ' </code></pre> <p>so in second line we get chars from 2-10 but we convert only 2nd hence return 3 as continue point, if we return error.end output is</p> <pre><code>¼ éíñ§ÐÌëÑ » ¼ ö ® © ’ 0 1 2 10 11 12 13 14 15 16 17 18 19 20 21 22 1/4 e &gt;&gt; 1/4 o R c ' </code></pre> <p>As we can see 2-10 portion has been replaced by a single char. off-course it would be faster to just encode whole range in one go and return error.end, but for demonstration purpose I have kept it simple.</p> <p>see <a href="http://docs.python.org/library/codecs.html#codecs.register_error" rel="nofollow">http://docs.python.org/library/codecs.html#codecs.register_error</a> for more details</p>
13
2009-09-05T10:44:40Z
30,650,136
<p>Package <a href="https://pypi.python.org/pypi/Unihandecode" rel="nofollow"><code>unihandecode</code></a> is</p> <blockquote> <p>US-ASCII transliterations of Unicode text.<br/> an improved version of Python unidecode, that is Python port of Text::Unidecode Perl module by Sean M. Burke .</p> </blockquote> <pre><code>pip install Unihandecode </code></pre> <p>then in <code>python</code></p> <pre><code>import unihandecode print(unihandecode.unidecode(u'Wikipédia, le projet d’encyclopédie')) </code></pre> <p>prints <code>Wikipedia, le projet d'encyclopedie</code>.</p>
0
2015-06-04T17:13:43Z
[ "python", "unicode" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
1,383,149
<p>Although you installed it, Python can apparently not find the module psycopg2. This is usually due to the module not being in Python's path. See if you can find a folder named psycopg2 in <code>/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages</code>. If it's not there, did MacPorts tell you where it put psycopg2? If you can locate it, just move it to the <code>site-packages</code> directory and you should be fine.</p>
3
2009-09-05T11:49:09Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
1,383,153
<p>There seems to be a problem with your <code>psycopg2</code> installation – Python does not find it. This is a Python installation problem, not a Django issue.</p> <p>You can try to load it manually using the Python interpreter and see if it works:</p> <pre><code>$ python &gt;&gt;&gt; import psycopg2 </code></pre> <p>If you get an <code>ImportError</code> exception, your installation is erroneous. To get a list of all directories Python looks for modules, use <code>sys.path</code>:</p> <pre><code>$ python &gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.path </code></pre> <p>You can also add custom directories to Python's module search path by modifying the <code>sys.path</code> variable. Do this somewhere before the respective <code>import</code> statement(s):</p> <pre><code>import sys sys.path.append("my-path") # ... import psycopg2 </code></pre>
24
2009-09-05T11:51:18Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
5,148,709
<p>For the record I got the same error for a different reason:</p> <p>I had put</p> <pre><code>'ENGINE': 'django.db.backends.postgresql' </code></pre> <p>instead of</p> <pre><code>'ENGINE': 'django.db.backends.postgresql_psycopg2' </code></pre> <p>in <code>settings.py</code></p>
10
2011-02-28T23:14:05Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
5,170,613
<p>Tim's answer worked for me too. By default, settings.py shows options like 'postgresql_psycopg2', 'mysql', etc, without a package name. Prefixing with 'django.db.backends.' worked for me (for postgresql_psycopg2, at least).</p>
0
2011-03-02T16:45:34Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
6,420,799
<p>Yes Tim's answer works for me too.It works without prefix 'django.db.backends.' also. But remember to create database or schema you mentioned in settings.py:</p> <pre><code>DATABASE_NAME = 'your_db_name' </code></pre> <p>manually using your database client so when you run 'python manage.py syncdb' you don't get the same problem. I was stuck because i didn't create it manually. I got the same problem may be because I used buildout. </p>
1
2011-06-21T05:37:51Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
6,648,494
<p>I got the same error, but it was because I was using <code>python26 ./manage.py runserver</code> when my virtualenv only had <code>python</code> and <code>python2.6</code> executables (thus the system <code>python26</code> was being used, which didn't have <code>psycopg2</code> installed</p>
1
2011-07-11T09:59:46Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
9,498,200
<p>Here's the solution: <a href="http://initd.org/psycopg/install/" rel="nofollow">http://initd.org/psycopg/install/</a> You've to install python-dev and libpq-dev libraries before executing "easy_install psycopg2"</p>
2
2012-02-29T11:24:07Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
10,399,009
<p>If you have <code>pip</code> installed, simply install the missing extension by running:</p> <pre><code>$ pip install psycopg2 </code></pre>
14
2012-05-01T14:18:47Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
11,973,485
<p>I realized I didn't have psycopg2 installed</p> <pre><code>aptitude install python-psycopg2 </code></pre> <p>Worked like a charm</p>
3
2012-08-15T16:46:49Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
27,580,910
<p>For me, psycopg2 was indeed installed, but not into the virtualenv in which Django was running. These two steps fixed it:</p> <pre><code>sudo apt-get build-dep python-psycopg2 sudo /opt/myenv/bin/pip install psycopg2 </code></pre>
0
2014-12-20T13:59:41Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
31,955,669
<p>I had this issue recently after updating homebrew on OSX. psycopg2 was already listed in my virtualenv I just reinstalled psycopg2 and it worked again</p> <p><code>pip install --forece-reinstall psycopg2</code></p>
0
2015-08-12T03:47:32Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
32,443,055
<p>I'm on Windows and had installed psycopg2, but the 64 bit version. So my fix was to download the 32 bit one from <a href="http://www.stickpeople.com/projects/python/win-psycopg/" rel="nofollow">here</a> then in PowerShell with my virtual environment activated, my fix was: </p> <pre><code>pip uninstall psycopg2 easy_install C:\WHEREVER_I_DOWNLOADED_IT\psycopg2-2.6.1.win32-py3.4-pg9.4.4-release.exe </code></pre> <p>(The Windows Python 3.4 installer automatically installs easy_install and pip, and pip is the easiest way to remove the package, even if originally installed using easy_install.)</p>
0
2015-09-07T16:43:39Z
[ "python", "django", "django-syncdb" ]
Django/Python Beginner: Error when executing python manage.py syncdb - psycopg2 not found
1,383,126
<p>I have Pythong2.6, psycopg2 and pgAdmin3 installed using Macports. My settings.py is:</p> <pre><code>DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite' # Or path to database file if using sqlite3. DATABASE_USER = 'postgres' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. </code></pre> <p>The error I get when I run python manage.py syncdb is:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 221, in execute self.validate() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please note, I am a complete beginner in this stuff. I am originally a PHP-guy and trying out Python for a small personal project. Do I need to "turn on" Postgres?</p> <p>Also, when I sudo python manage.py runserver 8080 I get this error:</p> <pre><code>Validating models... Unhandled exception in thread started by &lt;function inner_run at 0x1242670&gt; Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/validation.py", line 22, in get_validation_errors from django.db import models, connection File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 41, in &lt;module&gt; backend = load_backend(settings.DATABASE_ENGINE) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/__init__.py", line 17, in load_backend return import_module('.base', 'django.db.backends.%s' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 22, in &lt;module&gt; raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named psycopg2 </code></pre> <p>Please guide me. Any reply will be appreciated.</p> <p>Thanks,</p> <p>Wenbert!</p>
21
2009-09-05T11:40:31Z
32,607,270
<p>THIS HAS HELPED ME:</p> <p>I just added PostgreSQL bin path to ENV and it was able to fine the needed dll: C:\Program Files (x86)\PostgreSQL\9.4\bin</p> <p><a href="https://groups.google.com/forum/#!topic/robotframework-users/qLq9KvHe1wE" rel="nofollow">https://groups.google.com/forum/#!topic/robotframework-users/qLq9KvHe1wE</a></p>
0
2015-09-16T11:26:06Z
[ "python", "django", "django-syncdb" ]
Can I use __init__.py to define global variables?
1,383,239
<p>I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the <code>__init__.py</code> file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules?</p> <p>Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.</p>
46
2009-09-05T12:33:03Z
1,383,248
<p>You cannot do that. You will have to explicitely import your constants into each individual module's namespace. The best way to achieve this is to define your constants in a "config" module and import it everywhere you require it:</p> <pre><code># mypackage/config.py MY_CONST = 17 # mypackage/main.py from mypackage.config import * </code></pre>
25
2009-09-05T12:38:56Z
[ "python", "global-variables", "module", "packages", "init" ]
Can I use __init__.py to define global variables?
1,383,239
<p>I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the <code>__init__.py</code> file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules?</p> <p>Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.</p>
46
2009-09-05T12:33:03Z
1,383,281
<p>You should be able to put them in __init__.py. This is done all the time.</p> <p>mypackage/__init__.py:</p> <pre><code>MY_CONSTANT = 42 </code></pre> <p>mypackage/mymodule.py:</p> <pre><code>from mypackage import MY_CONSTANT print "my constant is", MY_CONSTANT </code></pre> <p>Then, import mymodule:</p> <pre><code>&gt;&gt;&gt; from mypackage import mymodule my constant is 42 </code></pre> <p>Still, if you do have constants, it would be reasonable (best practices, probably) to put them in a separate module (constants.py, config.py, ...) and then if you want them in the package namespace, import them.</p> <p>mypackage/__init__.py:</p> <pre><code>from mypackage.constants import * </code></pre> <p>Still, this doesn't automatically include the constants in the namespaces of the package modules. Each of the modules in the package will still have to import constants explicitly either from mypackage or from mypackage.constants.</p>
75
2009-09-05T12:57:05Z
[ "python", "global-variables", "module", "packages", "init" ]
Can I use __init__.py to define global variables?
1,383,239
<p>I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the <code>__init__.py</code> file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules?</p> <p>Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.</p>
46
2009-09-05T12:33:03Z
1,383,549
<p>You can define global variables from anywhere, but it is a really bad idea. import the <code>__builtin__</code> module and modify or add attributes to this modules, and suddenly you have new builtin constants or functions. In fact, when my application installs gettext, I get the _() function in all my modules, without importing anything. So this is possible, but of course only for Application-type projects, not for reusable packages or modules.</p> <p>And I guess no one would recommend this practice anyway. What's wrong with a namespace? Said application has the version module, so that I have "global" variables available like <code>version.VERSION</code>, <code>version.PACKAGE_NAME</code> etc.</p>
2
2009-09-05T15:09:14Z
[ "python", "global-variables", "module", "packages", "init" ]
Can I use __init__.py to define global variables?
1,383,239
<p>I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the <code>__init__.py</code> file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules?</p> <p>Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.</p>
46
2009-09-05T12:33:03Z
38,275,781
<p>Just wanted to add that constants can be employed using a config.ini file and parsed in the script using the configparser library. This way you could have constants for multiple circumstances. For instance if you had parameter constants for two separate url requests just label them like so:</p> <pre><code>mymodule/config.ini [request0] conn = 'admin@localhost' pass = 'admin' ... [request1] conn = 'barney@localhost' pass = 'dinosaur' ... </code></pre> <p>I found the documentation on the Python website very helpful. I am not sure if there are any differences between Python 2 and 3 so here are the links to both:</p> <p>For Python 3: <a href="https://docs.python.org/3/library/configparser.html#module-configparser" rel="nofollow">https://docs.python.org/3/library/configparser.html#module-configparser</a> </p> <p>For Python 2: <a href="https://docs.python.org/2/library/configparser.html#module-configparser" rel="nofollow">https://docs.python.org/2/library/configparser.html#module-configparser</a></p>
0
2016-07-08T21:41:23Z
[ "python", "global-variables", "module", "packages", "init" ]
Logging, StreamHandler and standard streams
1,383,254
<p>I can't figure out how to log info-level messages to stdout, but everything else to stderr. I already read this <a href="http://docs.python.org/library/logging.html">http://docs.python.org/library/logging.html</a>. Any suggestion?</p>
37
2009-09-05T12:45:17Z
1,383,365
<p>The following script, <code>log1.py</code>:</p> <pre><code>import logging, sys class SingleLevelFilter(logging.Filter): def __init__(self, passlevel, reject): self.passlevel = passlevel self.reject = reject def filter(self, record): if self.reject: return (record.levelno != self.passlevel) else: return (record.levelno == self.passlevel) h1 = logging.StreamHandler(sys.stdout) f1 = SingleLevelFilter(logging.INFO, False) h1.addFilter(f1) rootLogger = logging.getLogger() rootLogger.addHandler(h1) h2 = logging.StreamHandler(sys.stderr) f2 = SingleLevelFilter(logging.INFO, True) h2.addFilter(f2) rootLogger.addHandler(h2) logger = logging.getLogger("my.logger") logger.setLevel(logging.DEBUG) logger.debug("A DEBUG message") logger.info("An INFO message") logger.warning("A WARNING message") logger.error("An ERROR message") logger.critical("A CRITICAL message") </code></pre> <p>when run, produces the following results.</p> <pre> C:\temp>log1.py A DEBUG message An INFO message A WARNING message An ERROR message A CRITICAL message </pre> <p>As you'd expect, since on a terminal <code>sys.stdout</code> and <code>sys.stderr</code> are the same. Now, let's redirect stdout to a file, <code>tmp</code>:</p> <pre> C:\temp>log1.py >tmp A DEBUG message A WARNING message An ERROR message A CRITICAL message </pre> <p>So the INFO message has not been printed to the terminal - but the messages directed to <code>sys.stderr</code> <em>have</em> been printed. Let's look at what's in <code>tmp</code>:</p> <pre> C:\temp>type tmp An INFO message </pre> <p>So that approach appears to do what you want.</p>
60
2009-09-05T13:46:23Z
[ "python", "logging" ]
Logging, StreamHandler and standard streams
1,383,254
<p>I can't figure out how to log info-level messages to stdout, but everything else to stderr. I already read this <a href="http://docs.python.org/library/logging.html">http://docs.python.org/library/logging.html</a>. Any suggestion?</p>
37
2009-09-05T12:45:17Z
24,956,305
<p>Generally, I think it makes sense to <strong>redirect messages lower than <code>WARNING</code> to <em>stdout</em>, instead of only <code>INFO</code> messages</strong>.</p> <p>Based on <em>Vinay Sajip</em>'s excellent answer, I came up with this:</p> <pre><code>class MaxLevelFilter(Filter): '''Filters (lets through) all messages with level &lt; LEVEL''' def __init__(self, level): self.level = level def filter(self, record): return record.levelno &lt; self.level # "&lt;" instead of "&lt;=": since logger.setLevel is inclusive, this should be exclusive MIN_LEVEL= DEBUG #... stdout_hdlr = StreamHandler(sys.stdout) stderr_hdlr = StreamHandler(sys.stderr) lower_than_warning= MaxLevelFilter(WARNING) stdout_hdlr.addFilter( lower_than_warning ) #messages lower than WARNING go to stdout stdout_hdlr.setLevel( MIN_LEVEL ) stderr_hdlr.setLevel( max(MIN_LEVEL, WARNING) ) #messages &gt;= WARNING ( and &gt;= STDOUT_LOG_LEVEL ) go to stderr #... </code></pre>
9
2014-07-25T12:56:45Z
[ "python", "logging" ]
Logging, StreamHandler and standard streams
1,383,254
<p>I can't figure out how to log info-level messages to stdout, but everything else to stderr. I already read this <a href="http://docs.python.org/library/logging.html">http://docs.python.org/library/logging.html</a>. Any suggestion?</p>
37
2009-09-05T12:45:17Z
28,743,317
<p>Since my edit was rejected, here's my answer. @goncalopp's answer is good but doesn't stand alone or work out of the box. Here's my improved version:</p> <pre><code>import sys, logging class LogFilter(logging.Filter): """Filters (lets through) all messages with level &lt; LEVEL""" # http://stackoverflow.com/a/24956305/408556 def __init__(self, level): self.level = level def filter(self, record): # "&lt;" instead of "&lt;=": since logger.setLevel is inclusive, this should # be exclusive return record.levelno &lt; self.level MIN_LEVEL = logging.DEBUG stdout_hdlr = logging.StreamHandler(sys.stdout) stderr_hdlr = logging.StreamHandler(sys.stderr) log_filter = LogFilter(logging.WARNING) stdout_hdlr.addFilter(log_filter) stdout_hdlr.setLevel(MIN_LEVEL) stderr_hdlr.setLevel(max(MIN_LEVEL, logging.WARNING)) # messages lower than WARNING go to stdout # messages &gt;= WARNING (and &gt;= STDOUT_LOG_LEVEL) go to stderr rootLogger = logging.getLogger() rootLogger.addHandler(stdout_hdlr) rootLogger.addHandler(stderr_hdlr) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Example Usage &gt;&gt;&gt; logger.debug("A DEBUG message") &gt;&gt;&gt; logger.info("An INFO message") &gt;&gt;&gt; logger.warning("A WARNING message") &gt;&gt;&gt; logger.error("An ERROR message") &gt;&gt;&gt; logger.critical("A CRITICAL message") </code></pre>
3
2015-02-26T13:07:25Z
[ "python", "logging" ]
Code organization in Python: Where is a good place to put obscure methods?
1,383,590
<p>I have a class called <code>Path</code> for which there are defined about 10 methods, in a dedicated module <code>Path.py</code>. Recently I had a need to write 5 more methods for <code>Path</code>, however these new methods are quite obscure and technical and 90% of the time they are irrelevant.</p> <p>Where would be a good place to put them so their context is clear? Of course I can just put them with the class definition, but I don't like that because I like to keep the important things separate from the obscure things.</p> <p>Currently I have these methods as functions that are defined in a separate module, just to keep things separate, but it would be better to have them as bound methods. (Currently they take the <code>Path</code> instance as an explicit parameter.) </p> <p>Does anyone have a suggestion?</p>
2
2009-09-05T15:25:58Z
1,383,601
<p>I would just prepend the names with an underscore <code>_</code>, to show that the reader shouldn't bother about them. It's conventionally the same thing as private members in other languages.</p>
0
2009-09-05T15:31:54Z
[ "python", "code-organization" ]
Code organization in Python: Where is a good place to put obscure methods?
1,383,590
<p>I have a class called <code>Path</code> for which there are defined about 10 methods, in a dedicated module <code>Path.py</code>. Recently I had a need to write 5 more methods for <code>Path</code>, however these new methods are quite obscure and technical and 90% of the time they are irrelevant.</p> <p>Where would be a good place to put them so their context is clear? Of course I can just put them with the class definition, but I don't like that because I like to keep the important things separate from the obscure things.</p> <p>Currently I have these methods as functions that are defined in a separate module, just to keep things separate, but it would be better to have them as bound methods. (Currently they take the <code>Path</code> instance as an explicit parameter.) </p> <p>Does anyone have a suggestion?</p>
2
2009-09-05T15:25:58Z
1,383,607
<p>If the method is relevant to the Path - no matter how obscure - I think it should reside within the class itself.</p> <p>If you have multiple places where you have path-related functionality, it leads to problems. For example, if you want to check if some functionality already exists, how will a new programmer know to check the other, less obvious places?</p> <p>I think a good practice might be to order functions by importance. As you may have heard, some suggest putting public members of classes first, and private/protected ones after. You could consider putting the common methods in your class higher than the obscure ones.</p>
4
2009-09-05T15:33:41Z
[ "python", "code-organization" ]
Code organization in Python: Where is a good place to put obscure methods?
1,383,590
<p>I have a class called <code>Path</code> for which there are defined about 10 methods, in a dedicated module <code>Path.py</code>. Recently I had a need to write 5 more methods for <code>Path</code>, however these new methods are quite obscure and technical and 90% of the time they are irrelevant.</p> <p>Where would be a good place to put them so their context is clear? Of course I can just put them with the class definition, but I don't like that because I like to keep the important things separate from the obscure things.</p> <p>Currently I have these methods as functions that are defined in a separate module, just to keep things separate, but it would be better to have them as bound methods. (Currently they take the <code>Path</code> instance as an explicit parameter.) </p> <p>Does anyone have a suggestion?</p>
2
2009-09-05T15:25:58Z
1,383,613
<p>Put them in the Path class, and document that they are "obscure" either with comments or docstrings. Separate them at the end if you like.</p>
0
2009-09-05T15:36:20Z
[ "python", "code-organization" ]
Code organization in Python: Where is a good place to put obscure methods?
1,383,590
<p>I have a class called <code>Path</code> for which there are defined about 10 methods, in a dedicated module <code>Path.py</code>. Recently I had a need to write 5 more methods for <code>Path</code>, however these new methods are quite obscure and technical and 90% of the time they are irrelevant.</p> <p>Where would be a good place to put them so their context is clear? Of course I can just put them with the class definition, but I don't like that because I like to keep the important things separate from the obscure things.</p> <p>Currently I have these methods as functions that are defined in a separate module, just to keep things separate, but it would be better to have them as bound methods. (Currently they take the <code>Path</code> instance as an explicit parameter.) </p> <p>Does anyone have a suggestion?</p>
2
2009-09-05T15:25:58Z
1,383,623
<p>If you're keen to put those methods in a different source file at any cost, AND keen to have them at methods at any cost, you can achieve both goals by using the different source file to define a mixin class and having your Path class import that method and multiply-inherit from that mixin. So, technically, it's quite feasible.</p> <p>However, I would not recommend this course of action: it's worth using "the big guns" (such as multiple inheritance) only to serve important goals (such as reuse and removing repetition), and separating methods out in this way is not really a particularly crucial goal.</p> <p>If those "obscure methods" played no role you would not be implementing them, so they must have SOME importance, after all; so I'd just clarify in docstrings and comments what they're for, maybe explicitly mention that they're rarely needed, and leave it at that.</p>
2
2009-09-05T15:39:15Z
[ "python", "code-organization" ]
Code organization in Python: Where is a good place to put obscure methods?
1,383,590
<p>I have a class called <code>Path</code> for which there are defined about 10 methods, in a dedicated module <code>Path.py</code>. Recently I had a need to write 5 more methods for <code>Path</code>, however these new methods are quite obscure and technical and 90% of the time they are irrelevant.</p> <p>Where would be a good place to put them so their context is clear? Of course I can just put them with the class definition, but I don't like that because I like to keep the important things separate from the obscure things.</p> <p>Currently I have these methods as functions that are defined in a separate module, just to keep things separate, but it would be better to have them as bound methods. (Currently they take the <code>Path</code> instance as an explicit parameter.) </p> <p>Does anyone have a suggestion?</p>
2
2009-09-05T15:25:58Z
1,383,639
<p>Oh wait, I thought of something -- I can just define them in the <code>Path.py</code> module, where every obscure method will be a one-liner that will call the function from the separate module that currently exists. With this compromise, the obscure methods will comprise of maybe 10 lines in the end of the file instead of 50% of its bulk.</p>
0
2009-09-05T15:45:08Z
[ "python", "code-organization" ]
Code organization in Python: Where is a good place to put obscure methods?
1,383,590
<p>I have a class called <code>Path</code> for which there are defined about 10 methods, in a dedicated module <code>Path.py</code>. Recently I had a need to write 5 more methods for <code>Path</code>, however these new methods are quite obscure and technical and 90% of the time they are irrelevant.</p> <p>Where would be a good place to put them so their context is clear? Of course I can just put them with the class definition, but I don't like that because I like to keep the important things separate from the obscure things.</p> <p>Currently I have these methods as functions that are defined in a separate module, just to keep things separate, but it would be better to have them as bound methods. (Currently they take the <code>Path</code> instance as an explicit parameter.) </p> <p>Does anyone have a suggestion?</p>
2
2009-09-05T15:25:58Z
8,028,755
<p>I suggest making them accessible from a property of the Path class called something like "Utilties". For example: <code>Path.Utilities.RazzleDazzle</code>. This will help with auto-completion tools and general maintenance.</p>
0
2011-11-06T17:09:05Z
[ "python", "code-organization" ]
You don't have permission to access /index.py on this server
1,383,632
<p>I am setting up a simple test page in Python. I only have two files: .htaccess and index.py. I get a 403 Forbidden error when trying to view the page - how can I fix this?</p> <p>.htaccess:</p> <pre><code>RewriteEngine On AddHandler application/x-httpd-cgi .py DirectoryIndex index.py </code></pre> <p>index.py:</p> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "test" </code></pre>
1
2009-09-05T15:41:05Z
1,383,637
<p>What permissions have you set on <code>index.py</code> (e.g. what does <code>ls -l index.py</code> say, if in Linux or other Unix variants)?</p>
2
2009-09-05T15:44:14Z
[ "python", ".htaccess" ]
remove inner border on gtk.Button
1,383,663
<p>I would like to remove border on a gtk.Button and also set its size fixed. How can I accomplish that? My button looks like that:</p> <pre> b = gtk.Button() b.set_relief(gtk.RELIEF_NONE) </pre> <p>Thanks! p.d: I'm using pygtk</p>
0
2009-09-05T16:01:42Z
1,383,706
<p>You can use <a href="http://www.pygtk.org/docs/pygtk/class-gtkwidget.html#method-gtkwidget--set-size-request" rel="nofollow">gtk.Widget.set_size_request</a> to set a fixed size for the widget. Note that this is generally a bad idea, since the user may want a larger font size than you had planned for, etc.</p> <p>As for removing the border, gtk.Button can often take up more space than you wish it would. You can try to set some of the style properties such as "inner-border" to 0 and see if that gets the result you want. If you need the smallest button possible, you should just gtk.Label inside a gtk.EventBox and handle clicks on the event box. That will use the least amount of pixels.</p>
2
2009-09-05T16:23:23Z
[ "python", "gtk", "pygtk" ]
remove inner border on gtk.Button
1,383,663
<p>I would like to remove border on a gtk.Button and also set its size fixed. How can I accomplish that? My button looks like that:</p> <pre> b = gtk.Button() b.set_relief(gtk.RELIEF_NONE) </pre> <p>Thanks! p.d: I'm using pygtk</p>
0
2009-09-05T16:01:42Z
1,507,847
<p>I don't think the EventBox can send button events like "activated" and "clicked".</p>
-1
2009-10-02T05:22:31Z
[ "python", "gtk", "pygtk" ]
Python data structure for a collection of objects with random access based on an attribute
1,383,693
<p>I need a collection of objects which can be looked up by a certain (unique) attribute common to each of the objects. Right now I am using a dicitionary assigning the dictionary key to the attribute. Here is an example of what I have now:</p> <pre><code>class Item(): def __init__(self, uniq_key, title=None): self.key = uniq_key self.title = title item_instance_1 = Item("unique_key1", title="foo") item_instance_2 = Item("unique_key3", title="foo") item_instance_3 = Item("unique_key2", title="foo") item_collection = { item_instance_1.key: item_instance_1, item_instance_2.key: item_instance_2, item_instance_3.key: item_instance_3 } item_instance_1.key = "new_key" </code></pre> <p>Now this seems a rather cumbersome solution, as the key is not a reference to the attribute but takes the value of the key-attribute on assignment, meaning that:</p> <ul> <li>the keys of the dictionary duplicate information already present in form of the object attribute and</li> <li>when the object attribute is changed the dictionary key is not updated.</li> </ul> <p>Using a list and iterating through the object seems even more inefficient.</p> <p>So, is there more fitting data structure than dict for this particular case, a collection of objects giving me random access based on a certain object attribute?</p> <p>This would need to work with Python 2.4 as that's what I am stuck with (at work).</p> <p>If it hasn't been obvious, I'm new to Python.</p>
3
2009-09-05T16:15:07Z
1,383,738
<p>Well, dict really is what you want. What may be cumbersome is not the dict itself, but the way you are building it. Here is a slight enhancement to your example, showing how to use a list expression and the dict constructor to easily create your lookup dict. This also shows how to create a multimap kind of dict, to look up matching items given a field value that might be duplicated across items:</p> <pre><code>class Item(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __str__(self): return str(self.__dict__) def __repr__(self): return str(self) allitems = [ Item(key="red", title="foo"), Item(key="green", title="foo"), Item(key="blue", title="foofoo"), ] # if fields are unique itemByKey = dict([(i.key,i) for i in allitems]) # if field value can be duplicated across items # (for Python 2.5 and higher, you could use a defaultdict from # the collections module) itemsByTitle = {} for i in allitems: if i.title in itemsByTitle: itemsByTitle[i.title].append(i) else: itemsByTitle[i.title] = [i] print itemByKey["red"] print itemsByTitle["foo"] </code></pre> <p>Prints:</p> <pre><code>{'key': 'red', 'title': 'foo'} [{'key': 'red', 'title': 'foo'}, {'key': 'green', 'title': 'foo'}] </code></pre>
0
2009-09-05T16:41:32Z
[ "python" ]
Python data structure for a collection of objects with random access based on an attribute
1,383,693
<p>I need a collection of objects which can be looked up by a certain (unique) attribute common to each of the objects. Right now I am using a dicitionary assigning the dictionary key to the attribute. Here is an example of what I have now:</p> <pre><code>class Item(): def __init__(self, uniq_key, title=None): self.key = uniq_key self.title = title item_instance_1 = Item("unique_key1", title="foo") item_instance_2 = Item("unique_key3", title="foo") item_instance_3 = Item("unique_key2", title="foo") item_collection = { item_instance_1.key: item_instance_1, item_instance_2.key: item_instance_2, item_instance_3.key: item_instance_3 } item_instance_1.key = "new_key" </code></pre> <p>Now this seems a rather cumbersome solution, as the key is not a reference to the attribute but takes the value of the key-attribute on assignment, meaning that:</p> <ul> <li>the keys of the dictionary duplicate information already present in form of the object attribute and</li> <li>when the object attribute is changed the dictionary key is not updated.</li> </ul> <p>Using a list and iterating through the object seems even more inefficient.</p> <p>So, is there more fitting data structure than dict for this particular case, a collection of objects giving me random access based on a certain object attribute?</p> <p>This would need to work with Python 2.4 as that's what I am stuck with (at work).</p> <p>If it hasn't been obvious, I'm new to Python.</p>
3
2009-09-05T16:15:07Z
1,383,743
<p>There is actually no duplication of information as you fear: the dict's key, and the object's <code>.key</code> attribute, are just two references to exactly the same object.</p> <p>The only real problem is "what if the <code>.key</code> gets reassigned". Well then, clearly you must use a property that updates all the relevant dicts as well as the instance's attribute; so each object must know all the dicts in which it may be enregistered. Ideally one would want to use weak references for the purpose, to avoid circular dependencies, but, alas, you can't take a <code>weakref.ref</code> (or proxy) to a dict. So, I'm using normal references here, instead (the alternative is not to use <code>dict</code> instances but e.g. some special subclass -- not handy).</p> <pre><code>def enregister(d, obj): obj.ds.append(d) d[obj.key] = obj class Item(object): def __init__(self, uniq_key, title=None): self._key = uniq_key self.title = title self.ds = [] def adjust_key(self, newkey): newds = [d for d in self.ds if self._key in d] for d in newds: del d[self._key] d[newkey] = self self.ds = newds self._key = newkey def get_key(self): return self._key key = property(get_key, adjust_key) </code></pre> <p><strong>Edit</strong>: if you want a single collection with ALL the instances of Item, that's even easier, as you can make the collection a class-level attribute; indeed it can be a WeakValueDictionary to avoid erroneously keeping items alive, if that's what you need. I.e.:</p> <pre><code>class Item(object): all = weakref.WeakValueDictionary() def __init__(self, uniq_key, title=None): self._key = uniq_key self.title = title # here, if needed, you could check that the key # is not ALREADY present in self.all self.all[self._key] = self def adjust_key(self, newkey): # "key non-uniqueness" could be checked here too del self.all[self._key] self.all[newkey] = self self._key = newkey def get_key(self): return self._key key = property(get_key, adjust_key) </code></pre> <p>Now you can use <code>Item.all['akey']</code>, <code>Item.all.get('akey')</code>, <code>for akey in Item.all:</code>, and so forth -- all the rich functionality of dicts.</p>
4
2009-09-05T16:44:02Z
[ "python" ]
Python data structure for a collection of objects with random access based on an attribute
1,383,693
<p>I need a collection of objects which can be looked up by a certain (unique) attribute common to each of the objects. Right now I am using a dicitionary assigning the dictionary key to the attribute. Here is an example of what I have now:</p> <pre><code>class Item(): def __init__(self, uniq_key, title=None): self.key = uniq_key self.title = title item_instance_1 = Item("unique_key1", title="foo") item_instance_2 = Item("unique_key3", title="foo") item_instance_3 = Item("unique_key2", title="foo") item_collection = { item_instance_1.key: item_instance_1, item_instance_2.key: item_instance_2, item_instance_3.key: item_instance_3 } item_instance_1.key = "new_key" </code></pre> <p>Now this seems a rather cumbersome solution, as the key is not a reference to the attribute but takes the value of the key-attribute on assignment, meaning that:</p> <ul> <li>the keys of the dictionary duplicate information already present in form of the object attribute and</li> <li>when the object attribute is changed the dictionary key is not updated.</li> </ul> <p>Using a list and iterating through the object seems even more inefficient.</p> <p>So, is there more fitting data structure than dict for this particular case, a collection of objects giving me random access based on a certain object attribute?</p> <p>This would need to work with Python 2.4 as that's what I am stuck with (at work).</p> <p>If it hasn't been obvious, I'm new to Python.</p>
3
2009-09-05T16:15:07Z
1,383,744
<p>There are a number of great things you can do here. One example would be to let the class keep track of everything:</p> <pre><code>class Item(): _member_dict = {} @classmethod def get_by_key(cls,key): return cls._member_dict[key] def __init__(self, uniq_key, title=None): self.key = uniq_key self.__class__._member_dict[key] = self self.title = title &gt;&gt;&gt; i = Item('foo') &gt;&gt;&gt; i == Item.get_by_key('foo') True </code></pre> <p>Note you will retain the update problem: if <code>key</code> changes, the <code>_member_dict</code> falls out of sync. This is where encapsulation will come in handy: make it (practically) impossible to change <code>key</code> without updating the dictionary. For a good tutorial on how to do that, see <a href="http://adam.gomaa.us/blog/2008/aug/11/the-python-property-builtin/" rel="nofollow">this tutorial</a>.</p>
2
2009-09-05T16:44:19Z
[ "python" ]
Python data structure for a collection of objects with random access based on an attribute
1,383,693
<p>I need a collection of objects which can be looked up by a certain (unique) attribute common to each of the objects. Right now I am using a dicitionary assigning the dictionary key to the attribute. Here is an example of what I have now:</p> <pre><code>class Item(): def __init__(self, uniq_key, title=None): self.key = uniq_key self.title = title item_instance_1 = Item("unique_key1", title="foo") item_instance_2 = Item("unique_key3", title="foo") item_instance_3 = Item("unique_key2", title="foo") item_collection = { item_instance_1.key: item_instance_1, item_instance_2.key: item_instance_2, item_instance_3.key: item_instance_3 } item_instance_1.key = "new_key" </code></pre> <p>Now this seems a rather cumbersome solution, as the key is not a reference to the attribute but takes the value of the key-attribute on assignment, meaning that:</p> <ul> <li>the keys of the dictionary duplicate information already present in form of the object attribute and</li> <li>when the object attribute is changed the dictionary key is not updated.</li> </ul> <p>Using a list and iterating through the object seems even more inefficient.</p> <p>So, is there more fitting data structure than dict for this particular case, a collection of objects giving me random access based on a certain object attribute?</p> <p>This would need to work with Python 2.4 as that's what I am stuck with (at work).</p> <p>If it hasn't been obvious, I'm new to Python.</p>
3
2009-09-05T16:15:07Z
1,383,798
<p>Editing to correct the problem I had - which was due to my "collection = dict()" default parameter <code>(*bonk*).</code> Now, each call to the function will return a class with its own collection as intended - this for convenience in case more than one such collection should be needed. Also am putting the collection in the class and just returning the class instead of the two separately in a tuple as before. (Leaving the default container here as dict(), but that could be changed to Alex's WeakValueDictionary, which is of course very cool.)</p> <pre><code>def make_item_collection(container = None): ''' Create a class designed to be collected in a specific collection. ''' container = dict() if container is None else container class CollectedItem(object): collection = container def __init__(self, key, title=None): self.key = key CollectedItem.collection[key] = self self.title = title def update_key(self, new_key): CollectedItem.collection[ new_key] = CollectedItem.collection.pop(self.key) self.key = new_key return CollectedItem # Usage Demo... Item = make_item_collection() my_collection = Item.collection item_instance_1 = Item("unique_key1", title="foo1") item_instance_2 = Item("unique_key2", title="foo2") item_instance_3 = Item("unique_key3", title="foo3") for k,v in my_collection.iteritems(): print k, v.title item_instance_1.update_key("new_unique_key") print '****' for k,v in my_collection.iteritems(): print k, v.title </code></pre> <p>And here's the output in Python 2.5.2:</p> <pre><code>unique_key1 foo1 unique_key2 foo2 unique_key3 foo3 **** new_unique_key foo1 unique_key2 foo2 unique_key3 foo3 </code></pre>
0
2009-09-05T17:08:05Z
[ "python" ]
OS X - multiple python versions, PATH and /usr/local
1,383,863
<p>If you install multiple versions of python (I currently have the default 2.5, installed 3.0.1 and now installed 2.6.2), it automatically puts stuff in <code>/usr/local</code>, and it also adjusts the path to include the <code>/Library/Frameworks/Python/Versions/theVersion/bin</code>, but whats the point of that when <code>/usr/local</code> is already on the PATH, and all installed versions (except the default 2.5, which is in <code>/usr/bin</code>) are in there? I removed the python framework paths from my PATH in <code>.bash_profile</code>, and I can still type <code>"python -V" =&gt; "Python 2.5.1"</code>, <code>"python2.6 -V" =&gt; "Python 2.6.2"</code>,<code>"python3 -V" =&gt; "Python 3.0.1"</code>. Just wondering why it puts it in <code>/usr/local</code>, and also changes the PATH. And is what I did fine? Thanks.</p> <p>Also, the 2.6 installation made it the 'current' one, having <code>.../Python.framework/Versions/Current</code> point to 2.6., So plain 'python' things in <code>/usr/local/bin</code> point to 2.6, but it doesn't matter because <code>usr/bin</code> comes first and things with the same name in there point to 2.5 stuff.. Anyway, 2.5 comes with leopard, I installed 3.0.1 just to have the latest version (that has a dmg file), and now I installed 2.6.2 for use with pygame.</p> <p>EDIT: OK, here's how I understand it. When you install, say, Python 2.6.2: A bunch of symlinks are added to <code>/usr/local/bin</code>, so when there's a <code>#! /usr/local/bin/python</code> shebang in a python script, it will run, and in <code>/Applications/Python 2.6</code>, the Python Launcher is made default application to run .py files, which uses <code>/usr/local/bin/pythonw</code>, and <code>/Library/Frameworks/Python.framework/Versions/2.6/bin</code> is created and added to the front of the path, so <code>which python</code> will get the python in there, and also <code>#! /usr/bin/env python</code> shebang's will run correctly.</p>
5
2009-09-05T17:40:24Z
1,383,891
<p>There's no a priori guarantee that /usr/local/bin will stay on the PATH (especially it will not necessarily stay "in front of" /usr/bin!-), so it's perfectly reasonable for an installer to ensure the specifically needed /Library/.../bin directory does get on the PATH. Plus, it may be the case that the /Library/.../bin has supplementary stuff that doesn't get symlinked into /usr/local/bin, although I believe that's not currently the case with recent Mac standard distributions of Python.</p> <p>If you know that the way you'll arrange your path, and the exact set of executables you'll be using, are entirely satisfied from /usr/local/bin, then it's quite OK for you to remove the /Library/etc directories from your own path, of course.</p>
5
2009-09-05T17:53:27Z
[ "python", "osx", "path", "multiple-versions" ]
OS X - multiple python versions, PATH and /usr/local
1,383,863
<p>If you install multiple versions of python (I currently have the default 2.5, installed 3.0.1 and now installed 2.6.2), it automatically puts stuff in <code>/usr/local</code>, and it also adjusts the path to include the <code>/Library/Frameworks/Python/Versions/theVersion/bin</code>, but whats the point of that when <code>/usr/local</code> is already on the PATH, and all installed versions (except the default 2.5, which is in <code>/usr/bin</code>) are in there? I removed the python framework paths from my PATH in <code>.bash_profile</code>, and I can still type <code>"python -V" =&gt; "Python 2.5.1"</code>, <code>"python2.6 -V" =&gt; "Python 2.6.2"</code>,<code>"python3 -V" =&gt; "Python 3.0.1"</code>. Just wondering why it puts it in <code>/usr/local</code>, and also changes the PATH. And is what I did fine? Thanks.</p> <p>Also, the 2.6 installation made it the 'current' one, having <code>.../Python.framework/Versions/Current</code> point to 2.6., So plain 'python' things in <code>/usr/local/bin</code> point to 2.6, but it doesn't matter because <code>usr/bin</code> comes first and things with the same name in there point to 2.5 stuff.. Anyway, 2.5 comes with leopard, I installed 3.0.1 just to have the latest version (that has a dmg file), and now I installed 2.6.2 for use with pygame.</p> <p>EDIT: OK, here's how I understand it. When you install, say, Python 2.6.2: A bunch of symlinks are added to <code>/usr/local/bin</code>, so when there's a <code>#! /usr/local/bin/python</code> shebang in a python script, it will run, and in <code>/Applications/Python 2.6</code>, the Python Launcher is made default application to run .py files, which uses <code>/usr/local/bin/pythonw</code>, and <code>/Library/Frameworks/Python.framework/Versions/2.6/bin</code> is created and added to the front of the path, so <code>which python</code> will get the python in there, and also <code>#! /usr/bin/env python</code> shebang's will run correctly.</p>
5
2009-09-05T17:40:24Z
1,384,223
<p>I just noticed/encountered this issue on my Mac. I have Python 2.5.4, 2.6.2, and 3.1.1 on my machine, and was looking for a way to easily change between them at will. That is when I noticed all the symlinks for the executables, which I found in both '/usr/bin' and '/usr/local/bin'. I ripped all the non-version specific symlinks out, leaving python2.5, python2.6, etc, and wrote a bash shell script that I can run as root to change one symlink I use to direct the path to the version of my choice</p> <p>'/Library/Frameworks/Python.framework/Versions/Current'</p> <p>The only bad thing about ripping the symlinks out, is if some other application needed them for some reason. My opinion as to why these symlinks are created is similar to Alex's assessment, the installer is trying to cover all of the bases. All of my versions have been installed by an installer, though I've been trying to compile my own to enable full 64-bit support, and when compiling and installing your own you can choose to not have the symlinks created or the PATH modified during installation.</p>
0
2009-09-05T20:41:25Z
[ "python", "osx", "path", "multiple-versions" ]
(re)Using dictionaries in django views
1,384,246
<p>I have this dictionary in my apps model file:</p> <pre><code>TYPE_DICT = ( ("1", "Shopping list"), ("2", "Gift Wishlist"), ("3", "test list type"), ) </code></pre> <p>model, which uses this dict is this:</p> <pre><code>class List(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) type = models.PositiveIntegerField(choices=TYPE_DICT) </code></pre> <p>I want to re-use it in my views and imported it from apps.models. I am creating a list of dictioneries to use in my view like this:</p> <pre><code>bunchofdicts = List.objects.filter(user=request.user) array = [] for dict in bunchofdicts: ListDict = {'Name':dict.name, 'type':TYPE_DICT[dict.type], 'edit':'placeholder' } array.append(ListDict) </code></pre> <p>When i use this list in my template then it gives me very strange results. Instead of returning me the type of the list (shopping list) it returns me ('2', 'Gift Wishlist').</p> <p>So i can understand what it is doing (in ths case, the dict.type equals 1, and it should return me "shopping list" , but it returns me [1] - second, element in list). What i do not understand, why doing exactly the same thing in python shell gives different results.</p> <p>doing it the way i do in django ( TYPE_DICT[dict.type] ), works as described above and creates error in python shell. using TYPE_DICT[str(dict.type)] in python shell works just fine, but creates this error in django:</p> <pre><code>TypeError at /list/ tuple indices must be integers, not str Request Method: GET Request URL: http://127.0.0.1/list/ Exception Type: TypeError Exception Value: tuple indices must be integers, not str Exception Location: /home/projects/tst/list/views.py in list, line 22 Python Executable: /usr/bin/python Python Version: 2.6.2 </code></pre> <p>Perhaps i did something wrong or different in python shell. What i did was:</p> <pre><code>python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; dict = {'1':'shoppinglist', '2':'giftlist','3':'testlist'} &gt;&gt;&gt; print dict[1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(1)] shoppinglist &gt;&gt;&gt; x = 1 &gt;&gt;&gt; print dict[x] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(x)] shoppinglist &gt;&gt;&gt; </code></pre> <p>so what is wrong here?</p> <p>Alan</p>
1
2009-09-05T20:55:39Z
1,384,258
<p>Your <code>TYPE_DICT</code> in your models file isn't a dictionary: it's a tuple of tuples.</p> <p>You can easily make a dictionary from it though if you want:</p> <pre><code>TYPE_DICT_DICT = dict(TYPE_DICT) </code></pre> <p>then you can use <code>TYPE_DICT_DICT</code> as a real dictionary.</p>
6
2009-09-05T21:02:22Z
[ "python", "django", "list", "dictionary", "tuples" ]
(re)Using dictionaries in django views
1,384,246
<p>I have this dictionary in my apps model file:</p> <pre><code>TYPE_DICT = ( ("1", "Shopping list"), ("2", "Gift Wishlist"), ("3", "test list type"), ) </code></pre> <p>model, which uses this dict is this:</p> <pre><code>class List(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) type = models.PositiveIntegerField(choices=TYPE_DICT) </code></pre> <p>I want to re-use it in my views and imported it from apps.models. I am creating a list of dictioneries to use in my view like this:</p> <pre><code>bunchofdicts = List.objects.filter(user=request.user) array = [] for dict in bunchofdicts: ListDict = {'Name':dict.name, 'type':TYPE_DICT[dict.type], 'edit':'placeholder' } array.append(ListDict) </code></pre> <p>When i use this list in my template then it gives me very strange results. Instead of returning me the type of the list (shopping list) it returns me ('2', 'Gift Wishlist').</p> <p>So i can understand what it is doing (in ths case, the dict.type equals 1, and it should return me "shopping list" , but it returns me [1] - second, element in list). What i do not understand, why doing exactly the same thing in python shell gives different results.</p> <p>doing it the way i do in django ( TYPE_DICT[dict.type] ), works as described above and creates error in python shell. using TYPE_DICT[str(dict.type)] in python shell works just fine, but creates this error in django:</p> <pre><code>TypeError at /list/ tuple indices must be integers, not str Request Method: GET Request URL: http://127.0.0.1/list/ Exception Type: TypeError Exception Value: tuple indices must be integers, not str Exception Location: /home/projects/tst/list/views.py in list, line 22 Python Executable: /usr/bin/python Python Version: 2.6.2 </code></pre> <p>Perhaps i did something wrong or different in python shell. What i did was:</p> <pre><code>python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; dict = {'1':'shoppinglist', '2':'giftlist','3':'testlist'} &gt;&gt;&gt; print dict[1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(1)] shoppinglist &gt;&gt;&gt; x = 1 &gt;&gt;&gt; print dict[x] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(x)] shoppinglist &gt;&gt;&gt; </code></pre> <p>so what is wrong here?</p> <p>Alan</p>
1
2009-09-05T20:55:39Z
1,384,262
<p>You're creating a tuple, not a dict.</p> <pre><code>TYPE_DICT = { 1: "Shopping list", 2: "Gift Wishlist", 3: "test list type", } </code></pre> <p>is a dict (but that's not what choices wants).</p>
-1
2009-09-05T21:03:35Z
[ "python", "django", "list", "dictionary", "tuples" ]
(re)Using dictionaries in django views
1,384,246
<p>I have this dictionary in my apps model file:</p> <pre><code>TYPE_DICT = ( ("1", "Shopping list"), ("2", "Gift Wishlist"), ("3", "test list type"), ) </code></pre> <p>model, which uses this dict is this:</p> <pre><code>class List(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) type = models.PositiveIntegerField(choices=TYPE_DICT) </code></pre> <p>I want to re-use it in my views and imported it from apps.models. I am creating a list of dictioneries to use in my view like this:</p> <pre><code>bunchofdicts = List.objects.filter(user=request.user) array = [] for dict in bunchofdicts: ListDict = {'Name':dict.name, 'type':TYPE_DICT[dict.type], 'edit':'placeholder' } array.append(ListDict) </code></pre> <p>When i use this list in my template then it gives me very strange results. Instead of returning me the type of the list (shopping list) it returns me ('2', 'Gift Wishlist').</p> <p>So i can understand what it is doing (in ths case, the dict.type equals 1, and it should return me "shopping list" , but it returns me [1] - second, element in list). What i do not understand, why doing exactly the same thing in python shell gives different results.</p> <p>doing it the way i do in django ( TYPE_DICT[dict.type] ), works as described above and creates error in python shell. using TYPE_DICT[str(dict.type)] in python shell works just fine, but creates this error in django:</p> <pre><code>TypeError at /list/ tuple indices must be integers, not str Request Method: GET Request URL: http://127.0.0.1/list/ Exception Type: TypeError Exception Value: tuple indices must be integers, not str Exception Location: /home/projects/tst/list/views.py in list, line 22 Python Executable: /usr/bin/python Python Version: 2.6.2 </code></pre> <p>Perhaps i did something wrong or different in python shell. What i did was:</p> <pre><code>python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; dict = {'1':'shoppinglist', '2':'giftlist','3':'testlist'} &gt;&gt;&gt; print dict[1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(1)] shoppinglist &gt;&gt;&gt; x = 1 &gt;&gt;&gt; print dict[x] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(x)] shoppinglist &gt;&gt;&gt; </code></pre> <p>so what is wrong here?</p> <p>Alan</p>
1
2009-09-05T20:55:39Z
1,384,777
<p>firstly, modify your tuple to dictionary format.. then, when accessing in django template you need to assume the key of that dictionary as an attribute...let say this is the dictionary</p> <pre><code>TYPE_DICT = { 1: 'Shopping list', 2: 'Gift Wishlist', 3: 'test list type', } </code></pre> <p>when accessing this dictionary in django template, you should use like this</p> <pre><code>TYPE_DICT.1 </code></pre>
0
2009-09-06T03:04:33Z
[ "python", "django", "list", "dictionary", "tuples" ]
(re)Using dictionaries in django views
1,384,246
<p>I have this dictionary in my apps model file:</p> <pre><code>TYPE_DICT = ( ("1", "Shopping list"), ("2", "Gift Wishlist"), ("3", "test list type"), ) </code></pre> <p>model, which uses this dict is this:</p> <pre><code>class List(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) type = models.PositiveIntegerField(choices=TYPE_DICT) </code></pre> <p>I want to re-use it in my views and imported it from apps.models. I am creating a list of dictioneries to use in my view like this:</p> <pre><code>bunchofdicts = List.objects.filter(user=request.user) array = [] for dict in bunchofdicts: ListDict = {'Name':dict.name, 'type':TYPE_DICT[dict.type], 'edit':'placeholder' } array.append(ListDict) </code></pre> <p>When i use this list in my template then it gives me very strange results. Instead of returning me the type of the list (shopping list) it returns me ('2', 'Gift Wishlist').</p> <p>So i can understand what it is doing (in ths case, the dict.type equals 1, and it should return me "shopping list" , but it returns me [1] - second, element in list). What i do not understand, why doing exactly the same thing in python shell gives different results.</p> <p>doing it the way i do in django ( TYPE_DICT[dict.type] ), works as described above and creates error in python shell. using TYPE_DICT[str(dict.type)] in python shell works just fine, but creates this error in django:</p> <pre><code>TypeError at /list/ tuple indices must be integers, not str Request Method: GET Request URL: http://127.0.0.1/list/ Exception Type: TypeError Exception Value: tuple indices must be integers, not str Exception Location: /home/projects/tst/list/views.py in list, line 22 Python Executable: /usr/bin/python Python Version: 2.6.2 </code></pre> <p>Perhaps i did something wrong or different in python shell. What i did was:</p> <pre><code>python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; dict = {'1':'shoppinglist', '2':'giftlist','3':'testlist'} &gt;&gt;&gt; print dict[1] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(1)] shoppinglist &gt;&gt;&gt; x = 1 &gt;&gt;&gt; print dict[x] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; KeyError: 1 &gt;&gt;&gt; print dict[str(x)] shoppinglist &gt;&gt;&gt; </code></pre> <p>so what is wrong here?</p> <p>Alan</p>
1
2009-09-05T20:55:39Z
8,796,869
<p>Hello I was trying to do this since yesterday and today I realized your can <a href="https://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">make your own filter</a> so that you can pass the dictionary key (that is stored in the database).</p> <p>I was trying to get this to work with states, and since I use this in plenty of models I added it to the settings so it goes like this:</p> <p>in settings.py</p> <pre><code>... CSTM_LISTA_ESTADOS = ( ('AS','Aguascalientes'), ('BC','Baja California'), ... ('YN','Yucatan'), ('ZS','Zacatecas') ) ... </code></pre> <p>in my customtags.py</p> <pre><code>@register.filter(name='estado') def estado(estado): from settings import CSTM_LISTA_ESTADOS lista_estados = dict(CSTM_LISTA_ESTADOS) return lista_estados[estado] </code></pre> <p>in my template basicas.html</p> <pre><code>{{oportunidad.estado|estado}} </code></pre> <p>oportunidad is the variable I'm passing to the template</p> <p>Hope this helps other people</p>
0
2012-01-09T23:57:46Z
[ "python", "django", "list", "dictionary", "tuples" ]
python variable scope issue
1,384,301
<p>i am stuck at scope resolution in python. let me explain a code first:</p> <pre><code>class serv_db: def __init__(self, db): self.db = db self.dbc = self.db.cursor() def menudisp (self): print"Welcome to Tata Motors" print"Please select one of the options to continue:" print"1. Insert Car Info" print"2. Display Car Info" print"3. Update Car Info" print"4. Exit" menu_choice = raw_input("Enter what you want to do: ") if menu_choice==1: additem() elif menu_choice==2: getitem() elif menu_choice==3: edititem() elif menu_choice==4: sys.exit() def additem (self): reg = raw_input("\n\nTo continue, please enter the Registration # of car: ") print"There are 3 books in our database:" print"1. Job Card" print"2. Car" print"3. Customer" ch = raw_input("\nEnter your choice: ") if ch==1: adnewjob() elif ch==2: adnewcar(self, reg) elif ch==3: adnewcust() def adnewcar ( self, reg ): print "adding info to database: car" carreg = reg #error here mftr = raw_input("Enter the Manufacturer of your car: ") model = raw_input("Enter the Model of your car: ") car_tb = (carreg,mftr,model) #writing to DB self.dbc.execute("insert into car(reg, mftr, model) values(%s,%s,%s)", car_tb) def main(): db = MySQLdb.connect(user="root", passwd="", db="tatamotors") service = serv_db(db) service.menudisp() if __name__ == '__main__': main() </code></pre> <p>i am inputting a registration num into the variable <code>reg</code> now based upon the user's choice one of three functions is performed. i havent yet created the <code>adnewjob()</code> and <code>adnewcust()</code> functions yet. the <code>adnewcar()</code> is ready. when i try to pass the value down to the adnewcar() function, it gives an error saying:</p> <p>This is the entire traceback:</p> <pre><code>Traceback &lt;most recent call last&gt;: File "tatamotors.py", line 5, in &lt;module&gt; class serv_db: File "tatamotors.py", line 38, in serv_db carreg = reg Name Error: name 'reg' is not defined </code></pre> <p>i am pretty sure i am making some mistake. n00b here. go easy. thanks :)</p> <p><strong>EDIT</strong> i have joined all the relevant functions and classes. i have also included the related functions too.</p>
-1
2009-09-05T21:28:01Z
1,384,304
<p>It's a mistake to explicitly pass self when calling a method on your class. It's another mistake comparing ch to integers, when raw_input returns a string</p> <p>Try</p> <pre><code>elif ch=='2': self.adnewcar(reg) </code></pre> <p>instead</p> <p>You also have a print misindented in adnewcar.</p> <p>But even then, after fixing all this I cannot reproduce your NameError. You really need to edit your question with </p> <ul> <li>More code (the whole class at least.)</li> <li>Full traceback of the error.</li> </ul> <p>EDIT: I really don't know how you even get that traceback. The code you pasted is filled with the errors I illustrate, no use of self and no use of quotes around the integer. </p> <p>Per chance are you using Python 3.0? What's your environment?</p> <p>For the record, this works for me, using Python 2.5.2</p> <pre><code>class serv_db: def __init__(self, db): self.db = db self.dbc = self.db.cursor() def menudisp (self): print"Welcome to Tata Motors" print"Please select one of the options to continue:" print"1. Insert Car Info" print"2. Display Car Info" print"3. Update Car Info" print"4. Exit" menu_choice = raw_input("Enter what you want to do: ") if menu_choice=='1': self.additem() elif menu_choice=='2': self.getitem() elif menu_choice=='3': self.edititem() elif menu_choice=='4': sys.exit() def additem (self): reg = raw_input("\n\nTo continue, please enter the Registration # of car: ") print"There are 3 books in our database:" print"1. Job Card" print"2. Car" print"3. Customer" ch = raw_input("\nEnter your choice: ") if ch=='1': self.adnewjob() elif ch=='2': self.adnewcar(reg) elif ch=='3': self.adnewcust() def adnewcar ( self, reg ): print "adding info to database: car" carreg = reg #error here mftr = raw_input("Enter the Manufacturer of your car: ") model = raw_input("Enter the Model of your car: ") car_tb = (carreg,mftr,model) #writing to DB self.dbc.execute("insert into car(reg, mftr, model) values(%s,%s,%s)", car_tb) def main(): db = MySQLdb.connect(user="root", passwd="", db="tatamotors") service = serv_db(db) service.menudisp() if __name__ == '__main__': main() </code></pre>
2
2009-09-05T21:31:52Z
[ "python" ]
python variable scope issue
1,384,301
<p>i am stuck at scope resolution in python. let me explain a code first:</p> <pre><code>class serv_db: def __init__(self, db): self.db = db self.dbc = self.db.cursor() def menudisp (self): print"Welcome to Tata Motors" print"Please select one of the options to continue:" print"1. Insert Car Info" print"2. Display Car Info" print"3. Update Car Info" print"4. Exit" menu_choice = raw_input("Enter what you want to do: ") if menu_choice==1: additem() elif menu_choice==2: getitem() elif menu_choice==3: edititem() elif menu_choice==4: sys.exit() def additem (self): reg = raw_input("\n\nTo continue, please enter the Registration # of car: ") print"There are 3 books in our database:" print"1. Job Card" print"2. Car" print"3. Customer" ch = raw_input("\nEnter your choice: ") if ch==1: adnewjob() elif ch==2: adnewcar(self, reg) elif ch==3: adnewcust() def adnewcar ( self, reg ): print "adding info to database: car" carreg = reg #error here mftr = raw_input("Enter the Manufacturer of your car: ") model = raw_input("Enter the Model of your car: ") car_tb = (carreg,mftr,model) #writing to DB self.dbc.execute("insert into car(reg, mftr, model) values(%s,%s,%s)", car_tb) def main(): db = MySQLdb.connect(user="root", passwd="", db="tatamotors") service = serv_db(db) service.menudisp() if __name__ == '__main__': main() </code></pre> <p>i am inputting a registration num into the variable <code>reg</code> now based upon the user's choice one of three functions is performed. i havent yet created the <code>adnewjob()</code> and <code>adnewcust()</code> functions yet. the <code>adnewcar()</code> is ready. when i try to pass the value down to the adnewcar() function, it gives an error saying:</p> <p>This is the entire traceback:</p> <pre><code>Traceback &lt;most recent call last&gt;: File "tatamotors.py", line 5, in &lt;module&gt; class serv_db: File "tatamotors.py", line 38, in serv_db carreg = reg Name Error: name 'reg' is not defined </code></pre> <p>i am pretty sure i am making some mistake. n00b here. go easy. thanks :)</p> <p><strong>EDIT</strong> i have joined all the relevant functions and classes. i have also included the related functions too.</p>
-1
2009-09-05T21:28:01Z
1,384,378
<p>You need all these three:</p> <pre><code>if menu_choice==1: self.additem() # 1: self. elif ch=='2': self.adnewcar(reg) # 2: self. instead of (self, reg) print "adding info to database: car" # 3: indented. </code></pre> <p>Always remember to keep indents consistent throughout a .py, otherwise the interpreter will have a hard time keeping track of your scopes.</p>
0
2009-09-05T22:11:13Z
[ "python" ]
python variable scope issue
1,384,301
<p>i am stuck at scope resolution in python. let me explain a code first:</p> <pre><code>class serv_db: def __init__(self, db): self.db = db self.dbc = self.db.cursor() def menudisp (self): print"Welcome to Tata Motors" print"Please select one of the options to continue:" print"1. Insert Car Info" print"2. Display Car Info" print"3. Update Car Info" print"4. Exit" menu_choice = raw_input("Enter what you want to do: ") if menu_choice==1: additem() elif menu_choice==2: getitem() elif menu_choice==3: edititem() elif menu_choice==4: sys.exit() def additem (self): reg = raw_input("\n\nTo continue, please enter the Registration # of car: ") print"There are 3 books in our database:" print"1. Job Card" print"2. Car" print"3. Customer" ch = raw_input("\nEnter your choice: ") if ch==1: adnewjob() elif ch==2: adnewcar(self, reg) elif ch==3: adnewcust() def adnewcar ( self, reg ): print "adding info to database: car" carreg = reg #error here mftr = raw_input("Enter the Manufacturer of your car: ") model = raw_input("Enter the Model of your car: ") car_tb = (carreg,mftr,model) #writing to DB self.dbc.execute("insert into car(reg, mftr, model) values(%s,%s,%s)", car_tb) def main(): db = MySQLdb.connect(user="root", passwd="", db="tatamotors") service = serv_db(db) service.menudisp() if __name__ == '__main__': main() </code></pre> <p>i am inputting a registration num into the variable <code>reg</code> now based upon the user's choice one of three functions is performed. i havent yet created the <code>adnewjob()</code> and <code>adnewcust()</code> functions yet. the <code>adnewcar()</code> is ready. when i try to pass the value down to the adnewcar() function, it gives an error saying:</p> <p>This is the entire traceback:</p> <pre><code>Traceback &lt;most recent call last&gt;: File "tatamotors.py", line 5, in &lt;module&gt; class serv_db: File "tatamotors.py", line 38, in serv_db carreg = reg Name Error: name 'reg' is not defined </code></pre> <p>i am pretty sure i am making some mistake. n00b here. go easy. thanks :)</p> <p><strong>EDIT</strong> i have joined all the relevant functions and classes. i have also included the related functions too.</p>
-1
2009-09-05T21:28:01Z
1,384,379
<p>is it a copy error or do you have your indentation wrong? The (I suppose) methods align with the class definition instead of being indented one level. </p> <p>Perhaps you are mixing tabs and spaces?</p> <p>btw if you define your class correctly you should be calling <em>self.additem()</em> instead of <em>additem()</em> (and the same goes for <em>adnewcar(self,reg</em>, at the moment it works because it is in fact <em>not</em> a method, but a module level function.</p>
0
2009-09-05T22:11:21Z
[ "python" ]
Serving file download with python
1,384,320
<p>Hey gang, I'm trying to convert a legacy php script over to python and not having much luck. </p> <p>The intent of the script is to serve up a file while concealing it's origin. Here's what's working in php:</p> <pre><code>&lt;?php $filepath = "foo.mp3"; $filesize = filesize($filepath); header("Pragma: no-cache"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // force download dialog //header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition: attachment;filename="'.$filepath.'"'); header("Content-Transfer-Encoding: binary"); #header('Content-Type: audio/mpeg3'); header('Content-Length: '.$filesize); @readfile($filepath); exit(0); ?&gt; </code></pre> <p>When I do the equivilent in Python, I get a download that is zero bytes. Here's what I'm trying:</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 import sys import os import cgitb; cgitb.enable() filepath = "foo.mp3" filesize = os.path.getsize(filepath) print "Prama: no-cache" print "Expires: 0" print "Cache-Control: must-revalidate, post-check=0, pre-check=0" print "Content-Type: application/octet-stream" print "Content-Type: application/download" print 'Content-Disposition: attachment;filename="'+filepath+'"' print "Content-Transfer-Encoding: binary" print 'Content-Length: '+str(filesize) print #required blank line open(filepath,"rb").read() </code></pre> <p>Can anyone please help me?</p>
1
2009-09-05T21:38:18Z
1,384,328
<p>Well, maybe it's just me missing something, but... You are actually not writing the contents of the file to stdout. You are just reading it into memory, so it will never show up on the other side of the TCP connection...</p> <p>Try:</p> <pre><code>sys.stdout.write(open(filepath,"rb").read()) sys.stdout.flush() </code></pre> <p>Depending on the file size, it might be better to read the file in chunks, like so:</p> <pre><code>chunk_size = 4096 handle = open(filepath, "rb") while True: buffer = handle.read(chunk_size) if buffer: sys.stdout.write(buffer) else: break </code></pre> <p>Another thing to be aware of: writing binary data to stdout may cause Python to choke due to encoding issues. This depends on the Python version you are using.</p>
5
2009-09-05T21:43:43Z
[ "php", "python", "binary" ]
Serving file download with python
1,384,320
<p>Hey gang, I'm trying to convert a legacy php script over to python and not having much luck. </p> <p>The intent of the script is to serve up a file while concealing it's origin. Here's what's working in php:</p> <pre><code>&lt;?php $filepath = "foo.mp3"; $filesize = filesize($filepath); header("Pragma: no-cache"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // force download dialog //header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition: attachment;filename="'.$filepath.'"'); header("Content-Transfer-Encoding: binary"); #header('Content-Type: audio/mpeg3'); header('Content-Length: '.$filesize); @readfile($filepath); exit(0); ?&gt; </code></pre> <p>When I do the equivilent in Python, I get a download that is zero bytes. Here's what I'm trying:</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 import sys import os import cgitb; cgitb.enable() filepath = "foo.mp3" filesize = os.path.getsize(filepath) print "Prama: no-cache" print "Expires: 0" print "Cache-Control: must-revalidate, post-check=0, pre-check=0" print "Content-Type: application/octet-stream" print "Content-Type: application/download" print 'Content-Disposition: attachment;filename="'+filepath+'"' print "Content-Transfer-Encoding: binary" print 'Content-Length: '+str(filesize) print #required blank line open(filepath,"rb").read() </code></pre> <p>Can anyone please help me?</p>
1
2009-09-05T21:38:18Z
1,384,329
<p>You should check out <a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> to set and work with headers. <a href="http://vsbabu.org/mt/archives/2003/05/27/urllib2%5Fsetting%5Fhttp%5Fheaders.html" rel="nofollow">Here's a small example</a> that does this.</p>
-1
2009-09-05T21:43:51Z
[ "php", "python", "binary" ]
Serving file download with python
1,384,320
<p>Hey gang, I'm trying to convert a legacy php script over to python and not having much luck. </p> <p>The intent of the script is to serve up a file while concealing it's origin. Here's what's working in php:</p> <pre><code>&lt;?php $filepath = "foo.mp3"; $filesize = filesize($filepath); header("Pragma: no-cache"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // force download dialog //header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header('Content-Disposition: attachment;filename="'.$filepath.'"'); header("Content-Transfer-Encoding: binary"); #header('Content-Type: audio/mpeg3'); header('Content-Length: '.$filesize); @readfile($filepath); exit(0); ?&gt; </code></pre> <p>When I do the equivilent in Python, I get a download that is zero bytes. Here's what I'm trying:</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 import sys import os import cgitb; cgitb.enable() filepath = "foo.mp3" filesize = os.path.getsize(filepath) print "Prama: no-cache" print "Expires: 0" print "Cache-Control: must-revalidate, post-check=0, pre-check=0" print "Content-Type: application/octet-stream" print "Content-Type: application/download" print 'Content-Disposition: attachment;filename="'+filepath+'"' print "Content-Transfer-Encoding: binary" print 'Content-Length: '+str(filesize) print #required blank line open(filepath,"rb").read() </code></pre> <p>Can anyone please help me?</p>
1
2009-09-05T21:38:18Z
1,384,330
<p>I don't know if this is the only issue but the python print statement terminates lines with "\n" whereas HTTP headers need to be terminated with "\r\n"</p>
1
2009-09-05T21:44:29Z
[ "php", "python", "binary" ]
lxml equivalent to BeautifulSoup "OR" syntax?
1,384,470
<p>I'm converting some html parsing code from BeautifulSoup to lxml. I'm trying to figure out the lxml equivalent syntax for the following BeautifullSoup statement:</p> <pre><code>soup.find('a', {'class': ['current zzt', 'zzt']}) </code></pre> <p>Basically I want to find all of the "a" tags in the document that have a class attribute of either "current zzt" or "zzt". BeautifulSoup allows one to pass in a list, dictionary, or even a regular express to perform the match.</p> <p>What is the lxml equivalent?</p> <p>Thanks!</p>
5
2009-09-05T23:04:18Z
1,429,316
<p>No, lxml does not provide the "find first or return None" method you're looking for. Just use <code>(select(soup) or [None])[0]</code> if you need that, or write a function to do it for you.</p> <pre><code>#!/usr/bin/python import lxml.html import lxml.cssselect soup = lxml.html.fromstring(""" &lt;html&gt; &lt;a href="foo" class="yyy zzz" /&gt; &lt;a href="bar" class="yyy" /&gt; &lt;a href="baz" class="zzz" /&gt; &lt;a href="quux" class="zzz yyy" /&gt; &lt;a href="warble" class="qqq" /&gt; &lt;p class="yyy zzz"&gt;Hello&lt;/p&gt; &lt;/html&gt;""") select = lxml.cssselect.CSSSelector("a.yyy.zzz, a.yyy") print [lxml.html.tostring(s).strip() for s in select(soup)] print (select(soup) or [None])[0] </code></pre> <p>Ok, so <code>soup.find('a')</code> would indeed find first a element or None as you expect. Trouble is, it doesn't appear to support the rich XPath syntax needed for CSSSelector.</p>
3
2009-09-15T19:57:42Z
[ "python", "beautifulsoup", "lxml" ]
python smtp gmail authentication error (sending email through gmail smtp server)
1,384,535
<p>I have the following code </p> <pre><code>import smtplib from email.mime.text import MIMEText smtpserver = 'smtp.gmail.com' AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1 smtpuser = 'admin@myhost.com' # for SMTP AUTH, set SMTP username here smtppass = '123456' # for SMTP AUTH, set SMTP password here RECIPIENTS = ['online8@gmail.com'] SENDER = 'admin@myhost.com' msg = MIMEText('dsdsdsdsds\n') msg['Subject'] = 'The contents of iii' msg['From'] = 'admin@myhost.com' msg['To'] = ''online8@gmail.com'' mailServer = smtplib.SMTP('smtp.gmail.com',587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(smtpuser, smtppass) mailServer.sendmail(smtpuser,RECIPIENTS,msg.as_string()) mailServer.close() </code></pre> <p>this code works fine on my desktop. but it failed with this error</p> <pre><code>smtplib.SMTPAuthenticationError: (535, '5.7.1 Username and Password not accepted. Learn more at\n5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 21sm4713429agd.11') </code></pre> <p>on my linux server.</p> <p>Not sure what went wrong, should i open some port on my linux server?</p>
2
2009-09-05T23:52:31Z
1,384,583
<p>Port 587 obviously needs to be open, but it probably is (or you wouldn't have gotten the detailed error msg in question). Python 2.5 vs 2.6 should make no difference. I think the issue has to do with "solving a captcha" once on the computer for which logins are currently getting rejected; follow the detailed instructions at the URL in the error message, i.e., <a href="http://mail.google.com/support/bin/answer.py?answer=14257">http://mail.google.com/support/bin/answer.py?answer=14257</a> </p>
6
2009-09-06T00:27:50Z
[ "python", "smtp", "gmail", "smtplib" ]
python smtp gmail authentication error (sending email through gmail smtp server)
1,384,535
<p>I have the following code </p> <pre><code>import smtplib from email.mime.text import MIMEText smtpserver = 'smtp.gmail.com' AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1 smtpuser = 'admin@myhost.com' # for SMTP AUTH, set SMTP username here smtppass = '123456' # for SMTP AUTH, set SMTP password here RECIPIENTS = ['online8@gmail.com'] SENDER = 'admin@myhost.com' msg = MIMEText('dsdsdsdsds\n') msg['Subject'] = 'The contents of iii' msg['From'] = 'admin@myhost.com' msg['To'] = ''online8@gmail.com'' mailServer = smtplib.SMTP('smtp.gmail.com',587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(smtpuser, smtppass) mailServer.sendmail(smtpuser,RECIPIENTS,msg.as_string()) mailServer.close() </code></pre> <p>this code works fine on my desktop. but it failed with this error</p> <pre><code>smtplib.SMTPAuthenticationError: (535, '5.7.1 Username and Password not accepted. Learn more at\n5.7.1 http://mail.google.com/support/bin/answer.py?answer=14257 21sm4713429agd.11') </code></pre> <p>on my linux server.</p> <p>Not sure what went wrong, should i open some port on my linux server?</p>
2
2009-09-05T23:52:31Z
5,673,945
<pre><code>import random,time for i in range(1,100): y=random.randint(30,300) time.sleep(y) print ("Mailing for fun, Mail No: " + str(i)) msg = MIMEText('Testing mailing \n Mail No:' + str(i)) msg['Subject'] = 'Mail Number: ' + str(i) </code></pre> <p>Randomizing the mail interval to check smtp behavior :) </p> <p>With a bit addition n modification, I got this to work to check our intermittent mail bouncing.</p>
2
2011-04-15T08:02:04Z
[ "python", "smtp", "gmail", "smtplib" ]
Python : Revert to base __str__ behavior
1,384,542
<p>How can I revert back to the default function that python uses if there is no <code>__str__</code> method?</p> <pre><code>class A : def __str__(self) : return "Something useless" class B(A) : def __str__(self) : return some_magic_base_function(self) </code></pre>
6
2009-09-06T00:00:39Z
1,384,559
<p>You can use <code>object.__str__()</code>:</p> <pre><code>class A: def __str__(self): return "Something useless" class B(A): def __str__(self): return object.__str__(self) </code></pre> <p>This gives you the default output for instances of <code>B</code>:</p> <pre><code>&gt;&gt;&gt; b = B() &gt;&gt;&gt; str(b) '&lt;__main__.B instance at 0x7fb34c4f09e0&gt;' </code></pre>
12
2009-09-06T00:06:42Z
[ "python", "string" ]
Python : Revert to base __str__ behavior
1,384,542
<p>How can I revert back to the default function that python uses if there is no <code>__str__</code> method?</p> <pre><code>class A : def __str__(self) : return "Something useless" class B(A) : def __str__(self) : return some_magic_base_function(self) </code></pre>
6
2009-09-06T00:00:39Z
1,384,569
<p>"the default function that python uses if there is no <code>__str__</code> method" is <code>repr</code>, so:</p> <pre><code>class B(A) : def __str__(self) : return repr(self) </code></pre> <p>This holds whether <code>__repr__</code> has been overridden in the inheritance chain or not. IOW, if you ALSO need to bypass possible overrides of <code>__repr__</code> (as opposed to using them if they exist, as this approach would do), you will need explicit calls to <code>object.__repr__(self)</code> (or to <code>object.__str__</code> as another answer suggested -- same thing).</p>
2
2009-09-06T00:16:30Z
[ "python", "string" ]
How to "slow down" a MIDI file (ideally in Python)?
1,384,588
<p>I have background music for some songs available in both .MID and .KAR formats, but in each case it's being played somewhat faster than I'd like. What's the simplest way to create either .MID or .KAR files with the same content but at a slower tempo -- say, one slowed down by 20% or so, another by 15%, a third by 25%, and so on?</p> <p>Ideally, I'd prefer a cross-platform Python script (since that would allow me to easily experimentally tweak the source to converge to the exact effect I want;-), but I'll take any free solution that runs in Linux (Ubuntu 8.04 if it matters) and Mac (Mac OS X 10.5, but 10.6 compatibility preferred).</p>
14
2009-09-06T00:35:53Z
1,384,611
<p>You could edit the file, as per <a href="http://www.sonicspot.com/guide/midifiles.html" rel="nofollow">http://www.sonicspot.com/guide/midifiles.html</a></p> <p>Although there probably is a MIDI reading/writing library already. In fact, it was a matter of seeing the related questions: <a href="http://stackoverflow.com/questions/569321/simple-cross-platform-midi-library-for-python">http://stackoverflow.com/questions/569321/simple-cross-platform-midi-library-for-python</a></p> <blockquote> <p>Set Tempo </p> <p>This meta event sets the sequence tempo in terms of microseconds per quarter-note which is encoded in three bytes. It usually is found in the first track chunk, time-aligned to occur at the same time as a MIDI clock message to promote more accurate synchronization. If no set tempo event is present, 120 beats per minute is assumed. The following formula's can be used to translate the tempo from microseconds per quarter-note to beats per minute and back.</p> </blockquote> <pre> MICROSECONDS_PER_MINUTE = 60000000 BPM = MICROSECONDS_PER_MINUTE / MPQN MPQN = MICROSECONDS_PER_MINUTE / BPM </pre> <pre> Meta Event Type Length Microseconds/Quarter-Note 255 (0xFF) 81 (0x51) 3 0-8355711 </pre>
9
2009-09-06T00:47:20Z
[ "python", "midi" ]
How to "slow down" a MIDI file (ideally in Python)?
1,384,588
<p>I have background music for some songs available in both .MID and .KAR formats, but in each case it's being played somewhat faster than I'd like. What's the simplest way to create either .MID or .KAR files with the same content but at a slower tempo -- say, one slowed down by 20% or so, another by 15%, a third by 25%, and so on?</p> <p>Ideally, I'd prefer a cross-platform Python script (since that would allow me to easily experimentally tweak the source to converge to the exact effect I want;-), but I'll take any free solution that runs in Linux (Ubuntu 8.04 if it matters) and Mac (Mac OS X 10.5, but 10.6 compatibility preferred).</p>
14
2009-09-06T00:35:53Z
1,449,597
<p>As Vinko says, you can edit the midifile, but since it's a binary format, squeezed into the least number of bits possible, it helps to have help.</p> <p>This is a midi-to-text converter (and vice-versa):<br /> <a href="http://midicomp.opensrc.org/">http://midicomp.opensrc.org/</a><br /> I've been using it quite a bit lately. it's pretty trivial to do text processing (e.g. searching for line with "Tempo") for simple operations once you have the midifile as text. haven't tried on mac (compiled with no problem on ubuntu 8.04).</p> <p>Regarding midifile tempo specifically, it's really easy to slow down or speed up playback since the timing of events is specified in terms of "ticks", whose real duration in seconds is determined by the tempo parameter described in Vinko's quote. I believe time signature is not so relevant, and is mainly for displaying bars/beats correctly when opened in a midi sequencer.</p> <p>Also, aside from pyPortMidi, there are a couple of other python midi modules around.</p> <p>[hmmm... it seems i can only post on link per post, being a new user. i'll try posting the links to the python modules in a couple comments or another couple answers...]</p>
13
2009-09-19T21:34:34Z
[ "python", "midi" ]
How to "slow down" a MIDI file (ideally in Python)?
1,384,588
<p>I have background music for some songs available in both .MID and .KAR formats, but in each case it's being played somewhat faster than I'd like. What's the simplest way to create either .MID or .KAR files with the same content but at a slower tempo -- say, one slowed down by 20% or so, another by 15%, a third by 25%, and so on?</p> <p>Ideally, I'd prefer a cross-platform Python script (since that would allow me to easily experimentally tweak the source to converge to the exact effect I want;-), but I'll take any free solution that runs in Linux (Ubuntu 8.04 if it matters) and Mac (Mac OS X 10.5, but 10.6 compatibility preferred).</p>
14
2009-09-06T00:35:53Z
20,596,154
<p>I have a similar interest as your post. I just came across this library which looks very promising:</p> <p><a href="http://web.mit.edu/music21/" rel="nofollow">http://web.mit.edu/music21/</a></p>
1
2013-12-15T15:27:14Z
[ "python", "midi" ]
Should I use Mako for Templating?
1,384,634
<p>I've been considering a templating solution, although my choices are between Mako and Genshi. I find templating in Genshi a bit ugly, so I'm shifting more towards Mako.</p> <p>I've gone to wonder: what is so good about the fact that Mako allows embedded Python code? How is it convenient for the average joe?</p> <p>Wouldn't templating JUST suffice without having embedded Python code?</p>
7
2009-09-06T01:11:38Z
1,384,671
<p>This seems to be a bit of a religious issue. Django templates take a hard line: no code in templates. They do this because of their history as a system used in shops where there's a clear separation between those who write code and those who create pages. Others (perhaps you) don't make such a clear distinction, and would feel more comfortable having a more flexible line between layout and logic.</p> <p>It really comes down to a matter of taste.</p>
2
2009-09-06T01:36:52Z
[ "python", "template-engine", "mako", "genshi" ]
Should I use Mako for Templating?
1,384,634
<p>I've been considering a templating solution, although my choices are between Mako and Genshi. I find templating in Genshi a bit ugly, so I'm shifting more towards Mako.</p> <p>I've gone to wonder: what is so good about the fact that Mako allows embedded Python code? How is it convenient for the average joe?</p> <p>Wouldn't templating JUST suffice without having embedded Python code?</p>
7
2009-09-06T01:11:38Z
1,384,699
<p>As the mako <a href="http://www.makotemplates.org/">homepage</a> points out, Mako's advantages are pretty clear: insanely fast, instantly familiar to anyone who's handy with Python in terms of both syntax and features.</p> <p>Genshi chooses "interpretation" instead of ahead-of-time Python code generation (according to their <a href="http://genshi.edgewall.org/wiki/GenshiFaq">FAQ</a>, that's for clarity of error messages) and an "arm's length" approach to Python (e.g. by using xpath for selectors, xinclude instead of inheritance, etc) so it might be more natural to people who know no Python but are very competent with XML.</p> <p>So what's your "audience"? If Python programmers, I suggest Mako (for speed and familiarity); if XML experts that are uncomfortable with Python, Genshi might be a better fit (for "arm's length from Python" approach and closer match to XML culture).</p> <p>You mention "the average Joe", but Joe doesn't know Python AND xpath is a deep dark mystery to him; if THAT was really your audience, other templating systems such as Django's might actually be a better fit (help him to avoid getting in trouble;-).</p>
18
2009-09-06T01:54:26Z
[ "python", "template-engine", "mako", "genshi" ]
Should I use Mako for Templating?
1,384,634
<p>I've been considering a templating solution, although my choices are between Mako and Genshi. I find templating in Genshi a bit ugly, so I'm shifting more towards Mako.</p> <p>I've gone to wonder: what is so good about the fact that Mako allows embedded Python code? How is it convenient for the average joe?</p> <p>Wouldn't templating JUST suffice without having embedded Python code?</p>
7
2009-09-06T01:11:38Z
1,384,847
<p>You could discipline yourself to not inject any Python code within the template unless it's really the last resort to get the job done. I have faced a similar issue with Django's template where I have to do some serious CSS gymnastics to display my content. If I could have used some Python code in the template, it would have been better.</p>
0
2009-09-06T04:15:18Z
[ "python", "template-engine", "mako", "genshi" ]
Should I use Mako for Templating?
1,384,634
<p>I've been considering a templating solution, although my choices are between Mako and Genshi. I find templating in Genshi a bit ugly, so I'm shifting more towards Mako.</p> <p>I've gone to wonder: what is so good about the fact that Mako allows embedded Python code? How is it convenient for the average joe?</p> <p>Wouldn't templating JUST suffice without having embedded Python code?</p>
7
2009-09-06T01:11:38Z
1,386,193
<p>Genshi is conceived (read: biased, optimized) for generation of xml docs (even if it does offer support for generating any kind of text document). Mako and Django templates are conceived as <em>generic text</em> templating system. <a href="http://evoque.gizmojo.org/" rel="nofollow">Evoque</a> also, but with one fundamental difference that it makes the design choice to only allow python <em>expressions</em> in templates i.e. no python <em>statements</em>. </p> <p>One important net result of this is that Evoque is able to execute template evaluation in a sandbox -- i.e. you could safely give untrusted users write-access to a template's source code -- a feature that is virtually impossible for template engines that also allow embedding of <em>python statements</em>. Oh, and while not losing out any in a direct feature comparison, Evoque is in some cases actually faster than Mako, and it also runs on Python 3. </p>
2
2009-09-06T17:30:33Z
[ "python", "template-engine", "mako", "genshi" ]
Should I use Mako for Templating?
1,384,634
<p>I've been considering a templating solution, although my choices are between Mako and Genshi. I find templating in Genshi a bit ugly, so I'm shifting more towards Mako.</p> <p>I've gone to wonder: what is so good about the fact that Mako allows embedded Python code? How is it convenient for the average joe?</p> <p>Wouldn't templating JUST suffice without having embedded Python code?</p>
7
2009-09-06T01:11:38Z
1,391,510
<blockquote> <p>Wouldn't templating JUST suffice without having embedded Python code?</p> </blockquote> <p>Only if your templating language has enough logical functionality that it is essentially a scripting language in itself. At which point, you might just as well have used Python.</p> <p>More involved sites often need complex presentation logic and non-trivial templated structures like sections repeated in different places/pages and recursive trees. This is no fun if your templating language ties your hands behind your back because it takes the religious position that "code in template are BAD".</p> <p>Then you just end up writing presentation helper functions in your Python business logic, which is a worse blending of presentation and application logic than you had to start with. Languages that take power away from you because they don't trust you to use it tastefully are lame.</p>
15
2009-09-08T01:16:12Z
[ "python", "template-engine", "mako", "genshi" ]
Is concurrent computing important for web development?
1,384,715
<p>Let's say I have a web application running on S servers with an average of C cores each. My application is processing an average of R requests at any instant. Assuming R is around 10 times larger than S * C, won't benefits from spreading the work of a request across multiple cores be minimal since each core is processing around 10 requests already?</p> <p>If I'm correct why does <a href="http://jacobian.org/writing/snakes-on-the-web/" rel="nofollow">this guy</a> say concurrency is so important to the future of Python as a language for web development?</p> <p>I can see many reasons why my argument would be incorrect. Perhaps the application receives a few very-difficult-to-process requests that are outnumbered by available cores. Or perhaps there is a large variation in the difficulty of requests, so it's possible for one core to be unlucky and be given 10 consecutive difficult requests, with the result being that some of them take much longer than is reasonable. Given that the guy who wrote the above essay is so much more experienced than I am, I think there's a significant chance I'm wrong about this, but I'd like to know why.</p>
4
2009-09-06T02:10:03Z
1,384,724
<p>Not anytime soon in my estimation. The lifespan of most single web requests are well under a second. In light of this it makes little sense to split up the web request task itself and rather distribute the web request tasks across the cores. Something web servers are capable of and most already do. </p>
4
2009-09-06T02:15:49Z
[ "python", "web-applications", "concurrency" ]
Is concurrent computing important for web development?
1,384,715
<p>Let's say I have a web application running on S servers with an average of C cores each. My application is processing an average of R requests at any instant. Assuming R is around 10 times larger than S * C, won't benefits from spreading the work of a request across multiple cores be minimal since each core is processing around 10 requests already?</p> <p>If I'm correct why does <a href="http://jacobian.org/writing/snakes-on-the-web/" rel="nofollow">this guy</a> say concurrency is so important to the future of Python as a language for web development?</p> <p>I can see many reasons why my argument would be incorrect. Perhaps the application receives a few very-difficult-to-process requests that are outnumbered by available cores. Or perhaps there is a large variation in the difficulty of requests, so it's possible for one core to be unlucky and be given 10 consecutive difficult requests, with the result being that some of them take much longer than is reasonable. Given that the guy who wrote the above essay is so much more experienced than I am, I think there's a significant chance I'm wrong about this, but I'd like to know why.</p>
4
2009-09-06T02:10:03Z
1,384,736
<p>In the hypothetical circumstances you design, with about 10 requests "in play" per core, as long as the request-to-core assignment is handled sensibly (probably even the simplest round-robin load balancing will do), it's just fine if each request lives throughout its lifetime on a single core.</p> <p>Point is, that scenario's just ONE possibility -- <em>heavy</em> requests that could really benefit (in terms of lower latency) from marshaling multiple cores per request are surely an alternative possibility. I suspect that on today's web your scenario is more prevalent, but it sure would be nice to handle both kinds, AND "batch-like" background processing ones too.... especially since the number of cores (as opposed to each core's speed) is what's increasing, and what's going to keep increasing, these days.</p> <p>Far be it from me to argue against Jacob Kaplan-Moss's wisdom, but I'm used to getting pretty good concurrency, at my employer, in nicer and more explicit AND trasparent ways than he seems to advocate -- mapreduce for batch-like jobs, distributed-hashing based sharding for enrolling N backends to shard the work for 1 query, and the like.</p> <p>Maybe I just don't have enough real-life experience with (say) Erlang, Scala, or Haskell's relatively-new software transactional memory, to see how wonderfully they scale to high utilization of tens or hundrends of thousands of cores on low-QPS, high-work-per-Q workloads... but it seems to me that the silver bullet for this scenario (net of the relatively limited subset of cases where you can turn to mapreduce, <a href="http://googleresearch.blogspot.com/2009/06/large-scale-graph-computing-at-google.html" rel="nofollow">pregel</a>, sharding, etc) has not yet been invented in ANY language. With explicit, carefully crafted architecture Python is surely no worse than Java, C# or C++ at handling such scenarios, in my working experience at least.</p>
5
2009-09-06T02:24:47Z
[ "python", "web-applications", "concurrency" ]
Is concurrent computing important for web development?
1,384,715
<p>Let's say I have a web application running on S servers with an average of C cores each. My application is processing an average of R requests at any instant. Assuming R is around 10 times larger than S * C, won't benefits from spreading the work of a request across multiple cores be minimal since each core is processing around 10 requests already?</p> <p>If I'm correct why does <a href="http://jacobian.org/writing/snakes-on-the-web/" rel="nofollow">this guy</a> say concurrency is so important to the future of Python as a language for web development?</p> <p>I can see many reasons why my argument would be incorrect. Perhaps the application receives a few very-difficult-to-process requests that are outnumbered by available cores. Or perhaps there is a large variation in the difficulty of requests, so it's possible for one core to be unlucky and be given 10 consecutive difficult requests, with the result being that some of them take much longer than is reasonable. Given that the guy who wrote the above essay is so much more experienced than I am, I think there's a significant chance I'm wrong about this, but I'd like to know why.</p>
4
2009-09-06T02:10:03Z
1,384,753
<p>Caveat: I've only skimmed the "Concurrency" section, which seems to be what you're referring to.The issue seems to be (and this isn't new, of course):</p> <ul> <li>Python threads don't run in parallel due to the GIL.</li> <li>A system with many cores will need as many backends (in practice, you probably want at least 2xN threads).</li> <li>Systems are moving towards having more cores; typical PCs have four cores, and affordable server systems with 128 or more cores probably aren't far off.</li> <li>Running 256 separate Python processes means no data is shared; the entire application and any loaded data is replicated in each process, leading to massive memory waste.</li> </ul> <p>The last bit is where this logic fails. Indeed, if you start 256 Python backends in the naive way, there's no data shared. However, that has no design forethought: that's the <em>wrong</em> way to start lots of backend processes.</p> <p>The correct way is to load your entire application (all of the Python modules you depend on, etc.) in a single master process. Then that master process forks off backend processes to handle requests. These become separate processes, but standard copy-on-write memory management means that all fixed data already loaded is shared with the master. All of the code that was loaded in advance by the master is now shared among all of the workers, despite the fact that they're all separate processes.</p> <p>(Of course, COW means that if you write to it, it makes a new copy of the data--but things like compiled Python bytecode should not be changed after loading.)</p> <p>I don't know if there are Python-related problems which prevent this, but if so, those are implementation details to be fixed. This approach is far easier to implement than trying to eliminate the GIL. It also eliminates any chance of traditional locking and threading problems. Those aren't as bad as they are in some languages and other use cases--there's almost no interaction or locking between the threads--but they don't disappear completely and race conditions in Python are just as much of a pain to track down as they are in any other language.</p>
1
2009-09-06T02:48:51Z
[ "python", "web-applications", "concurrency" ]
Is concurrent computing important for web development?
1,384,715
<p>Let's say I have a web application running on S servers with an average of C cores each. My application is processing an average of R requests at any instant. Assuming R is around 10 times larger than S * C, won't benefits from spreading the work of a request across multiple cores be minimal since each core is processing around 10 requests already?</p> <p>If I'm correct why does <a href="http://jacobian.org/writing/snakes-on-the-web/" rel="nofollow">this guy</a> say concurrency is so important to the future of Python as a language for web development?</p> <p>I can see many reasons why my argument would be incorrect. Perhaps the application receives a few very-difficult-to-process requests that are outnumbered by available cores. Or perhaps there is a large variation in the difficulty of requests, so it's possible for one core to be unlucky and be given 10 consecutive difficult requests, with the result being that some of them take much longer than is reasonable. Given that the guy who wrote the above essay is so much more experienced than I am, I think there's a significant chance I'm wrong about this, but I'd like to know why.</p>
4
2009-09-06T02:10:03Z
1,384,774
<p>In the article, he seems to single out the GIL as the cause of holding back concurrent processing in web applications in Python, which I simply don't understand. As you get larger, eventually you're going to have another server, and, GIL or not GIL, it won't matter - you have multiple machines.</p> <p>If he's talking about being able to squeeze more out of a single computer, then I don't think thats as relevant, especially to large-scale <em>distributed</em> computing - different machines don't share a GIL. And, really, if you going to have lots of computers in a cluster, it's better to have a more mid-range servers instead of a single super server for a lot of reasons.</p> <p>If he means as a way for better supporting functional and asynchronous approaches, then I somewhat agree, but it seems tangential to his "we need better concurrency" point. Python can has it now (which he acknowledges), but, apparently, its not good <em>enough</em> (all because of the GIL, naturally). To be honest, it seems more like bashing on the GIL than a justification of the importance of concurrency in web development.</p> <p>One important point, with regards to concurrency and web development, is that concurrency is <em>hard</em>. The beauty of something like PHP is that there <em>is</em> no concurrency. You have a process, and you are stuck in that process. Its so simple and easy. You don't have to worry about any sort of concurrency problems - suddenly programming is <em>much</em> easier.</p>
0
2009-09-06T03:01:17Z
[ "python", "web-applications", "concurrency" ]
Is concurrent computing important for web development?
1,384,715
<p>Let's say I have a web application running on S servers with an average of C cores each. My application is processing an average of R requests at any instant. Assuming R is around 10 times larger than S * C, won't benefits from spreading the work of a request across multiple cores be minimal since each core is processing around 10 requests already?</p> <p>If I'm correct why does <a href="http://jacobian.org/writing/snakes-on-the-web/" rel="nofollow">this guy</a> say concurrency is so important to the future of Python as a language for web development?</p> <p>I can see many reasons why my argument would be incorrect. Perhaps the application receives a few very-difficult-to-process requests that are outnumbered by available cores. Or perhaps there is a large variation in the difficulty of requests, so it's possible for one core to be unlucky and be given 10 consecutive difficult requests, with the result being that some of them take much longer than is reasonable. Given that the guy who wrote the above essay is so much more experienced than I am, I think there's a significant chance I'm wrong about this, but I'd like to know why.</p>
4
2009-09-06T02:10:03Z
1,384,855
<p>One thing you're omitting is that a web request isn't a single sequential series of instructions that involve only the CPU.</p> <p>A typical web request handler might need to do some computation with the CPU, then read some config data off the disk, then ask the database server for some records that have to get transferred to it over ethernet, and so on. The CPU usage might be low, but it could still take a nontrivial amount of time due to waiting on all that I/O between each step.</p> <p>I think that, even with the GIL, Python can run other threads while one thread waits on I/O. (Other processes certainly can.) Still, Python threads aren't like Erlang threads: start enough of them and it'll start to hurt.</p> <p>Another issue is memory. C libraries are shared between processes, but (AFAIK) Python libraries aren't. So starting up 10x as many Python processes may reduce I/O waiting, but now you've got 10 copies of each Python module loaded, per core.</p> <p>I don't know how significant these are, but they do complicate things well beyond "R > 10 * S * C". There's lots still to be done in the Python world to solve them, because these aren't easy problems.</p>
1
2009-09-06T04:23:01Z
[ "python", "web-applications", "concurrency" ]
Python egg found interactively but not in fastcgi
1,384,717
<p>In agreement to <a href="http://stackoverflow.com/questions/531224/setting-up-django-on-an-internal-server-os-environ-not-working-as-expected">this question, and its answer</a>. I added the path of the egg and it worked. However, when I run python interactively and I import flup, it works without any problem or additional path specification. Where is the difference ?</p> <p><strong>Edit</strong>: It appears that while doing fastcgi stuff, the .pth files are not parsed, but this is only a guess. Need more official statement.</p>
1
2009-09-06T02:10:28Z
1,384,729
<p>Programs run by or code run in a web server has a restricted environment compared with what you use interactively. Most likely, the difference stems from the difference between your interactive environment and the FastCGI environment. What I can't tell you is which difference is critical in this context.</p>
0
2009-09-06T02:20:09Z
[ "python", "fastcgi", "egg" ]
Python egg found interactively but not in fastcgi
1,384,717
<p>In agreement to <a href="http://stackoverflow.com/questions/531224/setting-up-django-on-an-internal-server-os-environ-not-working-as-expected">this question, and its answer</a>. I added the path of the egg and it worked. However, when I run python interactively and I import flup, it works without any problem or additional path specification. Where is the difference ?</p> <p><strong>Edit</strong>: It appears that while doing fastcgi stuff, the .pth files are not parsed, but this is only a guess. Need more official statement.</p>
1
2009-09-06T02:10:28Z
1,384,775
<p>I've encountered a similar issue when running my Python applications under IIS (Windows). I've found that when running under ISAPI, eggs aren't readable because setuptools munges the permissions on zipped eggs, and because the ISAPI application runs under a limited privilege account.</p> <p>You may be experiencing the same situation in FastCGI. If the FastCGI process doesn't have permission to read the eggs or expand the eggs as necessary, you may have problems. Also, I've found that setting the PYTHON_EGG_CACHE environment variable to a directory that's writable by the process is also necessary for some eggs (in particular, eggs with binary/extension modules or resources that must be accessed as files).</p>
0
2009-09-06T03:01:20Z
[ "python", "fastcgi", "egg" ]
Python egg found interactively but not in fastcgi
1,384,717
<p>In agreement to <a href="http://stackoverflow.com/questions/531224/setting-up-django-on-an-internal-server-os-environ-not-working-as-expected">this question, and its answer</a>. I added the path of the egg and it worked. However, when I run python interactively and I import flup, it works without any problem or additional path specification. Where is the difference ?</p> <p><strong>Edit</strong>: It appears that while doing fastcgi stuff, the .pth files are not parsed, but this is only a guess. Need more official statement.</p>
1
2009-09-06T02:10:28Z
1,386,226
<p>After some more thorough analysis, I think I understand what's going on here.</p> <p>When Python starts up, it sets up the sys.path (all as part of initializing the interpreter).</p> <p>At this time, the environment is used to determine where to find .pth files. If no PYTHONPATH is defined at this time, then it won't find your modules installed to sys.prefix. Additionally, since easy-install.pth is probably installed to your custom prefix directory, it won't find that .pth file to be parsed.</p> <p>Adding environment variables to os.environ or sys.path after the interpreter has initialized won't cause .pth files to be parsed again. This is why you're finding yourself forced to manually do what you expect Python to do naturally.</p> <p>I think the correct solution is to make sure the custom path is available to the Python interpreter at the time the interpreter starts up (which is before mysite.fcgi is executed).</p> <p>I looked for options to add a PYTHONPATH environment variable to mod_fastcgi, but I see no such option. Perhaps it's a general Apache option, so not documented in mod_fastcgi, or perhaps it's not possible to set a static variable in the mod_fastcgi config.</p> <p>Given that, I believe you could produce a workaround with the following:</p> <ol> <li>Create a wrapper script (a shell script or another Python script) that will be your new FastCGI handler.</li> <li>In this wrapper script, set the PYTHONPATH environment variable to your prefix path (just as you have set in your user environment which works).</li> <li>Have the wrapper script launch the Python process for your original fastcgi handler (mysite.fcgi) with the altered environment.</li> </ol> <p>Although I don't have a good environment in which to test, I think a wrapper shell script would look something like:</p> <pre><code>#!/bin/sh export PYTHONPATH=/your/local/python/path /path/to/python /path/to/your/fastcgi/handler # this line should be similar to what was supplied to mod_fastcgi originally </code></pre> <p>There may be alternative workarounds to consider.</p> <ul> <li>From mysite.fgci, cause the Python to re-process the sys.path based on a new, altered environment. I don't know how this would be done, but this might be cleaner than having a wrapper script.</li> <li>Find an Apache/mod_fastcgi option that allows an environment variable (PYTHONPATH) to be specified to the fastcgi process.</li> </ul>
2
2009-09-06T17:42:41Z
[ "python", "fastcgi", "egg" ]
Python egg found interactively but not in fastcgi
1,384,717
<p>In agreement to <a href="http://stackoverflow.com/questions/531224/setting-up-django-on-an-internal-server-os-environ-not-working-as-expected">this question, and its answer</a>. I added the path of the egg and it worked. However, when I run python interactively and I import flup, it works without any problem or additional path specification. Where is the difference ?</p> <p><strong>Edit</strong>: It appears that while doing fastcgi stuff, the .pth files are not parsed, but this is only a guess. Need more official statement.</p>
1
2009-09-06T02:10:28Z
3,748,247
<p>I concur that even with the PYTHONPATH environment variable defined the .pth files do not get interpreted when python starts up in the FastCGI environment. I do not now why this is so, but I do have a suggestion for a workaround.</p> <p>Use site.addsitedir. It will interpret the .pth files allowing you to then import eggs simply by name without having to add the full path to each one.</p> <pre><code>#!/user/bin/python2.6 import site # adds a directory to sys.path and processes its .pth files site.addsitedir('/home/mhanney/.local/lib/python2.6/site-packages/') # avoids permissions error writing to system egg-cache os.environ['PYTHON_EGG_CACHE'] = '/home/mhanney/.local/egg-cache' </code></pre> <p>It is not necessary to use virtual env. At my shared hosting provider I just install eggs in ~/.local using</p> <pre><code>python setup.py install --prefix=~/.local </code></pre> <p>Here is a variation on the flup 'Hello World' example to dump the environment vars, path and modules, useful for debugging FastCGI.</p> <pre><code>#!/usr/bin/python2.6 import sys, os, site, StringIO from pprint import pprint as p # adds a directory to sys.path and processes its .pth files site.addsitedir('/home/mhanney/.local/lib/python2.6/site-packages/') # avoids permissions error writing to system egg-cache os.environ['PYTHON_EGG_CACHE'] = '/home/mhanney/.local/egg-cache' def test_app(environ, start_response): output = StringIO.StringIO() output.write("Environment:\n") for param in os.environ.keys(): output.write("%s %s\n" % (param,os.environ[param])) output.write("\n\nsys.path:\n") p(sys.path, output) output.write("\n\nsys.modules:\n") p(sys.modules, output) start_response('200 OK', [('Content-Type', 'text/plain')]) yield output.getvalue() if __name__ == '__main__': from flup.server.fcgi import WSGIServer WSGIServer(test_app).run() </code></pre>
0
2010-09-20T01:43:10Z
[ "python", "fastcgi", "egg" ]
Where should one place the code to autoincrement a sharded counter on Google App Engine/Django when one creates a new model?
1,384,932
<p>I've a model MyModel (extending Google's db.Model), and I want to keep track of the number of Models that have been created.</p> <p>I think the code at from Google's I/O talk on <a href="http://code.google.com/appengine/articles/sharding_counters.html" rel="nofollow">Sharding Counters</a> is quite good, so I'm using that. But I'm not sure where I ought to be calling the increment when creating a new code. (I'm using Django, and I've kept the familiar models.py, views.py, etc. layout to the project's applications.)</p> <p>There are a couple possibilities that seem to come to mind for where to put the incrementing code:</p> <ol> <li><p>Overload the Model.put() so that it increments the counter when the model is saved for the first time, and similarly overload Model.delete() to decrement the counter</p></li> <li><p>Attach some sort of listener to saves/deletes, and check that the save is of a new model (does GAE have such listeners?)</p></li> <li><p>Put the counter incrementing code in the function in view.py that creates/deletes models</p></li> </ol> <p>I'd be much obliged for suggestions and thoughts as to how to do this best (and pros/cons of each option).</p> <p>Thank you for reading.</p> <p>Best, Brian</p>
3
2009-09-06T05:26:18Z
1,386,885
<p>I suggest the approach (curiously close to "aspect oriented programming") suggested by "App Engine Fan" <a href="http://blog.appenginefan.com/2009/01/hacking-google-app-engine-part-1.html" rel="nofollow">here</a> (essentially "setting the scene") and especially <a href="http://blog.appenginefan.com/2009/01/hacking-google-app-engine-part-2.html" rel="nofollow">here</a> (showing the right solution: not "monkey patching" but rather the use of the well-architected built-in "hooks" facility of App Engine).</p> <p>The two "Hacks" he gives as examples are close enough to your use case that you should have no trouble implementing your code -- indeed it's not all that far from the "listener" solution you considered sub point (2), just somewhat more general because "hooks" can actually "interfere" with the operation (not that you need that here) as well as being able to run either before or after the operation itself (in your case I suspect "after" may be better, just in case the <code>put</code> fails somehow, in which case I imagine you don't want to count it).</p>
2
2009-09-06T22:25:53Z
[ "python", "django", "google-app-engine", "auto-increment", "sharding" ]
Django admin and showing thumbnail images
1,385,094
<p>I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong.</p> <p>Server media URL:</p> <pre><code>from django.conf import settings (r'^public/(?P&lt;path&gt;.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), </code></pre> <p>Function model:</p> <pre><code>def image_img(self): if self.image: return u'&lt;img src="%s" /&gt;' % self.image.url_125x125 else: return '(Sin imagen)' image_img.short_description = 'Thumb' image_img.allow_tags = True </code></pre> <p>admin.py:</p> <pre><code>class ImagesAdmin(admin.ModelAdmin): list_display= ('image_img','product',) </code></pre> <p>And the result:</p> <pre><code>&lt;img src="http://127.0.0.1:8000/public/product_images/6a00d8341c630a53ef0120a556b3b4970c.125x125.jpg" /&gt; </code></pre>
44
2009-09-06T07:15:35Z
1,385,145
<p>This is in the source for <a href="http://code.google.com/p/django-photologue/">photologue</a> (see <code>models.py</code>, slightly adapted to remove irrelevant stuff):</p> <pre><code>def admin_thumbnail(self): return u'&lt;img src="%s" /&gt;' % (self.image.url) admin_thumbnail.short_description = 'Thumbnail' admin_thumbnail.allow_tags = True </code></pre> <p>The <code>list_display</code> bit looks identical too, and I know that works. The only thing that looks suspect to me is your indentation - the two lines beginning <code>image_img</code> at the end of your <code>models.py</code> code should be level with <code>def image_img(self):</code>, like this:</p> <pre><code>def image_img(self): if self.image: return u'&lt;img src="%s" /&gt;' % self.image.url_125x125 else: return '(Sin imagen)' image_img.short_description = 'Thumb' image_img.allow_tags = True </code></pre>
64
2009-09-06T07:43:07Z
[ "python", "django", "django-admin" ]
Django admin and showing thumbnail images
1,385,094
<p>I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong.</p> <p>Server media URL:</p> <pre><code>from django.conf import settings (r'^public/(?P&lt;path&gt;.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), </code></pre> <p>Function model:</p> <pre><code>def image_img(self): if self.image: return u'&lt;img src="%s" /&gt;' % self.image.url_125x125 else: return '(Sin imagen)' image_img.short_description = 'Thumb' image_img.allow_tags = True </code></pre> <p>admin.py:</p> <pre><code>class ImagesAdmin(admin.ModelAdmin): list_display= ('image_img','product',) </code></pre> <p>And the result:</p> <pre><code>&lt;img src="http://127.0.0.1:8000/public/product_images/6a00d8341c630a53ef0120a556b3b4970c.125x125.jpg" /&gt; </code></pre>
44
2009-09-06T07:15:35Z
11,475,926
<p>Adding on to @dominic, I wanted to use this in multiple models, so I created a function that I could call in each model, inputing the image to be displayed.</p> <p>For instance in one app I have:</p> <pre><code>from django.contrib import admin from .models import Frontpage from ..admin import image_file class FrontpageAdmin(admin.ModelAdmin): list_display = ('image_thumb', ...) image_thumb = image_file('obj.image()') admin.site.register(Frontpage, FrontpageAdmin) </code></pre> <p>with <code>image</code> a function of Frontpage that returns an image.</p> <p>In another app I have:</p> <pre><code>from django.contrib import admin from .models import Exhibition from ..admin import image_file class ExhibitionAdmin(admin.ModelAdmin): list_display = ('first_image_thumb', ...) first_image_thumb = image_file('obj.related_object.image', short_description='First Image') admin.site.register(Exhibition, ExhibitionAdmin) </code></pre> <p>This allows me to specify the image object and the <code>short_description</code> while keeping the boilerplate in another file. The function is:</p> <pre><code>from sorl.thumbnail import get_thumbnail from django.conf import settings def image_file(image, short_description='Image'): def image_thumb(self, obj): image = eval(image_thumb.image) if image: thumb = get_thumbnail(image.file, settings.ADMIN_THUMBS_SIZE) return u'&lt;img width="{}" height={} src="{}" /&gt;'.format(thumb.width, thumb.height, thumb.url) else: return "No Image" image_thumb.__dict__.update({'short_description': short_description, 'allow_tags': True, 'image': image}) return image_thumb </code></pre>
6
2012-07-13T18:06:17Z
[ "python", "django", "django-admin" ]
Django admin and showing thumbnail images
1,385,094
<p>I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong.</p> <p>Server media URL:</p> <pre><code>from django.conf import settings (r'^public/(?P&lt;path&gt;.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), </code></pre> <p>Function model:</p> <pre><code>def image_img(self): if self.image: return u'&lt;img src="%s" /&gt;' % self.image.url_125x125 else: return '(Sin imagen)' image_img.short_description = 'Thumb' image_img.allow_tags = True </code></pre> <p>admin.py:</p> <pre><code>class ImagesAdmin(admin.ModelAdmin): list_display= ('image_img','product',) </code></pre> <p>And the result:</p> <pre><code>&lt;img src="http://127.0.0.1:8000/public/product_images/6a00d8341c630a53ef0120a556b3b4970c.125x125.jpg" /&gt; </code></pre>
44
2009-09-06T07:15:35Z
21,449,282
<p>Add a method in your model (<code>models.py</code>):</p> <pre><code>def image_tag(self): return u'&lt;img src="%s" /&gt;' % &lt;URL to the image&gt; image_tag.short_description = 'Image' image_tag.allow_tags = True </code></pre> <p>and in your ModelAdmin (<code>admin.py</code>) add:</p> <pre><code>readonly_fields = ('image_tag',) </code></pre>
6
2014-01-30T06:24:23Z
[ "python", "django", "django-admin" ]
Django admin and showing thumbnail images
1,385,094
<p>I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong.</p> <p>Server media URL:</p> <pre><code>from django.conf import settings (r'^public/(?P&lt;path&gt;.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), </code></pre> <p>Function model:</p> <pre><code>def image_img(self): if self.image: return u'&lt;img src="%s" /&gt;' % self.image.url_125x125 else: return '(Sin imagen)' image_img.short_description = 'Thumb' image_img.allow_tags = True </code></pre> <p>admin.py:</p> <pre><code>class ImagesAdmin(admin.ModelAdmin): list_display= ('image_img','product',) </code></pre> <p>And the result:</p> <pre><code>&lt;img src="http://127.0.0.1:8000/public/product_images/6a00d8341c630a53ef0120a556b3b4970c.125x125.jpg" /&gt; </code></pre>
44
2009-09-06T07:15:35Z
37,965,195
<h1>Update v. 1.9</h1> <p>Note that in Django v.1.9 <strike></p> <pre><code>image_tag.allow_tags = True </code></pre> <p></strike></p> <blockquote> <p><a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display" rel="nofollow">is depricated and you should use format_html(), format_html_join(), or <strong>mark_safe()</strong> instead</a></p> </blockquote> <p>So your model.py should look like this:</p> <pre><code>... def image_img(self): if self.image: return marksafe('&lt;img src="%s" /&gt;' % self.image.url_125x125) else: return '(Sin imagen)' image_img.short_description = 'Thumb' </code></pre> <p>and in your <em>admin.py</em> add:</p> <pre><code>list_display= ('image_img','product',) readonly_fields = ('image_img',) </code></pre> <p>and for adding it in the 'Edit mode' of your admin panel in your <em>admin.py</em> add:</p> <pre><code>fields = ( 'image_img', ) </code></pre>
3
2016-06-22T10:23:21Z
[ "python", "django", "django-admin" ]
Django admin and showing thumbnail images
1,385,094
<p>I'm trying to show thumbnail images in Django admin, but I can only see the path to the images, but not the rendered images. I don't know what I'm doing wrong.</p> <p>Server media URL:</p> <pre><code>from django.conf import settings (r'^public/(?P&lt;path&gt;.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), </code></pre> <p>Function model:</p> <pre><code>def image_img(self): if self.image: return u'&lt;img src="%s" /&gt;' % self.image.url_125x125 else: return '(Sin imagen)' image_img.short_description = 'Thumb' image_img.allow_tags = True </code></pre> <p>admin.py:</p> <pre><code>class ImagesAdmin(admin.ModelAdmin): list_display= ('image_img','product',) </code></pre> <p>And the result:</p> <pre><code>&lt;img src="http://127.0.0.1:8000/public/product_images/6a00d8341c630a53ef0120a556b3b4970c.125x125.jpg" /&gt; </code></pre>
44
2009-09-06T07:15:35Z
38,718,178
<p>With <a href="https://github.com/matthewwithanm/django-imagekit" rel="nofollow">django-imagekit</a> you can add any image like this:</p> <pre><code>from imagekit.admin import AdminThumbnail @register(Fancy) class FancyAdmin(ModelAdmin): list_display = ['name', 'image_display'] image_display = AdminThumbnail(image_field='image') image_display.short_description = 'Image' # set this to also show the image in the change view readonly_fields = ['image_display'] </code></pre>
1
2016-08-02T10:39:14Z
[ "python", "django", "django-admin" ]
Unpickling classes from Python 3 in Python 2
1,385,096
<p>If a Python 3 class is pickled using protocol 2, it is supposed to work in Python 2, but unfortunately, this fails because the names of some classes have changed.</p> <p>Assume we have code called as follows.</p> <p>Sender</p> <pre><code>pickle.dumps(obj,2) </code></pre> <p>Receiver</p> <pre><code>pickle.loads(atom) </code></pre> <p>To give a specific case, if <code>obj={}</code>, then the error given is:</p> <blockquote> <p>ImportError: No module named builtins</p> </blockquote> <p>This is because Python 2 uses <code>__builtin__</code> instead.</p> <p>The question is the best way to fix this problem.</p>
5
2009-09-06T07:15:54Z
1,385,100
<p>This problem is <a href="http://bugs.python.org/issue3675" rel="nofollow">Python issue 3675</a>. This bug is actually fixed in Python 3.11.</p> <p>If we import:</p> <pre><code>from lib2to3.fixes.fix_imports import MAPPING </code></pre> <p>MAPPING maps Python 2 names to Python 3 names. We want this in reverse.</p> <pre><code>REVERSE_MAPPING={} for key,val in MAPPING.items(): REVERSE_MAPPING[val]=key </code></pre> <p>We can override the Unpickler and loads</p> <pre><code>class Python_3_Unpickler(pickle.Unpickler): """Class for pickling objects from Python 3""" def find_class(self,module,name): if module in REVERSE_MAPPING: module=REVERSE_MAPPING[module] __import__(module) mod = sys.modules[module] klass = getattr(mod, name) return klass def loads(str): file = pickle.StringIO(str) return Python_3_Unpickler(file).load() </code></pre> <p>We then call this loads instead of pickle.loads.</p> <p>This should solve the problem.</p>
11
2009-09-06T07:18:45Z
[ "python", "python-3.x", "pickle" ]
Edit python31 file and it opens notepad and starts python26
1,385,280
<p>I am in python31, </p> <p>then I go to file open i left click to open file and it opens in notepad(simple text editor)python31</p> <p>The moment it opens the notepad, it starts python26</p> <p>I thought it has something to open with, and I have changed that to python31 And it still opens python26</p> <p>EDIT:</p> <p>The file is created by python26, but it is not executable. </p>
-1
2009-09-06T09:27:10Z
1,385,322
<p>I am guessing here, the question it not very clear. </p> <p>It sounds like the .py extension in Windows is associated with the Python 2.6 runtime. (This normally get setup this way during installation of Python on Windows). You can change this by updating the associated file extensions and programs in Windows.</p> <p>By double clicking on the file it is not opening the file for editing but instead running it. If you want to edit the file you have to either right-click and select an approriate edit action or open the file from your editor's 'open file' action. (Or change the .py extension to open in your favourite editor)</p>
0
2009-09-06T10:01:35Z
[ "python", "windows", "python-3.x" ]
Edit python31 file and it opens notepad and starts python26
1,385,280
<p>I am in python31, </p> <p>then I go to file open i left click to open file and it opens in notepad(simple text editor)python31</p> <p>The moment it opens the notepad, it starts python26</p> <p>I thought it has something to open with, and I have changed that to python31 And it still opens python26</p> <p>EDIT:</p> <p>The file is created by python26, but it is not executable. </p>
-1
2009-09-06T09:27:10Z
1,385,779
<p>I had similar problems, and right clicking and changing edit options didn't solve it. You can try repairing python31 installation with running the msi installer and selecting it as the default python</p>
0
2009-09-06T14:18:41Z
[ "python", "windows", "python-3.x" ]
Calling non-static method from static one in Python
1,385,546
<p>I can't find if it's possible to call a non-static method from a static one in Python.</p> <p>Thanks</p> <p>EDIT: Ok. And what about static from static? Can I do this:</p> <pre><code>class MyClass(object): @staticmethod def static_method_one(cmd): ... @staticmethod def static_method_two(cmd): static_method_one(cmd) </code></pre>
3
2009-09-06T12:20:29Z
1,385,553
<p>When in a static method, you don't have a self instance: what object are you calling the non-static methods on? Certainly if you have an instance lying around, you can call methods on it.</p>
2
2009-09-06T12:22:45Z
[ "python", "oop" ]
Calling non-static method from static one in Python
1,385,546
<p>I can't find if it's possible to call a non-static method from a static one in Python.</p> <p>Thanks</p> <p>EDIT: Ok. And what about static from static? Can I do this:</p> <pre><code>class MyClass(object): @staticmethod def static_method_one(cmd): ... @staticmethod def static_method_two(cmd): static_method_one(cmd) </code></pre>
3
2009-09-06T12:20:29Z
1,385,563
<p>It's not possible withotut the instance of the class. You could add a param to your method <code>f(x, y, ..., me)</code> and use <code>me</code> as the object to call the non-static methods on.</p>
0
2009-09-06T12:28:24Z
[ "python", "oop" ]
Calling non-static method from static one in Python
1,385,546
<p>I can't find if it's possible to call a non-static method from a static one in Python.</p> <p>Thanks</p> <p>EDIT: Ok. And what about static from static? Can I do this:</p> <pre><code>class MyClass(object): @staticmethod def static_method_one(cmd): ... @staticmethod def static_method_two(cmd): static_method_one(cmd) </code></pre>
3
2009-09-06T12:20:29Z
1,385,611
<p>After the other answers and your follow-up question - regarding static method from static method: Yes you can:</p> <pre><code>&gt;&gt;&gt; class MyClass(object): @staticmethod def static_method_one(x): return MyClass.static_method_two(x) @staticmethod def static_method_two(x): return 2 * x &gt;&gt;&gt; MyClass.static_method_one(5) 10 </code></pre> <p>And, in case you're curious, also yes for class method from class method (easy to test this stuff in the interpreter - all this is cut and pasted from Idle in 2.5.2) <code>[**EDITED to make correction in usage pointed out by others**]</code>:</p> <pre><code>&gt;&gt;&gt; class MyClass2(object): @classmethod def class_method_one(cls, x): return cls.class_method_two(x) @classmethod def class_method_two(cls, x): return 2 * x &gt;&gt;&gt; MyClass2.class_method_one(5) 10 </code></pre>
2
2009-09-06T12:57:05Z
[ "python", "oop" ]
Calling non-static method from static one in Python
1,385,546
<p>I can't find if it's possible to call a non-static method from a static one in Python.</p> <p>Thanks</p> <p>EDIT: Ok. And what about static from static? Can I do this:</p> <pre><code>class MyClass(object): @staticmethod def static_method_one(cmd): ... @staticmethod def static_method_two(cmd): static_method_one(cmd) </code></pre>
3
2009-09-06T12:20:29Z
1,385,633
<p>Use class methods, not static methods. Why else put it inside a class?</p> <pre><code>class MyClass(object): @classmethod def static_method_one(cls, cmd): ... @classmethod def static_method_two(cls, cmd): cls.static_method_one(cmd) </code></pre>
3
2009-09-06T13:06:04Z
[ "python", "oop" ]
Calling non-static method from static one in Python
1,385,546
<p>I can't find if it's possible to call a non-static method from a static one in Python.</p> <p>Thanks</p> <p>EDIT: Ok. And what about static from static? Can I do this:</p> <pre><code>class MyClass(object): @staticmethod def static_method_one(cmd): ... @staticmethod def static_method_two(cmd): static_method_one(cmd) </code></pre>
3
2009-09-06T12:20:29Z
1,385,650
<p>It's perfectly possible, but not very meaningful. Ponder the following class:</p> <pre><code>class MyClass: # Normal method: def normal_method(self, data): print "Normal method called with instance %s and data %s" % (self, data) @classmethod def class_method(cls, data): print "Class method called with class %s and data %s" % (cls, data) @staticmethod def static_method(data): print "Static method called with data %s" % (data) </code></pre> <p>Obviously, we can call this in the expected ways:</p> <pre><code>&gt;&gt;&gt; instance = MyClass() &gt;&gt;&gt; instance.normal_method("Success!") Normal method called with instance &lt;__main__.MyClass instance at 0xb7d26bcc&gt; and data Success! &gt;&gt;&gt; instance.class_method("Success!") Class method called with class __main__.MyClass and data Success! &gt;&gt;&gt; instance.static_method("Success!") Static method called with data Success! </code></pre> <p>But also consider this:</p> <pre><code>&gt;&gt;&gt; MyClass.normal_method(instance, "Success!") Normal method called with instance &lt;__main__.MyClass instance at 0xb7d26bcc&gt; and data Success! </code></pre> <p>The syntax <code>instance.normal_method()</code> is pretty much just a "shortcut" for <code>MyClass.normal_method(instance)</code>. That's why there is this "self" parameter in methods, to pass in self. The name self is not magical, you can call it whatever you want.</p> <p>The same trick is perfectly possible from withing a static method. You can call the normal method with an instance as first parameter, like so:</p> <pre><code> @staticmethod def a_cool_static_method(instance, data): print "Cool method called with instance %s and data %s" % (instance, data) MyClass.normal_method(instance, data) MyClass.class_method(data) MyClass.static_method(data) &gt;&gt;&gt; instance.a_cool_static_method(instance, "So Cool!") Cool method called with instance &lt;__main__.MyClass instance at 0xb7d26bcc&gt; and data So Cool! Normal method called with instance &lt;__main__.MyClass instance at 0xb7d26bcc&gt; and data So Cool! Class method called with class __main__.MyClass and data So Cool! Static method called with data So Cool! </code></pre> <p>So the answer is yes, you can cal non-static methods from static methods. But only if you can pass in an instance as first parameter. So you either have to generate it from inside the static method (and in that case you are probably better off with a class method) or pass it in. But if you pass in the instance, you can typically just make it a normal method.</p> <p>So you can, but, it's pretty pointless.</p> <p>And that then begs the question: Why do you want to?</p>
7
2009-09-06T13:13:35Z
[ "python", "oop" ]