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 |
|---|---|---|---|---|---|---|---|---|---|
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 1,213,801 | <p>I use <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">easy_install</a> with Apple's Python, and it works like a charm.</p>
| -1 | 2009-07-31T17:21:32Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 1,213,811 | <p>Regarding which python version to use, Mac OS usually ships an old version of python. It's a good idea to upgrade to a newer version. You can download a .dmg from <a href="http://www.python.org/download/" rel="nofollow">http://www.python.org/download/</a> . If you do that, remember to update the path. You can find the exact commands here <a href="http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/" rel="nofollow">http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/</a></p>
| 1 | 2009-07-31T17:23:02Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 1,213,823 | <p>Please see <a href="http://stackoverflow.com/questions/1169025/python-os-x-10-5-development-environment">Python OS X development environment</a>. The best way is to use <a href="http://www.macports.org/">MacPorts</a>. Download and install MacPorts, then install Python via MacPorts by typing the following commands in the Terminal:</p>
<pre>
sudo port install python26 python_select
sudo port select --set python python26
</pre>
<p>OR</p>
<pre>
sudo port install python30 python_select
sudo port select --set python python30
</pre>
<p>Use the first set of commands to install Python 2.6 and the second set to install Python 3.0. Then use:</p>
<pre>
sudo port install py26-packagename
</pre>
<p>OR</p>
<pre>
sudo port install py30-packagename
</pre>
<p>In the above commands, replace <i>packagename</i> with the name of the package, for example:</p>
<pre>
sudo port install py26-setuptools
</pre>
<p>These commands will automatically install the package (and its dependencies) for the given Python version.</p>
<p>For a full list of available packages for Python, type:</p>
<pre>
port list | grep py26-
</pre>
<p>OR</p>
<pre>
port list | grep py30-
</pre>
<p>Which command you use depends on which version of Python you chose to install.</p>
| 30 | 2009-07-31T17:25:10Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 1,214,096 | <p>There's nothing wrong with using a MacPorts Python installation. If you are installing python modules from MacPorts but then not seeing them, that likely means you are not invoking the MacPorts python you installed to. In a terminal shell, you can use absolute paths to invoke the various Pythons that may be installed. For example:</p>
<pre><code>$ /usr/bin/python2.5 # Apple-supplied 2.5 (Leopard)
$ /opt/local/bin/python2.5 # MacPorts 2.5
$ /opt/local/bin/python2.6 # MacPorts 2.6
$ /usr/local/bin/python2.6 # python.org (MacPython) 2.6
$ /usr/local/bin/python3.1 # python.org (MacPython) 3.1
</code></pre>
<p>To get the right python by default requires ensuring your shell $PATH is set properly to ensure that the right executable is found first. Another solution is to define shell aliases to the various pythons.</p>
<p>A python.org (MacPython) installation is fine, too, as others have suggested. <code>easy_install</code> can help but, again, because each Python instance may have its own <code>easy_install</code> command, make sure you are invoking the right <code>easy_install</code>.</p>
| 6 | 2009-07-31T18:26:32Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 1,214,123 | <p>I use MacPorts to install Python and any third-party modules tracked by MacPorts into <code>/opt/local</code>, and I install any manually installed modules (those not in the MacPorts repository) into <code>/usr/local</code>, and this has never caused any problems. I think you may be confused as to the use of certain MacPorts scripts and environment variables.</p>
<p>MacPorts <code>python_select</code> is used to select the "current" version of Python, but it has nothing to do with modules. This allows you to, e.g., install both Python 2.5 and Python 2.6 using MacPorts, and switch between installs.</p>
<p>The <code>$PATH</code> environment variables does <em>not</em> affect what Python modules are loaded. <code>$PYTHONPATH</code> is what you are looking for. <code>$PYTHONPATH</code> should point to directories containing Python modules you want to load. In my case, my <code>$PYTHONPATH</code> variable contains <code>/usr/local/lib/python26/site-packages</code>. If you use MacPorts' Python, it sets up the other proper directories for you, so you only need to add <em>additional</em> paths to <code>$PYTHONPATH</code>. But again, <code>$PATH</code> isn't used at all when Python searches for modules you have installed.</p>
<p><code>$PATH</code> <em>is</em> used to find executables, so if you install MacPorts' Python, make sure <code>/opt/local/bin</code> is in your <code>$PATH</code>.</p>
| 6 | 2009-07-31T18:31:26Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 1,283,224 | <p>For MacPython installations, I found an effective solution to fixing the problem with setuptools (easy_install) in this blog post:</p>
<p><a href="http://droidism.com/getting-running-with-django-and-macpython-26-on-leopard" rel="nofollow">http://droidism.com/getting-running-with-django-and-macpython-26-on-leopard</a></p>
<p>One handy tip includes finding out which version of python is active in the terminal:</p>
<pre><code>which python
</code></pre>
| 3 | 2009-08-16T00:44:05Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 2,380,159 | <p>If you use Python from MacPorts, it has it's own easy_install located at: <strong>/opt/local/bin/easy_install-2.6</strong> (for py26, that is). It's not the same one as simply calling easy_install directly, even if you used python_select to change your default python command.</p>
| 6 | 2010-03-04T14:51:18Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 7,220,022 | <p>Your question is already three years old and there are some details not covered in other answers:</p>
<p>Most people I know use <a href="http://mxcl.github.com/homebrew/">HomeBrew</a> or <a href="https://trac.macports.org/wiki/Python">MacPorts</a>, I prefer MacPorts because of its clean cut of what is a default Mac OS X environment and my development setup. Just move out your <em>/opt</em> folder and test your packages with a normal user Python environment</p>
<p>MacPorts is only portable within Mac, but with easy_install or pip you will learn how to setup your environment in any platform (Win/Mac/Linux/Bsd...). Furthermore it will always be more up to date and with more packages</p>
<p>I personally let MacPorts handle my Python modules to keep everything updated. Like any other high level package manager (ie: apt-get) it is much better for the heavy lifting of modules with lots of binary dependencies. There is no way I would build my Qt bindings (PySide) with easy_install or pip. Qt is huge and takes a lot to compile. As soon as you want a Python package that needs a library used by non Python programs, try to avoid easy_install or pip </p>
<p>At some point you will find that there are some packages missing within MacPorts. I do not believe that MacPorts will ever give you the whole <a href="http://pypi.python.org/pypi">CheeseShop</a>. For example, recently I needed the <a href="http://elixir.ematia.de/trac/wiki">Elixir</a> module, but MacPorts only offers py25-elixir and py26-elixir, no py27 version. In cases like these you have:</p>
<blockquote>
<p>pip-2.7 install --user elixir</p>
</blockquote>
<p>( make sure you always type pip-(version) )</p>
<p>That will build an extra Python library in your home dir. Yes, Python will work with more than one library location: one controlled by MacPorts and a user local one for everything missing within MacPorts.</p>
<p>Now notice that I favor pip over easy_install. There is a good reason you should avoid setuptools and easy_install. Here is a <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">good explanation</a> and I try to keep away from them. One very useful feature of pip is giving you a list of all the modules (along their versions) that you installed with MacPorts, easy_install and pip itself:</p>
<blockquote>
<p>pip-2.7 freeze</p>
</blockquote>
<p>If you already started using easy_install, don't worry, pip can recognize everything done already by easy_install and even upgrade the packages installed with it.</p>
<p>If you are a developer keep an eye on <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> for controlling different setups and combinations of module versions. Other answers mention it already, what is not mentioned so far is the <a href="http://pypi.python.org/pypi/tox">Tox</a> module, a tool for testing that your package installs correctly with different Python versions.</p>
<p>Although I usually do not have version conflicts, I like to have virtualenv to set up a clean environment and get a clear view of my packages dependencies. That way I never forget any dependencies in my setup.py</p>
<p>If you go for MacPorts be aware that multiple versions of the same package are not selected anymore like the old Debian style with an extra python_select package (it is still there for compatibility). Now you have the select command to choose which Python version will be used (you can even select the Apple installed ones):</p>
<pre><code>$ port select python
Available versions for python:
none
python25-apple
python26-apple
python27 (active)
python27-apple
python32
$ port select python python32
</code></pre>
<p>Add tox on top of it and your programs should be really portable</p>
| 37 | 2011-08-28T09:13:47Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What is the most compatible way to install python modules on a Mac? | 1,213,690 | <p>I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble.</p>
<p>On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding that most of the python modules I install with it are not being seen by python. I've spent some time playing around with PATH settings and using python_select . Nothing has really worked and at this point I'm not really understanding, instead I'm just poking around.</p>
<p>I get the impression that Macports isn't universally loved for managing python modules. I'd like to start fresh using a more "accepted" (if that's the right word) approach. </p>
<p><strong>So, I was wondering, what is the method that Mac python developers use to manage their modules?</strong></p>
<p>Bonus questions: </p>
<p>Do you use Apple's python, or some other version?
Do you compile everything from source or is there a package manger that works well (Fink?).</p>
<p>Any tips or suggestions here are greatly appreciated. Thanks for your time. :)</p>
| 108 | 2009-07-31T16:58:55Z | 19,816,612 | <p>Directly install one of the fink packages (Django 1.6 as of 2013-Nov)</p>
<pre><code>fink install django-py27
fink install django-py33
</code></pre>
<p>Or create yourself a virtualenv:</p>
<pre><code>fink install virtualenv-py27
virtualenv django-env
source django-env/bin/activate
pip install django
deactivate # when you are done
</code></pre>
<p>Or use fink django plus any other pip installed packages in a virtualenv</p>
<pre><code>fink install django-py27
fink install virtualenv-py27
virtualenv django-env --system-site-packages
source django-env/bin/activate
# django already installed
pip install django-analytical # or anything else you might want
deactivate # back to your normally scheduled programming
</code></pre>
| -1 | 2013-11-06T15:53:01Z | [
"python",
"osx",
"module",
"packages",
"macports"
] |
What user do python scripts run as in windows? | 1,213,706 | <p>I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?</p>
<pre><code>WindowsError: [Error 5] Access is denied: 'path'
</code></pre>
<p>is what I get when I run the script.<br />
I've tried </p>
<pre><code>shutil.rmtree
os.remove
os.rmdir
</code></pre>
<p>they all return the same error.</p>
| 21 | 2009-07-31T17:02:28Z | 1,213,713 | <p>I've never used Python, but I would assume it runs as whatever user executes the script.</p>
| 4 | 2009-07-31T17:03:52Z | [
"python",
"windows",
"file-permissions"
] |
What user do python scripts run as in windows? | 1,213,706 | <p>I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?</p>
<pre><code>WindowsError: [Error 5] Access is denied: 'path'
</code></pre>
<p>is what I get when I run the script.<br />
I've tried </p>
<pre><code>shutil.rmtree
os.remove
os.rmdir
</code></pre>
<p>they all return the same error.</p>
| 21 | 2009-07-31T17:02:28Z | 1,213,724 | <p>How are you running the script? From an interactive console session? If so, just open up a DOS command window (using cmd) and type 'whoami'. That is who you are running the scripts interactively.</p>
<p>Ok I saw your edits just now...why don't you print the path and check the properties to see if the user account running the scripts has the required privileges?</p>
<p>If whoami does not work on your version of Windows, you may use the environment variables like SET USERNAME and SET DOMAINNAME from your command window.</p>
| 0 | 2009-07-31T17:06:12Z | [
"python",
"windows",
"file-permissions"
] |
What user do python scripts run as in windows? | 1,213,706 | <p>I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?</p>
<pre><code>WindowsError: [Error 5] Access is denied: 'path'
</code></pre>
<p>is what I get when I run the script.<br />
I've tried </p>
<pre><code>shutil.rmtree
os.remove
os.rmdir
</code></pre>
<p>they all return the same error.</p>
| 21 | 2009-07-31T17:02:28Z | 1,213,743 | <p>If the script is being run as a scheduled task (which seems likely for a cleanup script), it will probably run as SYSTEM. It's (unwise, but) possible to set permissions on directories so that SYSTEM has no access.</p>
| 0 | 2009-07-31T17:09:15Z | [
"python",
"windows",
"file-permissions"
] |
What user do python scripts run as in windows? | 1,213,706 | <p>I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?</p>
<pre><code>WindowsError: [Error 5] Access is denied: 'path'
</code></pre>
<p>is what I get when I run the script.<br />
I've tried </p>
<pre><code>shutil.rmtree
os.remove
os.rmdir
</code></pre>
<p>they all return the same error.</p>
| 21 | 2009-07-31T17:02:28Z | 1,213,758 | <p>Are the directories empty, and if not do those methods support decursively deleting the contents of a directory?</p>
| 0 | 2009-07-31T17:12:10Z | [
"python",
"windows",
"file-permissions"
] |
What user do python scripts run as in windows? | 1,213,706 | <p>I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?</p>
<pre><code>WindowsError: [Error 5] Access is denied: 'path'
</code></pre>
<p>is what I get when I run the script.<br />
I've tried </p>
<pre><code>shutil.rmtree
os.remove
os.rmdir
</code></pre>
<p>they all return the same error.</p>
| 21 | 2009-07-31T17:02:28Z | 1,213,797 | <p>The scripts have no special user, they just run under the currently logged-in user which executed the script.</p>
<p>Have you tried checking that:</p>
<ul>
<li>you are trying to delete a valid path? and that</li>
<li>the path has no locked files?</li>
</ul>
| 3 | 2009-07-31T17:20:31Z | [
"python",
"windows",
"file-permissions"
] |
What user do python scripts run as in windows? | 1,213,706 | <p>I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?</p>
<pre><code>WindowsError: [Error 5] Access is denied: 'path'
</code></pre>
<p>is what I get when I run the script.<br />
I've tried </p>
<pre><code>shutil.rmtree
os.remove
os.rmdir
</code></pre>
<p>they all return the same error.</p>
| 21 | 2009-07-31T17:02:28Z | 1,214,935 | <p>We've had issues removing files and directories on Windows, even if we had just copied them, if they were set to 'readonly'. <code>shutil.rmtree()</code> offers you sort of exception handlers to handle this situation. You call it and provide an exception handler like this:</p>
<pre><code>import errno, os, stat, shutil
def handleRemoveReadonly(func, path, exc):
excvalue = exc[1]
if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
func(path)
else:
raise
shutil.rmtree(filename, ignore_errors=False, onerror=handleRemoveReadonly)
</code></pre>
<p>You might want to try that.</p>
| 41 | 2009-07-31T21:15:18Z | [
"python",
"windows",
"file-permissions"
] |
What user do python scripts run as in windows? | 1,213,706 | <p>I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights?</p>
<pre><code>WindowsError: [Error 5] Access is denied: 'path'
</code></pre>
<p>is what I get when I run the script.<br />
I've tried </p>
<pre><code>shutil.rmtree
os.remove
os.rmdir
</code></pre>
<p>they all return the same error.</p>
| 21 | 2009-07-31T17:02:28Z | 9,735,134 | <p>@ThomasH : another brick to the wall.</p>
<p>On unix systems, you have to ensure that parent directory is writeable too.
Here is another version :</p>
<pre><code>def remove_readonly(func, path, exc):
excvalue = exc[1]
if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
# ensure parent directory is writeable too
pardir = os.path.abspath(os.path.join(path, os.path.pardir))
if not os.access(pardir, os.W_OK):
os.chmod(pardir, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO)
os.chmod(path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
func(path)
else:
raise
</code></pre>
| 0 | 2012-03-16T09:59:24Z | [
"python",
"windows",
"file-permissions"
] |
Remap keyboard navigation with Jython / Swing | 1,213,730 | <p>I'm trying to remap several navigation keys:</p>
<ul>
<li>ENTER: to work like standard TAB behavior (focus to next control)</li>
<li>SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control)</li>
<li>UP / DOWN arrows: previous /next control</li>
<li>etc</li>
</ul>
<p>I tried with a couple of options but without luck:</p>
<pre><code>from javax.swing import *
from java.awt import *
class JTextFieldX(JTextField):
def __init__(self, *args):
# Thanks, Jack!!
JTextField.__init__(
self,
focusGained=self.onGotFocus,
focusLost=self.onLostFocus,
*args)
def onGotFocus (self, event):
print "onGotFocus "
self.selectionStart = 0
self.selectionEnd = len(self.text)
def onLostFocus (self, event):
print "onLostFocus ", self.name
class Test(JFrame):
def __init__(self):
JFrame.__init__(self,
'JDesktopPane and JInternalFrame Demo',
size=(600, 300),
defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
self.desktop = JDesktopPane()
self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)
frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
panel = JPanel()
self.label = JLabel('Hello from Jython')
panel.add(self.label)
self.textfield1 = JTextFieldX('Type something here', 15)
panel.add(self.textfield1)
self.textfield2 = JTextFieldX('and click Copy', 15)
panel.add(self.textfield2)
panel.add(copyButton)
frame.add(panel)
frame.pack()
self.desktop.add(frame)
# ENTER=SPACE remapping for buttons (works ok, but only for buttons)
# inputMap = UIManager.getDefaults().get("Button.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed SPACE"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released SPACE"));
# # pressedAction = self.noAction
# inputMap.put (KeyStroke.getKeyStroke("pressed ENTER"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released ENTER"), releasedAction)
# # Attemp to remap ENTER=TAB for TextFields (didn't work, no errors)
# inputMap = UIManager.getDefaults().get("TextField.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed TAB"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released TAB"));
# inputMap.put (KeyStroke.getKeyStroke("pressed W"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released W"), releasedAction)
# # Attemp to remap ENTER=TAB for all controls (didn't work, no errors)
# spaceMap = self.textfield1.getInputMap().get(KeyStroke.getKeyStroke(event.KeyEvent.VK_TAB, 0, True));
# self.textfield1.getInputMap().put(KeyStroke.getKeyStroke(event.KeyEvent.VK_ENTER, 0, True),spaceMap);
frame.setSelected(1)
frame.moveToFront()
def noAction (self, event):
print "noAction"
pass
if __name__ == '__main__':
test = Test()
test.setLocation(100, 100)
test.show()
</code></pre>
| 3 | 2009-07-31T17:07:38Z | 1,213,879 | <p>Add keyPressed to the swing competent that you want to listen for the key press on</p>
<pre><code>self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey)
</code></pre>
<p><strong><em>myOnKey can be named anything in that method do something like:</em></strong></p>
<pre><code>def myOnKey(self,event):
print str(event) # see all other info you can get.
key_code = event.keyCode
if key_code == 10:
print "you pressed enter"
# simulate the "tab" by just focusing the next textbox...
</code></pre>
<p>Then you should just be able to play around with the print str(event) command to get all the proper keycodes that you want.</p>
| 0 | 2009-07-31T17:37:08Z | [
"python",
"swing",
"jython"
] |
Remap keyboard navigation with Jython / Swing | 1,213,730 | <p>I'm trying to remap several navigation keys:</p>
<ul>
<li>ENTER: to work like standard TAB behavior (focus to next control)</li>
<li>SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control)</li>
<li>UP / DOWN arrows: previous /next control</li>
<li>etc</li>
</ul>
<p>I tried with a couple of options but without luck:</p>
<pre><code>from javax.swing import *
from java.awt import *
class JTextFieldX(JTextField):
def __init__(self, *args):
# Thanks, Jack!!
JTextField.__init__(
self,
focusGained=self.onGotFocus,
focusLost=self.onLostFocus,
*args)
def onGotFocus (self, event):
print "onGotFocus "
self.selectionStart = 0
self.selectionEnd = len(self.text)
def onLostFocus (self, event):
print "onLostFocus ", self.name
class Test(JFrame):
def __init__(self):
JFrame.__init__(self,
'JDesktopPane and JInternalFrame Demo',
size=(600, 300),
defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
self.desktop = JDesktopPane()
self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)
frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
panel = JPanel()
self.label = JLabel('Hello from Jython')
panel.add(self.label)
self.textfield1 = JTextFieldX('Type something here', 15)
panel.add(self.textfield1)
self.textfield2 = JTextFieldX('and click Copy', 15)
panel.add(self.textfield2)
panel.add(copyButton)
frame.add(panel)
frame.pack()
self.desktop.add(frame)
# ENTER=SPACE remapping for buttons (works ok, but only for buttons)
# inputMap = UIManager.getDefaults().get("Button.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed SPACE"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released SPACE"));
# # pressedAction = self.noAction
# inputMap.put (KeyStroke.getKeyStroke("pressed ENTER"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released ENTER"), releasedAction)
# # Attemp to remap ENTER=TAB for TextFields (didn't work, no errors)
# inputMap = UIManager.getDefaults().get("TextField.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed TAB"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released TAB"));
# inputMap.put (KeyStroke.getKeyStroke("pressed W"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released W"), releasedAction)
# # Attemp to remap ENTER=TAB for all controls (didn't work, no errors)
# spaceMap = self.textfield1.getInputMap().get(KeyStroke.getKeyStroke(event.KeyEvent.VK_TAB, 0, True));
# self.textfield1.getInputMap().put(KeyStroke.getKeyStroke(event.KeyEvent.VK_ENTER, 0, True),spaceMap);
frame.setSelected(1)
frame.moveToFront()
def noAction (self, event):
print "noAction"
pass
if __name__ == '__main__':
test = Test()
test.setLocation(100, 100)
test.show()
</code></pre>
| 3 | 2009-07-31T17:07:38Z | 1,214,292 | <p>I made a new post for readability.</p>
<pre><code>self.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey)
#create textfield2...must be created before can be referenced below.
self.textfield1.setNextFocusableComponent(self.textfield2)
</code></pre>
<p>then in your event handler:</p>
<pre><code>def myOnKey(self,event):
print str(event) # see all other info you can get.
key_code = event.keyCode
if key_code == 10:
print "you pressed enter"
# simulate the "tab" just focus next textbox...
gotFocus = event.getComponent()
nextToFocus = gotFocus.nextFocusableComponent
nextToFocus.requestFocus()
</code></pre>
<p>Should do it.</p>
| 1 | 2009-07-31T19:05:38Z | [
"python",
"swing",
"jython"
] |
Remap keyboard navigation with Jython / Swing | 1,213,730 | <p>I'm trying to remap several navigation keys:</p>
<ul>
<li>ENTER: to work like standard TAB behavior (focus to next control)</li>
<li>SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control)</li>
<li>UP / DOWN arrows: previous /next control</li>
<li>etc</li>
</ul>
<p>I tried with a couple of options but without luck:</p>
<pre><code>from javax.swing import *
from java.awt import *
class JTextFieldX(JTextField):
def __init__(self, *args):
# Thanks, Jack!!
JTextField.__init__(
self,
focusGained=self.onGotFocus,
focusLost=self.onLostFocus,
*args)
def onGotFocus (self, event):
print "onGotFocus "
self.selectionStart = 0
self.selectionEnd = len(self.text)
def onLostFocus (self, event):
print "onLostFocus ", self.name
class Test(JFrame):
def __init__(self):
JFrame.__init__(self,
'JDesktopPane and JInternalFrame Demo',
size=(600, 300),
defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
self.desktop = JDesktopPane()
self.contentPane.add(JScrollPane(self.desktop)) # This is the same as self.getContentPane().add(...)
frame = JInternalFrame("Frame", 1, 1, 1, 1, size=(400, 400), visible=1)
panel = JPanel()
self.label = JLabel('Hello from Jython')
panel.add(self.label)
self.textfield1 = JTextFieldX('Type something here', 15)
panel.add(self.textfield1)
self.textfield2 = JTextFieldX('and click Copy', 15)
panel.add(self.textfield2)
panel.add(copyButton)
frame.add(panel)
frame.pack()
self.desktop.add(frame)
# ENTER=SPACE remapping for buttons (works ok, but only for buttons)
# inputMap = UIManager.getDefaults().get("Button.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed SPACE"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released SPACE"));
# # pressedAction = self.noAction
# inputMap.put (KeyStroke.getKeyStroke("pressed ENTER"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released ENTER"), releasedAction)
# # Attemp to remap ENTER=TAB for TextFields (didn't work, no errors)
# inputMap = UIManager.getDefaults().get("TextField.focusInputMap")
# pressedAction = inputMap.get(KeyStroke.getKeyStroke("pressed TAB"));
# releasedAction = inputMap.get(KeyStroke.getKeyStroke("released TAB"));
# inputMap.put (KeyStroke.getKeyStroke("pressed W"), pressedAction)
# inputMap.put (KeyStroke.getKeyStroke("released W"), releasedAction)
# # Attemp to remap ENTER=TAB for all controls (didn't work, no errors)
# spaceMap = self.textfield1.getInputMap().get(KeyStroke.getKeyStroke(event.KeyEvent.VK_TAB, 0, True));
# self.textfield1.getInputMap().put(KeyStroke.getKeyStroke(event.KeyEvent.VK_ENTER, 0, True),spaceMap);
frame.setSelected(1)
frame.moveToFront()
def noAction (self, event):
print "noAction"
pass
if __name__ == '__main__':
test = Test()
test.setLocation(100, 100)
test.show()
</code></pre>
| 3 | 2009-07-31T17:07:38Z | 1,216,973 | <p>Finally used part of Jack's answer (the keyPressed event) but without manually setting setNextFocusableComponent:</p>
<pre><code>keyFocusMgr = KeyboardFocusManager.getCurrentKeyboardFocusManager()
keyFocusMgr.focusNextComponent()
</code></pre>
| 1 | 2009-08-01T16:39:01Z | [
"python",
"swing",
"jython"
] |
Filter and sort music info on Google App Engine | 1,213,959 | <p>I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another.</p>
<p>Let's assume the core model is an Album that contains several properties, including:</p>
<ul>
<li>Title</li>
<li>Artist</li>
<li>Label</li>
<li>Publication Year</li>
<li>Genre</li>
<li>Length</li>
<li>List of track names</li>
<li>List of moods</li>
<li>Datetime of insertion into database</li>
</ul>
<p>Let's also assume that I would like to filter the entire collection using those properties, and then sorting the results by one of:</p>
<ul>
<li>Publication year</li>
<li>Length of album</li>
<li>Artist name</li>
<li>When the info was added into the database</li>
</ul>
<p>I don't know how to do this without running into the exploding index conundrum. Specifically, I'd love to do something like:</p>
<pre><code>Albums.all().filter('publication_year <', 1980).order('artist_name')
</code></pre>
<p>I know that's not possible, but what's the workaround?</p>
<p>This seems like a fairly general type of application. The music albums could be restaurants, bottles of wine, or hotels. I have a collection of items with descriptive properties that I'd like to filter and sort.</p>
<p>Is there a best practice data model design that I'm overlooking? Any advice?</p>
| 1 | 2009-07-31T17:55:20Z | 1,214,106 | <p>As you say, you can't have an inequality condition on one field and an order by another (or inequalities on two fields, etc, etc). The workaround is simply to use the "best" inequality condition to get data in memory (where "best" means the one that's expected to yield the least data) and then further refine it and order it by Python code in your application.</p>
<p>Python's list comprehensions (and other forms of loops &c), list's <code>sort</code> method and the <code>sorted</code> built-in function, the <code>itertools</code> module in the standard library, and so on, all help a lot to make these kinds of tasks quite simple to perform in Python itself.</p>
| 0 | 2009-07-31T18:28:35Z | [
"python",
"google-app-engine",
"django-models",
"model"
] |
Filter and sort music info on Google App Engine | 1,213,959 | <p>I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another.</p>
<p>Let's assume the core model is an Album that contains several properties, including:</p>
<ul>
<li>Title</li>
<li>Artist</li>
<li>Label</li>
<li>Publication Year</li>
<li>Genre</li>
<li>Length</li>
<li>List of track names</li>
<li>List of moods</li>
<li>Datetime of insertion into database</li>
</ul>
<p>Let's also assume that I would like to filter the entire collection using those properties, and then sorting the results by one of:</p>
<ul>
<li>Publication year</li>
<li>Length of album</li>
<li>Artist name</li>
<li>When the info was added into the database</li>
</ul>
<p>I don't know how to do this without running into the exploding index conundrum. Specifically, I'd love to do something like:</p>
<pre><code>Albums.all().filter('publication_year <', 1980).order('artist_name')
</code></pre>
<p>I know that's not possible, but what's the workaround?</p>
<p>This seems like a fairly general type of application. The music albums could be restaurants, bottles of wine, or hotels. I have a collection of items with descriptive properties that I'd like to filter and sort.</p>
<p>Is there a best practice data model design that I'm overlooking? Any advice?</p>
| 1 | 2009-07-31T17:55:20Z | 1,216,332 | <p>There's a couple of options here: You can filter as best as possible, then sort the results in memory, as Alex suggests, or you can rework your data structures for equality filters instead of inequality filters.</p>
<p>For example, assuming you only want to filter by decade, you can add a field encoding the decade in which the song was recorded. To find everything before or after a decade, do an IN query for the decades you want to span. This will require one underlying query per decade included, but if the number of records is large, this can still be cheaper than fetching all the results and sorting them in memory.</p>
| 1 | 2009-08-01T10:27:56Z | [
"python",
"google-app-engine",
"django-models",
"model"
] |
Filter and sort music info on Google App Engine | 1,213,959 | <p>I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another.</p>
<p>Let's assume the core model is an Album that contains several properties, including:</p>
<ul>
<li>Title</li>
<li>Artist</li>
<li>Label</li>
<li>Publication Year</li>
<li>Genre</li>
<li>Length</li>
<li>List of track names</li>
<li>List of moods</li>
<li>Datetime of insertion into database</li>
</ul>
<p>Let's also assume that I would like to filter the entire collection using those properties, and then sorting the results by one of:</p>
<ul>
<li>Publication year</li>
<li>Length of album</li>
<li>Artist name</li>
<li>When the info was added into the database</li>
</ul>
<p>I don't know how to do this without running into the exploding index conundrum. Specifically, I'd love to do something like:</p>
<pre><code>Albums.all().filter('publication_year <', 1980).order('artist_name')
</code></pre>
<p>I know that's not possible, but what's the workaround?</p>
<p>This seems like a fairly general type of application. The music albums could be restaurants, bottles of wine, or hotels. I have a collection of items with descriptive properties that I'd like to filter and sort.</p>
<p>Is there a best practice data model design that I'm overlooking? Any advice?</p>
| 1 | 2009-07-31T17:55:20Z | 1,220,528 | <p>Since storage is cheap, you could create your own ListProperty based indexfiles with key_names that reflect the sort criteria. </p>
<pre><code>class album_pubyear_List(db.Model):
words = db.StringListProperty()
class album_length_List(db.Model):
words = db.StringListProperty()
class album_artist_List(db.Model):
words = db.StringListProperty()
class Album(db.Model):
blah...
def save(self):
super(Album, self).save()
# you could do this at save time or batch it and do
# it with a cronjob or taskqueue
words = []
for field in ["title", "artist", "label", "genre", ...]:
words.append("%s:%s" %(field, getattr(self, field)))
word_records = []
now = repr(time.time())
word_records.append(album_pubyear_List(parent=self, key_name="%s_%s" %(self.pubyear, now)), words=words)
word_records.append(album_length_List(parent=self, key_name="%s_%s" %(self.album_length, now)), words=words)
word_records.append(album_artist_List(parent=self, key_name="%s_%s" %(self.artist_name, now)), words=words)
db.put(word_records)
</code></pre>
<p>Now when it's time to search you create an appropriate WHERE clause and call the appropriate model</p>
<pre><code>where = "WHERE words = " + "%s:%s" %(field-a, value-a) + " AND " + "%s:%s" %(field-b, value-b) etc.
aModel = "album_pubyear_List" # or anyone of the other key_name sorted wordlist models
indexes = db.GqlQuery("""SELECT __key__ from %s %s""" %(aModel, where))
keys = [k.parent() for k in indexes[offset:numresults+1]] # +1 for pagination
object_list = db.get(keys) # returns a sorted by key_name list of Albums
</code></pre>
| 1 | 2009-08-03T03:06:11Z | [
"python",
"google-app-engine",
"django-models",
"model"
] |
Remove ppc from compilation flags in python setup scripts | 1,214,133 | <p>I'm trying to install PIL on an Intel Mac OS X Leopard machine. Unfortunately, "setup.py build" thinks it should be compiling for ppc.</p>
<pre><code>gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -DHAVE_LIBJPEG -DHAVE_LIBZ -I/System/Library/Frameworks/Tcl.framework/Headers -I/System/Library/Frameworks/Tk.framework/Headers -I/opt/local/include/freetype2 -IlibImaging -I/sw/include -I/opt/local/include -I/Users/adam/Development/pinax-env/include -I/usr/local/include -I/usr/include -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c libImaging/GifEncode.c -o build/temp.macosx-10.3-i386-2.5/libImaging/GifEncode.o
</code></pre>
<p>This fails because I don't have the ppc arch files available on my machine (nor do I want to install them). How can I tell setup.py to only do i386?</p>
<p>I've looked in /Library/Frameworks/Python.framework for a config file to no avail.</p>
| 7 | 2009-07-31T18:34:03Z | 1,214,163 | <p>The easiest solution (for a single or a few C files) is to copy the compiler line, edit it, and invoke it manually, then run setup.py again - it should notice that this step was already done.</p>
<p>To make setup.py not use these options anymore, you need to change the Makefile in Python's config directory, and remove the options.</p>
| 2 | 2009-07-31T18:40:10Z | [
"python",
"python-imaging-library"
] |
Remove ppc from compilation flags in python setup scripts | 1,214,133 | <p>I'm trying to install PIL on an Intel Mac OS X Leopard machine. Unfortunately, "setup.py build" thinks it should be compiling for ppc.</p>
<pre><code>gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -DHAVE_LIBJPEG -DHAVE_LIBZ -I/System/Library/Frameworks/Tcl.framework/Headers -I/System/Library/Frameworks/Tk.framework/Headers -I/opt/local/include/freetype2 -IlibImaging -I/sw/include -I/opt/local/include -I/Users/adam/Development/pinax-env/include -I/usr/local/include -I/usr/include -I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 -c libImaging/GifEncode.c -o build/temp.macosx-10.3-i386-2.5/libImaging/GifEncode.o
</code></pre>
<p>This fails because I don't have the ppc arch files available on my machine (nor do I want to install them). How can I tell setup.py to only do i386?</p>
<p>I've looked in /Library/Frameworks/Python.framework for a config file to no avail.</p>
| 7 | 2009-07-31T18:34:03Z | 5,808,548 | <p>The solution that worked for me was:</p>
<p>ARCHFLAGS="-arch i386 -arch x86_64" python setup.py build</p>
<p>Just pass the values for the flag right in the command line.</p>
| 17 | 2011-04-27T18:07:07Z | [
"python",
"python-imaging-library"
] |
Django transaction.commit_on_success not rolling back transaction | 1,214,143 | <p>I'm trying to use Django transactions on MySQL with <a href="http://docs.djangoproject.com/en/dev/topics/db/transactions/#django-db-transaction-commit-on-success" rel="nofollow">the <code>commit_on_success</code> decorator</a>. According to the documentation, "If the function raises an exception, though, Django will roll back the transaction." However, this doesn't seem to work for me:</p>
<pre><code>>>> @transaction.commit_on_success
... def fails():
... Site.objects.create(name="New Site", ip_address="127.0.0.1")
... raise ValueError("oh noes!")
...
>>> Site.objects.count()
2
>>> fails()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/site-packages/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "<stdin>", line 4, in fails
ValueError: oh noes!
>>> Site.objects.count()
3
>>>
</code></pre>
<p>I'm pretty sure that MySQL supports transactions; do I need to use a different table type or something?</p>
| 2 | 2009-07-31T18:35:29Z | 1,214,224 | <p>Apparently MySQL doesn't support transactions with MyISAM tables, which is the default type of tables. InnoDB tables do support transactions, so I'll recreate the tables and then see whether the transactions work then.</p>
| 3 | 2009-07-31T18:53:54Z | [
"python",
"mysql",
"django",
"transactions"
] |
Django transaction.commit_on_success not rolling back transaction | 1,214,143 | <p>I'm trying to use Django transactions on MySQL with <a href="http://docs.djangoproject.com/en/dev/topics/db/transactions/#django-db-transaction-commit-on-success" rel="nofollow">the <code>commit_on_success</code> decorator</a>. According to the documentation, "If the function raises an exception, though, Django will roll back the transaction." However, this doesn't seem to work for me:</p>
<pre><code>>>> @transaction.commit_on_success
... def fails():
... Site.objects.create(name="New Site", ip_address="127.0.0.1")
... raise ValueError("oh noes!")
...
>>> Site.objects.count()
2
>>> fails()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/site-packages/django/db/transaction.py", line 240, in _commit_on_success
res = func(*args, **kw)
File "<stdin>", line 4, in fails
ValueError: oh noes!
>>> Site.objects.count()
3
>>>
</code></pre>
<p>I'm pretty sure that MySQL supports transactions; do I need to use a different table type or something?</p>
| 2 | 2009-07-31T18:35:29Z | 1,214,406 | <p>From <a href="http://docs.djangoproject.com/en/dev/ref/databases/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/databases/</a>:</p>
<p>"The default engine is MyISAM [1]. The main drawback of MyISAM is that it doesn't currently support transactions or foreign keys. On the plus side, it's currently the only engine that supports full-text indexing and searching.</p>
<p>"The InnoDB engine is fully transactional and supports foreign key references."</p>
| 8 | 2009-07-31T19:26:34Z | [
"python",
"mysql",
"django",
"transactions"
] |
Multiple periodic timers | 1,214,164 | <p>Is there any standard python module for creating multiple periodic timers.
I want to design a system which supports creating multiple periodic timers of different periodicity running in just one thread. The system should be able to cancel a specific timer at any point of time.</p>
<p>Thanks in advance for any input!</p>
| 3 | 2009-07-31T18:40:20Z | 1,214,352 | <p>If you have to stick with 1 thread - maintain a list of tasks, along with the frequency they should execute and what function should be called:</p>
<pre><code>import time
def example1():
print 'Example'
class Task(object):
def __init__(self, func, delay, args=()):
self.args = args
self.function = func
self.delay = delay
self.next_run = time.time() + self.delay
def shouldRun(self):
return time.time() >= self.next_run
def run(self):
self.function(*(self.args))
self.next_run += self.delay
# self.next_run = time.time() + self.delay
tasks = [Task(example1, 1)] # Run example1 every second
while True:
for t in tasks:
if t.shouldRun():
t.run()
time.sleep(0.01)
</code></pre>
<p>Or you may want to have a look at stackless - which is ideally suited to what you want to do, and makes it possible to do much finer grained task-switching than the above scheduler.</p>
| 1 | 2009-07-31T19:17:47Z | [
"python"
] |
Multiple periodic timers | 1,214,164 | <p>Is there any standard python module for creating multiple periodic timers.
I want to design a system which supports creating multiple periodic timers of different periodicity running in just one thread. The system should be able to cancel a specific timer at any point of time.</p>
<p>Thanks in advance for any input!</p>
| 3 | 2009-07-31T18:40:20Z | 1,215,690 | <p>Check out the <a href="http://docs.python.org/search.html?q=sched">sched</a> module in Python's standard library -- per se, it doesn't directly support periodic timers, only one-off "events", but the standard trick to turn a one-off event into a periodic timer applies (the callable handling the one-off event just reschedules itself for the next repetition, before moving on to doing real work).</p>
<p>It may be handy to define a "scheduled periodic timer" class to encapsulate the key ideas:</p>
<pre><code>class spt(object):
def __init__(self, scheduler, period):
self._sched = scheduler
self._period = period
self._event = None
def start(self):
self._event = self._sched.enter(0, 0, self._action, ())
def _action(self):
self._event - self._sched.enter(self._period, 0, self._action, ())
self.act()
def act(self):
print "hi there"
def cancel(self):
self._sched.cancel(self._event)
</code></pre>
<p>To associate a meaningful action to a scheduled periodic timer, subclass spt and override the <code>act</code> method (a Template Method design pattern). You can of course choose more flexible architectures, such as having <code>__init__</code> take a callable and arguments as well as a scheduler (an instance of <code>self.scheduler</code>) and a period (as a float in seconds, if you instantiate the scheduler in the standard way with time.time and time.sleep); optionally you might also want to set a priority there (maybe with a <em>default</em> value of 0) rather than using the constant 0 priority I'm using above.</p>
| 6 | 2009-08-01T02:38:48Z | [
"python"
] |
Basic Python dictionary question | 1,214,422 | <p>I have a dictionary with one key and two values and I want to set each value to a separate variable.</p>
<p>d= {'key' : ('value1, value2'),
'key2' : ('value3, value4'),
'key3' : ('value5, value6')}</p>
<p>I tried d[key][0] in the hope it would return "value1" but instead it return "v"</p>
<p>Any suggestions?</p>
| 2 | 2009-07-31T19:28:50Z | 1,214,430 | <p>Try something like this:</p>
<pre><code>d = {'key' : 'value1, value2'}
list = d['key'].split(', ')
</code></pre>
<p><code>list[0]</code> will be "value1" and <code>list[1]</code> will be "value2".</p>
| 4 | 2009-07-31T19:30:36Z | [
"python",
"dictionary"
] |
Basic Python dictionary question | 1,214,422 | <p>I have a dictionary with one key and two values and I want to set each value to a separate variable.</p>
<p>d= {'key' : ('value1, value2'),
'key2' : ('value3, value4'),
'key3' : ('value5, value6')}</p>
<p>I tried d[key][0] in the hope it would return "value1" but instead it return "v"</p>
<p>Any suggestions?</p>
| 2 | 2009-07-31T19:28:50Z | 1,214,443 | <p>A better solution is to store your value as a two-tuple:</p>
<pre><code>d = {'key' : ('value1', 'value2')}
</code></pre>
<p>That way you don't have to split every time you want to access the values.</p>
| 16 | 2009-07-31T19:32:22Z | [
"python",
"dictionary"
] |
Basic Python dictionary question | 1,214,422 | <p>I have a dictionary with one key and two values and I want to set each value to a separate variable.</p>
<p>d= {'key' : ('value1, value2'),
'key2' : ('value3, value4'),
'key3' : ('value5, value6')}</p>
<p>I tried d[key][0] in the hope it would return "value1" but instead it return "v"</p>
<p>Any suggestions?</p>
| 2 | 2009-07-31T19:28:50Z | 1,214,455 | <p>I would suggest storing lists in your dictionary. It'd make it much easier to reference. For instance,</p>
<pre><code>from collections import defaultdict
my_dict = defaultdict(list)
my_dict["key"].append("value 1")
my_dict["key"].append("value 2")
print my_dict["key"][1]
</code></pre>
| 1 | 2009-07-31T19:33:51Z | [
"python",
"dictionary"
] |
Basic Python dictionary question | 1,214,422 | <p>I have a dictionary with one key and two values and I want to set each value to a separate variable.</p>
<p>d= {'key' : ('value1, value2'),
'key2' : ('value3, value4'),
'key3' : ('value5, value6')}</p>
<p>I tried d[key][0] in the hope it would return "value1" but instead it return "v"</p>
<p>Any suggestions?</p>
| 2 | 2009-07-31T19:28:50Z | 1,214,461 | <p>To obtain the two values and assign them to value1 and value2:</p>
<pre><code>for v in d.itervalues():
value1, value2 = v.split(', ')
</code></pre>
<p>As said by zenazn, I wouldn't consider this to be a sensible data structure, using a tuple or a class to store the multiple values would be better.</p>
| 1 | 2009-07-31T19:35:28Z | [
"python",
"dictionary"
] |
Basic Python dictionary question | 1,214,422 | <p>I have a dictionary with one key and two values and I want to set each value to a separate variable.</p>
<p>d= {'key' : ('value1, value2'),
'key2' : ('value3, value4'),
'key3' : ('value5, value6')}</p>
<p>I tried d[key][0] in the hope it would return "value1" but instead it return "v"</p>
<p>Any suggestions?</p>
| 2 | 2009-07-31T19:28:50Z | 1,214,606 | <p>The way you're storing your values, you'll need something like:</p>
<pre><code>value1, value2 = d['key'].split(', ')
print value1, value2
</code></pre>
<p>or to iterate over all values:</p>
<pre><code>for key in d:
v1, v2 = d[k].split(', ')
print v1, v2
</code></pre>
<p>But, if you can, you should probably follow zenazn's suggestion of storing your values as tuples, and avoid the need to split every time.</p>
| 0 | 2009-07-31T20:08:19Z | [
"python",
"dictionary"
] |
Allowing the " - " character in usernames in the Django Admin interface | 1,214,453 | <p>In our webapp we needed to allow dashes "-" in our usernames.
I've enabled that for the consumer signup process just fine with this regex
r'^[\w-]+$' </p>
<p>How can I tell the admin app so that I can edit usernames in auth > users to allows the "-" character in usernames? Currently I am unable to edit any usernames with dashes in them as it will return a validation error on the username.</p>
<p>I'd like to try and avoid patching django directly if possible.
I'm fairly new to programming but is this what I would use "subclassing" for?</p>
| 7 | 2009-07-31T19:33:23Z | 1,214,660 | <p>This should be as simple as overriding the behavior of the User ModelAdmin class. In one of your apps, in <code>admin.py</code> include the following code.</p>
<pre><code>from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class MyUserCreationForm(UserCreationForm):
username = forms.RegexField(
label='Username',
max_length=30,
regex=r'^[\w-]+$',
help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
error_message = 'This value must contain only letters, numbers, hyphens and underscores.')
class MyUserChangeForm(UserChangeForm):
username = forms.RegexField(
label='Username',
max_length=30,
regex=r'^[\w-]+$',
help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
error_message = 'This value must contain only letters, numbers, hyphens and underscores.')
class MyUserAdmin(UserAdmin):
form = MyUserChangeForm
add_form = MyUserCreationForm
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)
</code></pre>
<p>Here's a little explanation. </p>
<p>The first class definition (MyUserCreationForm) is a subclass (yes your terminology is correct) of the UserCreationForm. This is the form that appears when you click "Add User" in the Django Admin site. All we are doing here is redefining the <code>username</code> field to use our improved, hyphen-accepting regex, and changing the <code>helptext</code> to reflect this.</p>
<p>The second class definition does the same, except for the UserChangeForm.</p>
<p>The final class definition is a subclass of UserAdmin, which is the ModelAdmin that the User model uses by default. Here we state that we want to use our new custom forms in the ModelAdmin.</p>
<p>Note that for each of these subclasses, we only change what we have to. The rest of the class will be inherited from its parent (UserCreationForm, UserChangeForm and UserAdmin respectively).</p>
<p>Finally, we perform the important step of registering the User model with the admin site. To do that we unregister the default UserAdmin, and then register with our improved MyUserAdmin class.</p>
<p>You'll find that the Django admin site is very easy to customize using these techniques, especially considering the admin site is just a regular Django app.</p>
| 17 | 2009-07-31T20:18:53Z | [
"python",
"django",
"django-admin"
] |
How to get environment from a subprocess in Python | 1,214,496 | <p>I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?</p>
<p>This is what the program look like:</p>
<pre><code>import subprocess
subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work
</code></pre>
<p>but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).</p>
<p>N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)</p>
| 12 | 2009-07-31T19:44:22Z | 1,214,515 | <p>As you say, processes don't share the environment - so what you literally ask is not possible, not only in Python, but with any programming language.</p>
<p>What you <em>can</em> do is to put the environment variables in a file, or in a pipe, and either</p>
<ul>
<li>have the parent process read them, and pass them to proc2 before proc2 is created, or</li>
<li>have proc2 read them, and set them locally</li>
</ul>
<p>The latter would require cooperation from proc2; the former requires that the variables become known before proc2 is started.</p>
| 2 | 2009-07-31T19:48:31Z | [
"python",
"environment-variables",
"subprocess",
"popen"
] |
How to get environment from a subprocess in Python | 1,214,496 | <p>I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?</p>
<p>This is what the program look like:</p>
<pre><code>import subprocess
subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work
</code></pre>
<p>but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).</p>
<p>N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)</p>
| 12 | 2009-07-31T19:44:22Z | 1,214,517 | <p>Environment is inherited from the parent process. Set the environment you need in the main script, not a subprocess (child).</p>
| 1 | 2009-07-31T19:49:06Z | [
"python",
"environment-variables",
"subprocess",
"popen"
] |
How to get environment from a subprocess in Python | 1,214,496 | <p>I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?</p>
<p>This is what the program look like:</p>
<pre><code>import subprocess
subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work
</code></pre>
<p>but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).</p>
<p>N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)</p>
| 12 | 2009-07-31T19:44:22Z | 1,214,518 | <p>Two things spring to mind: (1) make the processes share the same environment, by combining them somehow into the same process, or (2) have the first process produce output that contains the relevant environment variables, that way Python can read it and construct the environment for the second process. I think (though I'm not 100% sure) that there isn't any way to get the environment from a subprocess as you're hoping to do.</p>
| 0 | 2009-07-31T19:49:12Z | [
"python",
"environment-variables",
"subprocess",
"popen"
] |
How to get environment from a subprocess in Python | 1,214,496 | <p>I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?</p>
<p>This is what the program look like:</p>
<pre><code>import subprocess
subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work
</code></pre>
<p>but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).</p>
<p>N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)</p>
| 12 | 2009-07-31T19:44:22Z | 1,214,802 | <p><a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">The Python standard module multiprocessing</a> have a Queues system that allow you to pass pickle-able object to be passed through processes. Also processes can exchange messages (a pickled object) using os.pipe. Remember that resources (e.g : database connection) and handle (e.g : file handles) can't be pickled.</p>
<p>You may find this link interesting :
<a href="http://www.doughellmann.com/PyMOTW/multiprocessing/communication.html" rel="nofollow">Communication between processes with multiprocessing</a></p>
<p>Also the PyMOTw about multiprocessing worth mentioning :
<a href="http://www.doughellmann.com/PyMOTW/multiprocessing/basics.html" rel="nofollow">multiprocessing Basics</a></p>
<p>sorry for my spelling</p>
| 0 | 2009-07-31T20:44:51Z | [
"python",
"environment-variables",
"subprocess",
"popen"
] |
How to get environment from a subprocess in Python | 1,214,496 | <p>I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?</p>
<p>This is what the program look like:</p>
<pre><code>import subprocess
subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work
</code></pre>
<p>but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).</p>
<p>N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)</p>
| 12 | 2009-07-31T19:44:22Z | 1,215,189 | <p>Since you're apparently in Windows, you need a Windows answer.</p>
<p>Create a wrapper batch file, eg. "run_program.bat", and run both programs:</p>
<pre><code>@echo off
call proc1.bat
proc2
</code></pre>
<p>The script will run and set its environment variables. Both scripts run in the same interpreter (cmd.exe instance), so the variables prog1.bat sets <em>will</em> be set when prog2 is executed.</p>
<p>Not terribly pretty, but it'll work.</p>
<p>(Unix people, you can do the same thing in a bash script: "source file.sh".)</p>
| 1 | 2009-07-31T22:31:09Z | [
"python",
"environment-variables",
"subprocess",
"popen"
] |
How to get environment from a subprocess in Python | 1,214,496 | <p>I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second?</p>
<p>This is what the program look like:</p>
<pre><code>import subprocess
subprocess.call(['proc1']) # this set env. variables for proc2
subprocess.call(['proc2']) # this must have env. variables set by proc1 to work
</code></pre>
<p>but the to process don't share the same environment. Note that these programs aren't mine (the first is big and ugly .bat file and the second a proprietary soft) so I can't modify them (ok, I can extract all that I need from the .bat but it's very combersome).</p>
<p>N.B.: I am using Windows, but I prefer a cross-platform solution (but my problem wouldn't happen on a Unix-like ...)</p>
| 12 | 2009-07-31T19:44:22Z | 2,214,292 | <p>Here's an example of how you can extract environment variables from a batch or cmd file without creating a wrapper script. Enjoy.</p>
<pre><code>from __future__ import print_function
import sys
import subprocess
import itertools
def validate_pair(ob):
try:
if not (len(ob) == 2):
print("Unexpected result:", ob, file=sys.stderr)
raise ValueError
except:
return False
return True
def consume(iter):
try:
while True: next(iter)
except StopIteration:
pass
def get_environment_from_batch_command(env_cmd, initial=None):
"""
Take a command (either a single command or list of arguments)
and return the environment created after running that command.
Note that if the command must be a batch file or .cmd file, or the
changes to the environment will not be captured.
If initial is supplied, it is used as the initial environment passed
to the child process.
"""
if not isinstance(env_cmd, (list, tuple)):
env_cmd = [env_cmd]
# construct the command that will alter the environment
env_cmd = subprocess.list2cmdline(env_cmd)
# create a tag so we can tell in the output when the proc is done
tag = 'Done running command'
# construct a cmd.exe command to do accomplish this
cmd = 'cmd.exe /s /c "{env_cmd} && echo "{tag}" && set"'.format(**vars())
# launch the process
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, env=initial)
# parse the output sent to stdout
lines = proc.stdout
# consume whatever output occurs until the tag is reached
consume(itertools.takewhile(lambda l: tag not in l, lines))
# define a way to handle each KEY=VALUE line
handle_line = lambda l: l.rstrip().split('=',1)
# parse key/values into pairs
pairs = map(handle_line, lines)
# make sure the pairs are valid
valid_pairs = filter(validate_pair, pairs)
# construct a dictionary of the pairs
result = dict(valid_pairs)
# let the process finish
proc.communicate()
return result
</code></pre>
<p>So to answer your question, you would create a .py file that does the following:</p>
<pre><code>env = get_environment_from_batch_command('proc1')
subprocess.Popen('proc2', env=env)
</code></pre>
| 21 | 2010-02-06T18:53:31Z | [
"python",
"environment-variables",
"subprocess",
"popen"
] |
XSLT Transform of Unicode source | 1,214,733 | <p>In my application I am using the <a href="http://4suite.org/docs/CoreManual.xml#xslt%5Fengine" rel="nofollow">4Suite.org XSLT library</a> to perform transformations of source XML. The syntax is like this:</p>
<pre><code>from Ft.Xml.Xslt import Transform
transformed_xml = Transform(raw_xml, stylesheet)
</code></pre>
<p>where <code>raw_xml</code> and <code>stylesheet</code> have been defined elsewhere in my application. <code>raw_xml</code> will be the xml resulting from reading a filehandle opened with the codecs module so the <code>raw_xml</code> will be unicode.</p>
<p>The problem is that the Transform() function requires the value of the source xml (<code>raw_xml</code> in my example) to be ascii. It says so in the pydoc and my own program fails with an error along those lines if I try to transform unicode.</p>
<p>Is there a different approach or is there another python library which can perform an XSLT transformation against a unicode source? Or, am I misunderstanding something about XSLT transformations?</p>
| 0 | 2009-07-31T20:33:18Z | 1,214,763 | <p>You are likely better off using the more modern and actively maintained <a href="http://codespeak.net/lxml/xpathxslt.html#xslt" rel="nofollow">lxml</a>.</p>
| 2 | 2009-07-31T20:39:30Z | [
"python",
"xslt",
"unicode"
] |
XSLT Transform of Unicode source | 1,214,733 | <p>In my application I am using the <a href="http://4suite.org/docs/CoreManual.xml#xslt%5Fengine" rel="nofollow">4Suite.org XSLT library</a> to perform transformations of source XML. The syntax is like this:</p>
<pre><code>from Ft.Xml.Xslt import Transform
transformed_xml = Transform(raw_xml, stylesheet)
</code></pre>
<p>where <code>raw_xml</code> and <code>stylesheet</code> have been defined elsewhere in my application. <code>raw_xml</code> will be the xml resulting from reading a filehandle opened with the codecs module so the <code>raw_xml</code> will be unicode.</p>
<p>The problem is that the Transform() function requires the value of the source xml (<code>raw_xml</code> in my example) to be ascii. It says so in the pydoc and my own program fails with an error along those lines if I try to transform unicode.</p>
<p>Is there a different approach or is there another python library which can perform an XSLT transformation against a unicode source? Or, am I misunderstanding something about XSLT transformations?</p>
| 0 | 2009-07-31T20:33:18Z | 1,215,184 | <p>I'm not sure <code>Transform</code> actually needs <em>ascii</em> -- looks to me like it should support any encoded Python str. What happens if you call <code>Transform(raw_xml.encode('utf8'), stylesheet)</code> (and then decode the resulting utf8-encoded string back to Unicode when you're done processing it of course, if you need Unicode) -- doesn't that work?</p>
| 2 | 2009-07-31T22:29:37Z | [
"python",
"xslt",
"unicode"
] |
Counting and filtering objects in a database with Django | 1,214,740 | <p>I'm struggling a little to work out how to follow the relation and count fields of objects.</p>
<p>In my Django site, I have a profile model:</p>
<pre><code>user = models.ForeignKey(User, unique=True)
name = models.CharField(_('name'), null=True, blank=True)
about = models.TextField(_('about'), null=True, blank=True)
location = models.CharField(_('location'), null=True, blank=True)
website = models.URLField(_('website'), null=True, blank=True)
</code></pre>
<p>My understanding is that this is using the username as the foreign key.</p>
<p>I would like to be able to count and display the number of completed profiles my users have filled out, and ones that have a specific "element / field"? (name)* filled out. I tried:</p>
<pre><code>Profile.objects.all().count()
</code></pre>
<p>That gave me the same number of profiles as users, which I am guessing is because the profile model exists for each user, even if it is blank.</p>
<p>I'm unsure how to count profiles that have one of these fields completed in them, and I am also unsure how to count the number of completed "name" fields that have been completed.</p>
<p>I tried:</p>
<pre><code>Profile.objects.all().name.count()
</code></pre>
<p>Django has some good docs on <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/" rel="nofollow">queryset api</a>, but its currently going a little over my head </p>
<ul>
<li>please excuse my use of incorrect terminology.</li>
</ul>
| 1 | 2009-07-31T20:35:10Z | 1,214,775 | <p>You should be able to get them using:</p>
<pre><code>Profile.objects.filter(name__isnull=False)
</code></pre>
| 1 | 2009-07-31T20:40:55Z | [
"python",
"django",
"django-models"
] |
Filtering dictionaries and creating sub-dictionaries based on keys/values in Python? | 1,214,968 | <p>Ok, I'm stuck, need some help from here on... </p>
<p>If I've got a main dictionary like this:</p>
<pre><code>data = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value4", "key2": "value5", "key1": "value6"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
<p>Now, I need to go through that dictionary already to format some of the data, ie:</p>
<pre><code>for datadict in data:
for key, value in datadict.items():
...filter the data...
</code></pre>
<p>Now, how would I in that same loop somehow (if possible... if not, suggest alternatives please) check for values of certain keys, and if those values match my presets then I would add that whole list to another dictionary, thus effectively creating smaller dictionaries as I go along out of this main dictionary based on certain keys and values?</p>
<p>So, let's say I want to create a sub-dictionary with all the lists in which key1 has value of "value1", which for the above list would give me something like this:</p>
<pre><code>subdata = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
| 5 | 2009-07-31T21:22:52Z | 1,215,024 | <p>The answer is too simple, so I guess we are missing some information. Anyway:</p>
<pre><code>result = []
for datadict in data:
for key, value in datadict.items():
thefiltering()
if datadict.get('matchkey') == 'matchvalue':
result.append(datadict)
</code></pre>
<p>Also, you "main dictionary" is not a dictionary but a list. Just wanted to clear that up.</p>
| 1 | 2009-07-31T21:39:32Z | [
"python",
"list",
"dictionary",
"filter"
] |
Filtering dictionaries and creating sub-dictionaries based on keys/values in Python? | 1,214,968 | <p>Ok, I'm stuck, need some help from here on... </p>
<p>If I've got a main dictionary like this:</p>
<pre><code>data = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value4", "key2": "value5", "key1": "value6"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
<p>Now, I need to go through that dictionary already to format some of the data, ie:</p>
<pre><code>for datadict in data:
for key, value in datadict.items():
...filter the data...
</code></pre>
<p>Now, how would I in that same loop somehow (if possible... if not, suggest alternatives please) check for values of certain keys, and if those values match my presets then I would add that whole list to another dictionary, thus effectively creating smaller dictionaries as I go along out of this main dictionary based on certain keys and values?</p>
<p>So, let's say I want to create a sub-dictionary with all the lists in which key1 has value of "value1", which for the above list would give me something like this:</p>
<pre><code>subdata = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
| 5 | 2009-07-31T21:22:52Z | 1,215,039 | <p>Here is a not so pretty way of doing it. The result is a generator, but if you really want a list you can surround it with a call to <code>list()</code>. Mostly it doesn't matter.</p>
<p>The predicate is a function which decides for each key/value pair if a dictionary in the list is going to cut it. The default one accepts all. If no k/v-pair in the dictionary matches it is rejected.</p>
<pre><code>def filter_data(data, predicate=lambda k, v: True):
for d in data:
for k, v in d.items():
if predicate(k, v):
yield d
test_data = [{"key1":"value1", "key2":"value2"}, {"key1":"blabla"}, {"key1":"value1", "eh":"uh"}]
list(filter_data(test_data, lambda k, v: k == "key1" and v == "value1"))
# [{'key2': 'value2', 'key1': 'value1'}, {'key1': 'value1', 'eh': 'uh'}]
</code></pre>
| 9 | 2009-07-31T21:44:29Z | [
"python",
"list",
"dictionary",
"filter"
] |
Filtering dictionaries and creating sub-dictionaries based on keys/values in Python? | 1,214,968 | <p>Ok, I'm stuck, need some help from here on... </p>
<p>If I've got a main dictionary like this:</p>
<pre><code>data = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value4", "key2": "value5", "key1": "value6"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
<p>Now, I need to go through that dictionary already to format some of the data, ie:</p>
<pre><code>for datadict in data:
for key, value in datadict.items():
...filter the data...
</code></pre>
<p>Now, how would I in that same loop somehow (if possible... if not, suggest alternatives please) check for values of certain keys, and if those values match my presets then I would add that whole list to another dictionary, thus effectively creating smaller dictionaries as I go along out of this main dictionary based on certain keys and values?</p>
<p>So, let's say I want to create a sub-dictionary with all the lists in which key1 has value of "value1", which for the above list would give me something like this:</p>
<pre><code>subdata = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
| 5 | 2009-07-31T21:22:52Z | 1,215,173 | <p>Net of the issues already pointed out in other comments and answers (multiple identical keys can't be in a dict, etc etc), here's how I'd do it:</p>
<pre><code>def select_sublist(list_of_dicts, **kwargs):
return [d for d in list_of_dicts
if all(d.get(k)==kwargs[k] for k in kwargs)]
subdata = select_sublist(data, key1='value1')
</code></pre>
| 3 | 2009-07-31T22:24:15Z | [
"python",
"list",
"dictionary",
"filter"
] |
Filtering dictionaries and creating sub-dictionaries based on keys/values in Python? | 1,214,968 | <p>Ok, I'm stuck, need some help from here on... </p>
<p>If I've got a main dictionary like this:</p>
<pre><code>data = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value4", "key2": "value5", "key1": "value6"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
<p>Now, I need to go through that dictionary already to format some of the data, ie:</p>
<pre><code>for datadict in data:
for key, value in datadict.items():
...filter the data...
</code></pre>
<p>Now, how would I in that same loop somehow (if possible... if not, suggest alternatives please) check for values of certain keys, and if those values match my presets then I would add that whole list to another dictionary, thus effectively creating smaller dictionaries as I go along out of this main dictionary based on certain keys and values?</p>
<p>So, let's say I want to create a sub-dictionary with all the lists in which key1 has value of "value1", which for the above list would give me something like this:</p>
<pre><code>subdata = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
| 5 | 2009-07-31T21:22:52Z | 3,602,315 | <p>Inspired by the answer of Skurmedal, I split this into a recursive scheme to work with a database of nested dictionaries. In this case, a "record" is the subdictionary at the trunk. The predicate defines which records we are after -- those that match some (key,value) pair where these pairs may be deeply nested.</p>
<pre><code>def filter_dict(the_dict, predicate=lambda k, v: True):
for k, v in the_dict.iteritems():
if isinstance(v, dict) and _filter_dict_sub(predicate, v):
yield k, v
def _filter_dict_sub(predicate, the_dict):
for k, v in the_dict.iteritems():
if isinstance(v, dict) and filter_dict_sub(predicate, v):
return True
if predicate(k, v):
return True
return False
</code></pre>
<p>Since this is a generator, you may need to wrap with <code>dict(filter_dict(the_dict))</code> to obtain a filtered dictionary.</p>
| 0 | 2010-08-30T16:33:07Z | [
"python",
"list",
"dictionary",
"filter"
] |
Filtering dictionaries and creating sub-dictionaries based on keys/values in Python? | 1,214,968 | <p>Ok, I'm stuck, need some help from here on... </p>
<p>If I've got a main dictionary like this:</p>
<pre><code>data = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value4", "key2": "value5", "key1": "value6"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
<p>Now, I need to go through that dictionary already to format some of the data, ie:</p>
<pre><code>for datadict in data:
for key, value in datadict.items():
...filter the data...
</code></pre>
<p>Now, how would I in that same loop somehow (if possible... if not, suggest alternatives please) check for values of certain keys, and if those values match my presets then I would add that whole list to another dictionary, thus effectively creating smaller dictionaries as I go along out of this main dictionary based on certain keys and values?</p>
<p>So, let's say I want to create a sub-dictionary with all the lists in which key1 has value of "value1", which for the above list would give me something like this:</p>
<pre><code>subdata = [ {"key1": "value1", "key2": "value2", "key1": "value3"},
{"key1": "value1", "key2": "value8", "key1": "value9"} ]
</code></pre>
| 5 | 2009-07-31T21:22:52Z | 32,983,032 | <p>It's an old question, but for some reason there is no one-liner syntax answer:</p>
<pre><code>{ k: v for k, v in <SOURCE_DICTIONARY>.iteritems() if <CONDITION> }
</code></pre>
<p>For example:</p>
<pre><code>src_dict = { 1: 'a', 2: 'b', 3: 'c', 4: 'd' }
predicate = lambda k, v: k % 2 == 0
filtered_dict = { k: v for k, v in src_dict.iteritems() if predicate(k, v) }
print "Source dictionary:", src_dict
print "Filtered dictionary:", filtered_dict
</code></pre>
<p>Will produce the following output:</p>
<pre><code>Source dictionary: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
Filtered dictionary: {2: 'b', 4: 'd'}
</code></pre>
| 0 | 2015-10-07T02:53:38Z | [
"python",
"list",
"dictionary",
"filter"
] |
oauth google using python | 1,215,033 | <p>i am fairly new to programming for web. and i want to start from scratch here.
i tried to search the net but ended up completely confused.
now what i want to learn is how to authenticate a google account through a python script.
can anyone please provide me with a code fragment or any example.</p>
<p>thanks a lot in advance.</p>
| 11 | 2009-07-31T21:42:37Z | 1,215,073 | <p>try this <a href="http://oauth.googlecode.com/svn/code/python/oauth/example/" rel="nofollow">example</a></p>
| 3 | 2009-07-31T21:56:02Z | [
"python",
"oauth"
] |
oauth google using python | 1,215,033 | <p>i am fairly new to programming for web. and i want to start from scratch here.
i tried to search the net but ended up completely confused.
now what i want to learn is how to authenticate a google account through a python script.
can anyone please provide me with a code fragment or any example.</p>
<p>thanks a lot in advance.</p>
| 11 | 2009-07-31T21:42:37Z | 1,215,078 | <p>See the document on Google Data API docs:</p>
<ul>
<li><a href="http://code.google.com/apis/gdata/articles/python%5Fclient%5Flib.html" rel="nofollow">Getting Started with the Google Data Python Library</a></li>
</ul>
<p>There's a ClientLogin sample under "Hello World".</p>
| 0 | 2009-07-31T21:56:55Z | [
"python",
"oauth"
] |
oauth google using python | 1,215,033 | <p>i am fairly new to programming for web. and i want to start from scratch here.
i tried to search the net but ended up completely confused.
now what i want to learn is how to authenticate a google account through a python script.
can anyone please provide me with a code fragment or any example.</p>
<p>thanks a lot in advance.</p>
| 11 | 2009-07-31T21:42:37Z | 1,215,081 | <p>Good intro:
<a href="http://code.google.com/apis/accounts/docs/OAuth.html" rel="nofollow">http://code.google.com/apis/accounts/docs/OAuth.html</a></p>
<p>Great working, playable example: <a href="http://googlecodesamples.com/oauth%5Fplayground/" rel="nofollow">http://googlecodesamples.com/oauth_playground/</a></p>
| 1 | 2009-07-31T21:57:39Z | [
"python",
"oauth"
] |
oauth google using python | 1,215,033 | <p>i am fairly new to programming for web. and i want to start from scratch here.
i tried to search the net but ended up completely confused.
now what i want to learn is how to authenticate a google account through a python script.
can anyone please provide me with a code fragment or any example.</p>
<p>thanks a lot in advance.</p>
| 11 | 2009-07-31T21:42:37Z | 1,572,565 | <p>Some good links above (the playground is invaluable).</p>
<p>I use a mixture of Leah Culver's oAuth code (the example in b3rx's post) and <a href="http://fireeagle.yahoo.net/developer/documentation/python%5Fwalkthru" rel="nofollow">FireEagle's Python OAuth code</a>. The former, the last time I looked, was lacking scope methods.</p>
<p>Also, make sure you are clear on whether you are using <a href="http://gdatatips.blogspot.com/2008/11/2-legged-oauth-in-python.html" rel="nofollow">2 or 3 legged OAuth</a>:</p>
| 0 | 2009-10-15T14:00:06Z | [
"python",
"oauth"
] |
oauth google using python | 1,215,033 | <p>i am fairly new to programming for web. and i want to start from scratch here.
i tried to search the net but ended up completely confused.
now what i want to learn is how to authenticate a google account through a python script.
can anyone please provide me with a code fragment or any example.</p>
<p>thanks a lot in advance.</p>
| 11 | 2009-07-31T21:42:37Z | 5,592,986 | <p>I spent a whole day on coding this, after several failed attempts over the past few weeks. This only gets you as far as the first step, but it does so without any external libraries. And yes, I know it's close to two years after the OP, but from what I could see it still needed to be done.</p>
<pre><code>
#!/usr/bin/python
'demo Google OAuth'
import sys, os, urllib, urllib2, time, httplib
import hmac, hashlib, random, re, base64
PARAMETERS = {
'oauth_consumer_key': os.getenv('OAUTH_CONSUMER_KEY') or 'anonymous',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_signature': '',
'oauth_timestamp': os.getenv('OAUTH_TIMESTAMP') or '%d' % time.time(),
'oauth_nonce': os.getenv('OAUTH_NONCE') or '%x' % random.getrandbits(64),
'oauth_version': '1.0',
'oauth_callback': os.getenv('OAUTH_CALLBACK') or 'callback',
}
SCOPE = {'scope': 'https://www.google.com/calendar/feeds/'}
SECRET = os.getenv('OAUTH_CONSUMER_SECRET') or 'anonymous'
def google_oauth():
'OAuthGetRequestToken, OAuthAuthorizeToken, OAuthGetAccessToken'
request_token = get_request_token()
return request_token
def get_request_token():
'ask Google for a request token'
url = 'https://www.google.com/accounts/OAuthGetRequestToken'
token_secret = '' # we don't have a token secret yet
PARAMETERS['oauth_signature'] = sign('&'.join((SECRET, token_secret)),
'&'.join(map(urlencode, ('GET', url, parameters('signing')))))
body = urllib.urlencode(SCOPE)
request = urllib2.Request(url + '?' + body)
request.add_header('Authorization', 'OAuth ' + parameters('header'))
opener = urllib2.build_opener(urllib2.HTTPSHandler(debuglevel = 1))
response = opener.open(request)
reply = response.read()
response.close()
return reply
def byte_encode(match):
'for use with re.sub'
return '%%%02X' % ord(match.group())
def urlencode(string):
"unreserved = ALPHA, DIGIT, '-', '.', '_', '~'"
return re.sub(re.compile('[^0-9A-Za-z._~-]'),
byte_encode, string.encode('utf8'))
def sign(secret, text):
print >>sys.stderr, 'signature base string: "%s", secret: %s' % (
repr(text), repr(secret))
digest = hmac.new(secret, text, hashlib.sha1).digest()
return urlencode(base64.encodestring(digest).rstrip())
def base64string(hexstring):
recoded = urlencode(base64.encodestring(hexstring.decode('hex')).rstrip())
print >>sys.stderr, 'recoded:', recoded
return recoded
def parameters(format):
if format == 'header':
formatted = ', '.join(['%s="%s"' % (key, value)
for key, value in PARAMETERS.items()])
elif format == 'signing':
formatted = '&'.join(sorted(['%s=%s' % (key,
urlencode(value.encode('utf8'))) for
key, value in (PARAMETERS.items() + SCOPE.items()) if
key not in ['oauth_signature']]))
#print >>sys.stderr, format, formatted
return formatted
def hmac_sha1_test():
'from tools.ietf.org/html/rfc2202'
assert sign('\x0b' * 20, 'Hi There') == base64string(
'b617318655057264e28bc0b6fb378c8ef146be00')
assert sign('Jefe', 'what do ya want for nothing?') == base64string(
'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79')
assert sign('\xaa' * 20, '\xdd' * 50) == base64string(
'125d7342b9ac11cd91a39af48aa17b4f63f175d3')
# last test from http://oauth.net/core/1.0/#rfc.section.9.1.1, app. A.5.2
assert sign('kd94hf93k423kf44&pfkkdhi9sl3r4s00',
'GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26' + \
'oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D' + \
'kllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26' + \
'oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26' + \
'oauth_version%3D1.0%26size%3Doriginal') == urlencode(
'tR3+Ty81lMeYAr/Fid0kMTYa/WM=')
return True
if __name__ == '__main__':
command = os.path.splitext(os.path.basename(sys.argv[0]))[0]
print eval(command)(*sys.argv[1:])
</code></pre>
<p>Save it as google_oauth.py, and you can link to it like so: <pre><code>ln -s google_oauth.py hmac_sha1_test.py</code></pre> to test any of the subroutines. Combined with the use of environment variables, you can compare your results with those of Google's OAuth Playground (other folks here provided the link) and see where you are going wrong. I found many problems with the script that way; there may well be many more. But if you invoke ./google_oauth.py, you should see something like this:</p>
<pre>
jcomeau@intrepid:~/rentacoder/marchie$ ./google_oauth.py
signature base string: "'GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_callback%3Dcallback%26oauth_consumer_key%3Danonymous%26oauth_nonce%3Da64720fda018906b%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1302253695%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fwww.google.com%252Fcalendar%252Ffeeds%252F'", secret: 'anonymous&'
send: 'GET /accounts/OAuthGetRequestToken?scope=https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nConnection: close\r\nAuthorization: OAuth oauth_nonce="a64720fda018906b", oauth_timestamp="1302253695", oauth_consumer_key="anonymous", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_signature="LSJxopFXWN71sTSIBIkNeGgsOjc%3D", oauth_callback="callback"\r\nUser-Agent: Python-urllib/2.6\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: text/plain; charset=UTF-8
header: Date: Fri, 08 Apr 2011 09:08:20 GMT
header: Expires: Fri, 08 Apr 2011 09:08:20 GMT
header: Cache-Control: private, max-age=0
header: X-Content-Type-Options: nosniff
header: X-XSS-Protection: 1; mode=block
header: Content-Length: 118
header: Server: GSE
header: Connection: close
oauth_token=4%2FfvSIWW9WBHXa_CjInpOf4FdNYhCj&oauth_token_secret=qhB1EGIKjL1pG9POF2ZOcQk3&oauth_callback_confirmed=true
</pre>
| 19 | 2011-04-08T09:14:37Z | [
"python",
"oauth"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 1,215,234 | <p>If you're on *nix, try running the following command:</p>
<pre><code>sort <file name> | uniq
</code></pre>
| 23 | 2009-07-31T22:43:14Z | [
"python",
"text",
"file-io"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 1,215,244 | <p>On Unix/Linux, use the <code>uniq</code> command, as per David Locke's answer, or <code>sort</code>, as per William Pursell's comment.</p>
<p>If you need a Python script:</p>
<pre><code>lines_seen = set() # holds lines already seen
outfile = open(outfilename, "w")
for line in open(infilename, "r"):
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()
</code></pre>
<p><strong>Update:</strong> The <code>sort</code>/<code>uniq</code> combination will remove duplicates but return a file with the lines sorted, which may or may not be what you want. The Python script above won't reorder lines, but just drop duplicates. Of course, to get the script above to sort as well, just leave out the <code>outfile.write(line)</code> and instead, immediately after the loop, do <code>outfile.writelines(sorted(lines_seen))</code>.</p>
| 45 | 2009-07-31T22:46:20Z | [
"python",
"text",
"file-io"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 1,216,544 | <pre><code>uniqlines = set(open('/tmp/foo').readlines())
</code></pre>
<p>this will give you the list of unique lines.</p>
<p>writing that back to some file would be as easy as:</p>
<pre><code>bar = open('/tmp/bar', 'w').writelines(set(uniqlines))
bar.close()
</code></pre>
| 10 | 2009-08-01T12:51:25Z | [
"python",
"text",
"file-io"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 1,216,798 | <p>get all your lines in the list and make a set of lines and you are done.
for example,</p>
<pre><code>>>> x = ["line1","line2","line3","line2","line1"]
>>> list(set(x))
['line3', 'line2', 'line1']
>>>
</code></pre>
<p>and write the content back to the file.</p>
| 3 | 2009-08-01T15:18:15Z | [
"python",
"text",
"file-io"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 17,356,204 | <p>Here is my solution</p>
<pre><code>if __name__ == '__main__':
f = open('temp.txt','w+')
flag = False
with open('file.txt') as fp:
for line in fp:
for temp in f:
if temp == line:
flag = True
print('Found Match')
break
if flag == False:
f.write(line)
elif flag == True:
flag = False
f.seek(0)
f.close()
</code></pre>
| -1 | 2013-06-28T02:15:04Z | [
"python",
"text",
"file-io"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 18,810,771 | <p><strong>Python One liners :</strong></p>
<pre><code>python -c "import sys; lines = sys.stdin.readlines(); print ''.join(sorted(set(lines)))" < InputFile > OutputFile
</code></pre>
| 2 | 2013-09-15T09:16:39Z | [
"python",
"text",
"file-io"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 24,097,615 | <p>You can do:</p>
<pre><code>import os
os.system("awk '!x[$0]++' /path/to/file > /path/to/rem-dups")
</code></pre>
<p>Here You are using bash into python :)</p>
<p>You have also other way:</p>
<pre><code>with open('/tmp/result.txt') as result:
uniqlines = set(result.readlines())
with open('/tmp/rmdup.txt', 'w') as rmdup:
rmdup.writelines(set(uniqlines))
</code></pre>
| 2 | 2014-06-07T13:15:58Z | [
"python",
"text",
"file-io"
] |
How might I remove duplicate lines from a file? | 1,215,208 | <p>I have a file with one column. How to delete repeated lines in a file?</p>
| 17 | 2009-07-31T22:37:44Z | 29,366,486 | <p>Its a rehash of whats already been said here - here what I use.</p>
<pre><code>import optparse
def removeDups(inputfile, outputfile):
lines=open(inputfile, 'r').readlines()
lines_set = set(lines)
out=open(outputfile, 'w')
for line in lines_set:
out.write(line)
def main():
parser = optparse.OptionParser('usage %prog ' +\
'-i <inputfile> -o <outputfile>')
parser.add_option('-i', dest='inputfile', type='string',
help='specify your input file')
parser.add_option('-o', dest='outputfile', type='string',
help='specify your output file')
(options, args) = parser.parse_args()
inputfile = options.inputfile
outputfile = options.outputfile
if (inputfile == None) or (outputfile == None):
print parser.usage
exit(1)
else:
removeDups(inputfile, outputfile)
if __name__ == '__main__':
main()
</code></pre>
| 4 | 2015-03-31T10:29:50Z | [
"python",
"text",
"file-io"
] |
Where can I find useful documentation for pyusb (Python USB library)? | 1,215,399 | <p>I am trying to interact with a keyboard with pyusb but I can't find any documentation or tutorial for it. <a href="http://sourceforge.net/projects/pyusb/">The project homepage</a> has absolutely no information and the installed README file is pretty useless. There is no man page. I found mailing lists but the people there have way more advanced problems than me.</p>
<p>The only useful thing I found so far is the sample subdirectory in the source. There is an usbenum.py which seems straightforward it does something like lsusb. I know what an USB bus or a device is but what exactly "Configuration", "Interface", "Alternate setting" and "Endpoint" mean? Some general USB information is also welcome.</p>
<p>The usbprint.py tells me that I can use a device with controlMsg, bulkRead and bulkWrite but what is the meaning of their parameters? Are there any other functions? Are the constants used specific to the printer? Is there a risk of damaging any hardware if I do something wrong?</p>
<p>The best thing would be a step-by-step guide for using some simple hardware and a detailed description of all the functions.</p>
<p>The problem I am trying to solve is described on superuser: <a href="http://superuser.com/questions/13120/how-can-i-get-usb-keyboard-extra-buttons-working">http://superuser.com/questions/13120/how-can-i-get-usb-keyboard-extra-buttons-working</a>
Please take a look at it. If there is an easier way to solve that problem then I have no intention of doing this. My own answer there may tell something about my level of understanding in this topic.</p>
<p>Thank you.</p>
| 7 | 2009-07-31T23:53:23Z | 1,215,465 | <p>Well from what I can see it is an fairly thin ctype wrapper around libusb, so I would start there: <a href="http://libusb.sourceforge.net/api-1.0/">http://libusb.sourceforge.net/api-1.0/</a></p>
| 5 | 2009-08-01T00:25:51Z | [
"python",
"documentation",
"usb"
] |
How to list all class properties | 1,215,408 | <p>I have class SomeClass with properties. For example <code>id</code> and <code>name</code>:</p>
<pre><code>class SomeClass(object):
def __init__(self):
self.__id = None
self.__name = None
def get_id(self):
return self.__id
def set_id(self, value):
self.__id = value
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = value
id = property(get_id, set_id)
name = property(get_name, set_name)
</code></pre>
<p>What is the easiest way to list properties? I need this for serialization.</p>
| 9 | 2009-07-31T23:58:46Z | 1,215,428 | <pre><code>property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]
</code></pre>
| 14 | 2009-08-01T00:05:19Z | [
"python",
"serialization",
"properties"
] |
How to list all class properties | 1,215,408 | <p>I have class SomeClass with properties. For example <code>id</code> and <code>name</code>:</p>
<pre><code>class SomeClass(object):
def __init__(self):
self.__id = None
self.__name = None
def get_id(self):
return self.__id
def set_id(self, value):
self.__id = value
def get_name(self):
return self.__name
def set_name(self, value):
self.__name = value
id = property(get_id, set_id)
name = property(get_name, set_name)
</code></pre>
<p>What is the easiest way to list properties? I need this for serialization.</p>
| 9 | 2009-07-31T23:58:46Z | 1,215,609 | <pre><code>import inspect
def isprop(v):
return isinstance(v, property)
propnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]
</code></pre>
<p><code>inspect.getmembers</code> gets inherited members as well (and selects members by a predicate, here we coded <code>isprop</code> because it's not among the many predefined ones in module <code>inspect</code>; you could also use a <code>lambda</code>, of course, if you prefer).</p>
| 17 | 2009-08-01T01:45:03Z | [
"python",
"serialization",
"properties"
] |
Can a Python function take a generator and return generators to subsets of its generated output? | 1,215,464 | <p>Let's say I have a generator function like this:</p>
<pre><code>import random
def big_gen():
i = 0
group = 'a'
while group != 'd':
i += 1
yield (group, i)
if random.random() < 0.20:
group = chr(ord(group) + 1)
</code></pre>
<p>Example output might be:
('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('a', 6), ('a', 7), ('a', 8), ('b', 9), ('c', 10), ('c', 11), ('c', 12), ('c', 13)</p>
<p>I would like to break this into three groups: Group A, Group B, and Group C. And I would like a generator for each group. Then I'd pass the generator and the group letter into a subfunction. An example of the subfunction:</p>
<pre><code>def printer(group_letter, generator):
print "These numbers are in group %s:" % group_letter
for num in generator:
print "\t%s" % num
</code></pre>
<p>The desired output would be:</p>
<pre><code>These numbers are in group a:
1
2
3
4
5
6
7
8
These numbers are in group b:
9
These numbers are in group c:
10
11
12
13
</code></pre>
<p>How can I do this without changing big_gen() or printer(), and avoid storing the entire group in memory at once? (In real life, the groups are <strong>huge</strong>)</p>
| 4 | 2009-08-01T00:24:45Z | 1,215,481 | <p>You have a slight problem here. You'd like the function to printer() to take a generator for each group, but in reality you have the same generator yielding all groups. You have two options, as I see it:</p>
<p>1) Change big_gen() to yield generators:</p>
<pre><code>import random
def big_gen():
i = 0
group = 'a'
while group != 'd':
def gen():
i += 1
yield i
if random.random() < 0.20:
group = chr(ord(group) + 1)
yield group, gen
from itertools import imap
imap(lambda a: printer(*a), big_gen())
</code></pre>
<p>2) Change printer() to keep state and notice when the group changes (keeping your original big_gen() function):</p>
<pre><code>def printer(generator):
group = None
for grp, num in generator:
if grp != group:
print "These numbers are in group %s:" % grp
group = grp
print "\t%s" % num
</code></pre>
| 0 | 2009-08-01T00:40:26Z | [
"python",
"generator"
] |
Can a Python function take a generator and return generators to subsets of its generated output? | 1,215,464 | <p>Let's say I have a generator function like this:</p>
<pre><code>import random
def big_gen():
i = 0
group = 'a'
while group != 'd':
i += 1
yield (group, i)
if random.random() < 0.20:
group = chr(ord(group) + 1)
</code></pre>
<p>Example output might be:
('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('a', 6), ('a', 7), ('a', 8), ('b', 9), ('c', 10), ('c', 11), ('c', 12), ('c', 13)</p>
<p>I would like to break this into three groups: Group A, Group B, and Group C. And I would like a generator for each group. Then I'd pass the generator and the group letter into a subfunction. An example of the subfunction:</p>
<pre><code>def printer(group_letter, generator):
print "These numbers are in group %s:" % group_letter
for num in generator:
print "\t%s" % num
</code></pre>
<p>The desired output would be:</p>
<pre><code>These numbers are in group a:
1
2
3
4
5
6
7
8
These numbers are in group b:
9
These numbers are in group c:
10
11
12
13
</code></pre>
<p>How can I do this without changing big_gen() or printer(), and avoid storing the entire group in memory at once? (In real life, the groups are <strong>huge</strong>)</p>
| 4 | 2009-08-01T00:24:45Z | 1,215,600 | <p>Sure, this does what you want:</p>
<pre><code>import itertools
import operator
def main():
for let, gen in itertools.groupby(big_gen(), key=operator.itemgetter(0)):
secgen = itertools.imap(operator.itemgetter(1), gen)
printer(let, secgen)
</code></pre>
<p><code>groupby</code> does the bulk of the work here -- the <code>key=</code> just tells it what field to group by. </p>
<p>The resulting generator needs to be wrapped in an <code>imap</code> just because you've specified your <code>printer</code> signature to take an iterator over number, while, by nature, <code>groupby</code> returns iterators over the same items it gets as its input -- here, 2-items tuples with a letter followed by a number -- but this is not really all that germane to your question's title.</p>
<p>The answer to that title is that, yep, a Python function can perfectly well do the job you want -- <code>itertools.groupby</code> in fact does exactly that. I recommend studying the <a href="http://docs.python.org/library/itertools.html">itertools</a> module carefully, it's a very useful tool (and delivers splendid performance as well).</p>
| 8 | 2009-08-01T01:39:01Z | [
"python",
"generator"
] |
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages | 1,215,610 | <p>Can someone please explain to me what is going on with python in ubuntu 9.04?</p>
<p>I'm trying to spin up <code>virtualenv</code>, and the <code>--no-site-packages</code> flag seems to do nothing with ubuntu. I installed <code>virtualenv 1.3.3</code> with <code>easy_install</code> (which I've upgraded to <code>setuptools 0.6c9</code>) and everything seems to be installed to <code>/usr/local/lib/python2.6/dist-packages</code></p>
<p>I <em>assume</em> that when installing a package using apt-get, it's placed in <code>/usr/lib/python2.6/dist-packages/</code> ?</p>
<p>The issue is, there is a <code>/usr/local/lib/python2.6/site-packages</code> as well that just sits there being empty. It would seem (by looking at the <code>path</code> in a <code>virtualenv</code>) that this is the folder virtualenv uses as backup. Thus even thought I omit <code>--no-site-packages</code>, I cant access my local systems packages from any of my virtualenv's.</p>
<p>So my questions are:</p>
<ol>
<li>How do I get <code>virtualenv</code> to point to one of the <code>dist-packages</code>?</li>
<li><em>Which</em> dist-packages should I point it to? <code>/usr/lib/python2.6/dist-packages</code> or <code>/usr/local/lib/python2.6/dist-packages/</code></li>
<li>What is the point of <code>/usr/lib/python2.6/site-packages</code>? There's nothing in there!</li>
<li>Is it first come first serve on the path? If I have a newer version of package XYZ installed in <code>/usr/local/lib/python2.6/dist-packages/</code> and and older one (from ubuntu repos/apt-get) in <code>/usr/lib/python2.6/dist-packages</code>, which one gets imported when I <code>import xyz</code>? I'm assuming this is based on the path list, yes?</li>
<li>Why the hell is this so confusing? Is there something I'm missing here?</li>
<li>Where is it defined that <code>easy_install</code> should install to <code>/usr/local/lib/python2.6/dist-packages</code>?</li>
<li>Will this affect <code>pip</code> as well?</li>
</ol>
<p>Thanks to anyone who can clear this up!</p>
| 15 | 2009-08-01T01:45:22Z | 1,215,627 | <p>I'd be tempted to hack it by making site-packages a link to dist-packages, but I guess this might affect other cases where you want to install some extension other than from the ubuntu dist. I can't think of another answer to 1 except tweaking virtualenv's sources (with both ubuntu and virtualenv being so popular I wouldn't be surprised to find tweaked versions already exist).</p>
<p>Re 2, if you're using /usr/local/bin/python you should use the /usr/local version of the lib (including site-packages) and conversely if you're using /usr/bin/python.</p>
<p>Re 3, there will be something there if you ever install an extension for /usr/bin/python from sources (not via easy_install or from ubuntu's distro).</p>
<p>Re 4, yes, earlier entries on the path take precedence.</p>
<p>Re 5, easy_install is easy only in its name -- it does so much dark magic that it's been carefully kept out of the standard python library despite its convenience because the consensus among us python committers is that deep dark magic for convenience is "easy" only on the surface.</p>
<p>Re 6, I think that's an ubuntu modification to easy_install -- if that's right then it's defined wherever Canonical or other ubuntu maintainers make their collective decisions.</p>
<p>Re 7, sorry, no idea -- I have no reasonably recent ubuntu at hand to check.</p>
| 9 | 2009-08-01T01:52:29Z | [
"python",
"ubuntu",
"setuptools",
"virtualenv"
] |
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages | 1,215,610 | <p>Can someone please explain to me what is going on with python in ubuntu 9.04?</p>
<p>I'm trying to spin up <code>virtualenv</code>, and the <code>--no-site-packages</code> flag seems to do nothing with ubuntu. I installed <code>virtualenv 1.3.3</code> with <code>easy_install</code> (which I've upgraded to <code>setuptools 0.6c9</code>) and everything seems to be installed to <code>/usr/local/lib/python2.6/dist-packages</code></p>
<p>I <em>assume</em> that when installing a package using apt-get, it's placed in <code>/usr/lib/python2.6/dist-packages/</code> ?</p>
<p>The issue is, there is a <code>/usr/local/lib/python2.6/site-packages</code> as well that just sits there being empty. It would seem (by looking at the <code>path</code> in a <code>virtualenv</code>) that this is the folder virtualenv uses as backup. Thus even thought I omit <code>--no-site-packages</code>, I cant access my local systems packages from any of my virtualenv's.</p>
<p>So my questions are:</p>
<ol>
<li>How do I get <code>virtualenv</code> to point to one of the <code>dist-packages</code>?</li>
<li><em>Which</em> dist-packages should I point it to? <code>/usr/lib/python2.6/dist-packages</code> or <code>/usr/local/lib/python2.6/dist-packages/</code></li>
<li>What is the point of <code>/usr/lib/python2.6/site-packages</code>? There's nothing in there!</li>
<li>Is it first come first serve on the path? If I have a newer version of package XYZ installed in <code>/usr/local/lib/python2.6/dist-packages/</code> and and older one (from ubuntu repos/apt-get) in <code>/usr/lib/python2.6/dist-packages</code>, which one gets imported when I <code>import xyz</code>? I'm assuming this is based on the path list, yes?</li>
<li>Why the hell is this so confusing? Is there something I'm missing here?</li>
<li>Where is it defined that <code>easy_install</code> should install to <code>/usr/local/lib/python2.6/dist-packages</code>?</li>
<li>Will this affect <code>pip</code> as well?</li>
</ol>
<p>Thanks to anyone who can clear this up!</p>
| 15 | 2009-08-01T01:45:22Z | 1,216,108 | <p>Well I have a Ubuntu 9.04 and quickly tried setting up a couple sandboxes with site-packages and one without. And things are working fine.</p>
<p>The only difference in the approach I took is I used Ubuntu's python-virtualenv package (1.3.3). And presume that it is tweaked by Ubuntu team to suit Ubuntu setups.</p>
<p>To sum up disable easy_installed virtualenv for a while, <strong>use packaged python-virtualenv</strong> and see if that meets your expectations.</p>
<p>In fact we use similar setup for production without any problem. Rest is already answered by Alex.</p>
| 2 | 2009-08-01T07:50:26Z | [
"python",
"ubuntu",
"setuptools",
"virtualenv"
] |
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages | 1,215,610 | <p>Can someone please explain to me what is going on with python in ubuntu 9.04?</p>
<p>I'm trying to spin up <code>virtualenv</code>, and the <code>--no-site-packages</code> flag seems to do nothing with ubuntu. I installed <code>virtualenv 1.3.3</code> with <code>easy_install</code> (which I've upgraded to <code>setuptools 0.6c9</code>) and everything seems to be installed to <code>/usr/local/lib/python2.6/dist-packages</code></p>
<p>I <em>assume</em> that when installing a package using apt-get, it's placed in <code>/usr/lib/python2.6/dist-packages/</code> ?</p>
<p>The issue is, there is a <code>/usr/local/lib/python2.6/site-packages</code> as well that just sits there being empty. It would seem (by looking at the <code>path</code> in a <code>virtualenv</code>) that this is the folder virtualenv uses as backup. Thus even thought I omit <code>--no-site-packages</code>, I cant access my local systems packages from any of my virtualenv's.</p>
<p>So my questions are:</p>
<ol>
<li>How do I get <code>virtualenv</code> to point to one of the <code>dist-packages</code>?</li>
<li><em>Which</em> dist-packages should I point it to? <code>/usr/lib/python2.6/dist-packages</code> or <code>/usr/local/lib/python2.6/dist-packages/</code></li>
<li>What is the point of <code>/usr/lib/python2.6/site-packages</code>? There's nothing in there!</li>
<li>Is it first come first serve on the path? If I have a newer version of package XYZ installed in <code>/usr/local/lib/python2.6/dist-packages/</code> and and older one (from ubuntu repos/apt-get) in <code>/usr/lib/python2.6/dist-packages</code>, which one gets imported when I <code>import xyz</code>? I'm assuming this is based on the path list, yes?</li>
<li>Why the hell is this so confusing? Is there something I'm missing here?</li>
<li>Where is it defined that <code>easy_install</code> should install to <code>/usr/local/lib/python2.6/dist-packages</code>?</li>
<li>Will this affect <code>pip</code> as well?</li>
</ol>
<p>Thanks to anyone who can clear this up!</p>
| 15 | 2009-08-01T01:45:22Z | 1,558,028 | <p>I believe Mike Orr's answer from <a href="http://groups.google.com/group/python-virtualenv/browse_thread/thread/1412994580f0a2c6/17271fcd6a6e747e?lnk=gst&q=ubuntu+virtualenv#17271fcd6a6e747e" rel="nofollow">the virtual-env mailing list</a> seems to be the best. Note the OP published this question in both places.</p>
<p><strong>Original content of mail:</strong></p>
<p>Years ago Debian created /usr/local/lib/pythonVERSION/site-packages,
and compiled the Python binary to include it in the default search
path. Ubuntu followed Debian's lead as it normally does. The Python
developers did not like this because you'd get interference with a
locally-installed /usr/local/bin/python using the same site-packages
directory. Ubuntu finally decided to abandon site-packages and use
dist-packages instead, a name which they invented so it wouldn't
interfere with anything. The loing story is out there somewhere if
you google it, somewhere in the Python bug tracker or distutils SIG or
such.</p>
<p>The system works, at least if you use the Ubuntu virtualenv package.
Some people have had problems using a locally-installed virtualenv on
Ubuntu because the magic sys.path entries weren't being added or
something. I'm not sure about --no-site-packages because I never use
that option: I run PIL and mysqldb from the Ubuntu packages because it
can be hard to compile their C dependencies sometimes. (Need the
right header files, Python is ignoring the header files, etc.)</p>
<p>So Ubuntu Python packages go into
/usr/lib/pythonVERSION/dist-packages. Or that python-support
directory for some reason. Locally-installed Python packages go into
/usr/local/lib/pythonVERSION/dist-packages by default. Whenever I
install an Ubuntu 9.04 system I run:</p>
<p>$ sudo apt-get install python-setuptools (6.0c9)
$ sudo apt-get install python-virtualenv (1.3.3)
$ sudo easy_install pip
$ sudo pip install virtualenvwrapper</p>
<p>The virtualenvs work fine this way, although I haven't tried --no-site-packages.</p>
<blockquote>
<p>I'm trying to spin up virtualenv, and the --no-site-packages flag
seems to do nothing with ubuntu. I installed virtualenv 1.3.3 with
easy_install (which I've upgraded to setuptools 0.6c9)</p>
</blockquote>
<p>These versions are both in Ubuntu 9.04, so you're making it harder on
yourself by installing them locally.</p>
<blockquote>
<p>and everything
seems to be installed to /usr/local/lib/python2.6/dist-packages</p>
</blockquote>
<p>Yes</p>
<blockquote>
<p>I assume that when installing a package using apt-get, it's placed in /
usr/lib/python2.6/dist-packages/ ?</p>
</blockquote>
<p>Yes</p>
<blockquote>
<ol start="4">
<li>Is it first come first serve on the path? If I have a newer
version of package XYZ installed in /usr/local/lib/python2.6/dist-
packages/ and and older one (from ubuntu repos/apt-get) in /usr/lib/
python2.6/dist-packages, which one gets imported when I import xyz?
I'm assuming this is based on the path list, yes?</li>
</ol>
</blockquote>
<p>sys.path is scanned in order. The only funny thing is that .pth eggs
get put earlier or later in the path than some people expect. But if
you're using pip for everything it can do (i.e. except to install pip
itself, precompiled eggs, and a snapshot of a local directory that's a
copy rather than an egg link), you won't have many .pth eggs anyway.</p>
<blockquote>
<ol start="5">
<li>Why the hell is this so confusing? Is there something I'm
missing here?</li>
</ol>
</blockquote>
<p>It's not well documented. I figured it out by scanning the web.</p>
<blockquote>
<ol start="7">
<li>Will this affect pip as well?</li>
</ol>
</blockquote>
<p>Yes, pip will automatically install to
/usr/local/lib/pythonVERSION/site-packages. Use "pip install -E
$VIRTUAL_ENV packagename" to install into a virtualenv.</p>
| 16 | 2009-10-13T03:09:20Z | [
"python",
"ubuntu",
"setuptools",
"virtualenv"
] |
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages | 1,215,610 | <p>Can someone please explain to me what is going on with python in ubuntu 9.04?</p>
<p>I'm trying to spin up <code>virtualenv</code>, and the <code>--no-site-packages</code> flag seems to do nothing with ubuntu. I installed <code>virtualenv 1.3.3</code> with <code>easy_install</code> (which I've upgraded to <code>setuptools 0.6c9</code>) and everything seems to be installed to <code>/usr/local/lib/python2.6/dist-packages</code></p>
<p>I <em>assume</em> that when installing a package using apt-get, it's placed in <code>/usr/lib/python2.6/dist-packages/</code> ?</p>
<p>The issue is, there is a <code>/usr/local/lib/python2.6/site-packages</code> as well that just sits there being empty. It would seem (by looking at the <code>path</code> in a <code>virtualenv</code>) that this is the folder virtualenv uses as backup. Thus even thought I omit <code>--no-site-packages</code>, I cant access my local systems packages from any of my virtualenv's.</p>
<p>So my questions are:</p>
<ol>
<li>How do I get <code>virtualenv</code> to point to one of the <code>dist-packages</code>?</li>
<li><em>Which</em> dist-packages should I point it to? <code>/usr/lib/python2.6/dist-packages</code> or <code>/usr/local/lib/python2.6/dist-packages/</code></li>
<li>What is the point of <code>/usr/lib/python2.6/site-packages</code>? There's nothing in there!</li>
<li>Is it first come first serve on the path? If I have a newer version of package XYZ installed in <code>/usr/local/lib/python2.6/dist-packages/</code> and and older one (from ubuntu repos/apt-get) in <code>/usr/lib/python2.6/dist-packages</code>, which one gets imported when I <code>import xyz</code>? I'm assuming this is based on the path list, yes?</li>
<li>Why the hell is this so confusing? Is there something I'm missing here?</li>
<li>Where is it defined that <code>easy_install</code> should install to <code>/usr/local/lib/python2.6/dist-packages</code>?</li>
<li>Will this affect <code>pip</code> as well?</li>
</ol>
<p>Thanks to anyone who can clear this up!</p>
| 15 | 2009-08-01T01:45:22Z | 6,919,668 | <p>You really should not touch Ubuntu's Python installation unless you are building system admin tools, or building something that could be considered to be a new system service.</p>
<p>If you are using Ubuntu to develop or deploy Python applications, always build your own Python from source, tar it up, and use that for deployment. That way you will have all the directories in the right place and virtualenv will work normally. If you will deploy several Python apps on the server, then make your Python live in some place like <code>/home/python</code> or <code>/opt/python</code> or somewhere outside of your home directory. Make sure that you have write permissions for the developers group (<code>users</code>?) so that people can easily add packages.</p>
<p>This also allows you to have two tiers of packages. The ones that are your in-house standard tools can be installed in your Python distro and be part of the tarball that you deploy, and only the app-specific packages would be in a virtualenv.</p>
<p>Do not upgrade or modify the Ubuntu system installed Python. </p>
| 3 | 2011-08-02T22:51:51Z | [
"python",
"ubuntu",
"setuptools",
"virtualenv"
] |
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages | 1,215,610 | <p>Can someone please explain to me what is going on with python in ubuntu 9.04?</p>
<p>I'm trying to spin up <code>virtualenv</code>, and the <code>--no-site-packages</code> flag seems to do nothing with ubuntu. I installed <code>virtualenv 1.3.3</code> with <code>easy_install</code> (which I've upgraded to <code>setuptools 0.6c9</code>) and everything seems to be installed to <code>/usr/local/lib/python2.6/dist-packages</code></p>
<p>I <em>assume</em> that when installing a package using apt-get, it's placed in <code>/usr/lib/python2.6/dist-packages/</code> ?</p>
<p>The issue is, there is a <code>/usr/local/lib/python2.6/site-packages</code> as well that just sits there being empty. It would seem (by looking at the <code>path</code> in a <code>virtualenv</code>) that this is the folder virtualenv uses as backup. Thus even thought I omit <code>--no-site-packages</code>, I cant access my local systems packages from any of my virtualenv's.</p>
<p>So my questions are:</p>
<ol>
<li>How do I get <code>virtualenv</code> to point to one of the <code>dist-packages</code>?</li>
<li><em>Which</em> dist-packages should I point it to? <code>/usr/lib/python2.6/dist-packages</code> or <code>/usr/local/lib/python2.6/dist-packages/</code></li>
<li>What is the point of <code>/usr/lib/python2.6/site-packages</code>? There's nothing in there!</li>
<li>Is it first come first serve on the path? If I have a newer version of package XYZ installed in <code>/usr/local/lib/python2.6/dist-packages/</code> and and older one (from ubuntu repos/apt-get) in <code>/usr/lib/python2.6/dist-packages</code>, which one gets imported when I <code>import xyz</code>? I'm assuming this is based on the path list, yes?</li>
<li>Why the hell is this so confusing? Is there something I'm missing here?</li>
<li>Where is it defined that <code>easy_install</code> should install to <code>/usr/local/lib/python2.6/dist-packages</code>?</li>
<li>Will this affect <code>pip</code> as well?</li>
</ol>
<p>Thanks to anyone who can clear this up!</p>
| 15 | 2009-08-01T01:45:22Z | 17,265,851 | <p>Another way to fix it:<br>
<a href="http://stackoverflow.com/a/17265840/202168">http://stackoverflow.com/a/17265840/202168</a></p>
<p>Have to remember to do that in each virtualenv where you need it, but doesn't rely on hacks or a special version of virtualenv</p>
| 1 | 2013-06-23T22:17:48Z | [
"python",
"ubuntu",
"setuptools",
"virtualenv"
] |
Search engine woes | 1,215,661 | <p>I have been trying to make this search engine for a MySQL database. Taking in user input is no problem, database querying is also fine.</p>
<p>One thing I need to figure out is this:</p>
<blockquote>
<p>I am a string in the database</p>
</blockquote>
<p>How do I match the input "AM", but keep the same case? There are PHP functions like <code>str_ireplace</code> or <code>preg_replace</code>/<code>eregi_replace</code>, but what I need to do is split the string according to <em>every exact</em> match (as separate word, so <em>do not</em> match "lAMb", only "am").</p>
<p>That is so I may highlight the matches. Also I need to figure out how to dynamically shorten a string but keep where matches are in the middle:</p>
<blockquote>
<p>... this is part of the string where ...</p>
</blockquote>
<p>and do this according to font-size set by user in any browser. I had one which only worked in WebKit, but this is no good. Please answer with something like PHP or Python, I'm not a hard-core C kind of guy.</p>
| 0 | 2009-08-01T02:11:53Z | 1,215,697 | <p>I suggest you read this</p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html</a></p>
<p>It may help you build a better search engine and probably answer some part of your question</p>
<p>Here is a good example of what you could do :</p>
<pre><code>mysql> SELECT id, body, MATCH (title,body) AGAINST
-> ('Security implications of running MySQL as root'
-> IN NATURAL LANGUAGE MODE) AS score
-> FROM articles WHERE MATCH (title,body) AGAINST
-> ('Security implications of running MySQL as root'
-> IN NATURAL LANGUAGE MODE);
</code></pre>
<pre>
+----+-------------------------------------+-----------------+
| id | body | score |
+----+-------------------------------------+-----------------+
| 4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014 |
| 6 | When configured properly, MySQL ... | 1.3114095926285 |
+----+-------------------------------------+-----------------+
2 rows in set (0.00 sec)
</pre>
| 4 | 2009-08-01T02:42:20Z | [
"php",
"javascript",
"python",
"mysql",
"search"
] |
Removing (or prefilling) the address details for PayPal Express Checkout | 1,215,704 | <p>I am looking at using PayPal as a payment option for my custom shopping cart I have built. I already have a cart set up, and a checkout 'complete'. It asks the user for their address. Once they have completed all the fields, they hit 'Pay with PayPal'. This does not send them to PayPal yet. First it processes the data they entered, THEN redirects them off to PayPal to pay.</p>
<p>This is all using PayPal Express Checkout.</p>
<p>The desired flow is something like this.</p>
<ol>
<li>The user adds items to the cart. All this happens and is already handled by my server, with no calls to PayPal. I want the user to manage the cart on MY WEBSITE, not PayPal.</li>
<li>Once finished, the user hits 'checkout'. This then takes them to another page on my server (for example <a href="http://mywebsite.com/store/checkout/" rel="nofollow">http://mywebsite.com/store/checkout/</a>) where they confirm their shopping cart and enter their shipping address and other details.</li>
<li>Once they finish that, they click a 'Pay with PayPal' button and are sent to another page on MY server (for example, <a href="http://mywebsite.com/store/checkout/pay/" rel="nofollow">http://mywebsite.com/store/checkout/pay/</a>) where my web application processes the order and information and adds it to the database. Now, HERE is where I want the paypal magic to happen.</li>
<li>During the processing of the previous page (step three), I want my web application to contact paypal using the SetExpressCheckout API and redirect the user to the PayPal payment page.</li>
<li>The user enters their credit card or PayPal details and pays on <a href="https://paypal.com" rel="nofollow">https://paypal.com</a>.</li>
<li>The user is then sent back to my website to be told that payment has been received (if it has) or any other alerts that they need to be aware of. The order status is updated accordingly and the order is shipped off.</li>
</ol>
<p>I am quite sure this is all possible. Is it? I am using Python and Django.</p>
<p>My only problem is that I do not want the users to have to enter their shipping/payment address TWICE (once on my website, once on the paypal payment website). I do not want the user to have to enter their shipping/payment address at the PayPal payment website. There is no need for this as I already have it. Is it possible to remove the address fields from the PayPal website, or just pre-fill them with data from my website?</p>
| 4 | 2009-08-01T02:45:23Z | 1,216,057 | <p>Yes, there is an option in the Paypal API to override the address input. See here:</p>
<p><a href="https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECCustomizing#id0864F070OHS__id0864H804030" rel="nofollow">https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECCustomizing#id0864F070OHS__id0864H804030</a></p>
<p>Relevant info copied here for convenience:</p>
<pre><code>To override the shipping address:
Set the ADDROVERRIDE parameter to 1 in the call to SetExpressCheckout.
Set the following shipping address parameters in the call to SetExpressCheckout to the address values you want to use for the new address.
SHIPTONAME
SHIPTOSTREET
SHIPTOCITY
SHIPTOSTATE (Optional)
SHIPTOCOUNTRYCODE
SHIPTOZIP
SHIPTOSTREET2 (Optional)
</code></pre>
| 2 | 2009-08-01T07:22:46Z | [
"python",
"django",
"paypal"
] |
Removing (or prefilling) the address details for PayPal Express Checkout | 1,215,704 | <p>I am looking at using PayPal as a payment option for my custom shopping cart I have built. I already have a cart set up, and a checkout 'complete'. It asks the user for their address. Once they have completed all the fields, they hit 'Pay with PayPal'. This does not send them to PayPal yet. First it processes the data they entered, THEN redirects them off to PayPal to pay.</p>
<p>This is all using PayPal Express Checkout.</p>
<p>The desired flow is something like this.</p>
<ol>
<li>The user adds items to the cart. All this happens and is already handled by my server, with no calls to PayPal. I want the user to manage the cart on MY WEBSITE, not PayPal.</li>
<li>Once finished, the user hits 'checkout'. This then takes them to another page on my server (for example <a href="http://mywebsite.com/store/checkout/" rel="nofollow">http://mywebsite.com/store/checkout/</a>) where they confirm their shopping cart and enter their shipping address and other details.</li>
<li>Once they finish that, they click a 'Pay with PayPal' button and are sent to another page on MY server (for example, <a href="http://mywebsite.com/store/checkout/pay/" rel="nofollow">http://mywebsite.com/store/checkout/pay/</a>) where my web application processes the order and information and adds it to the database. Now, HERE is where I want the paypal magic to happen.</li>
<li>During the processing of the previous page (step three), I want my web application to contact paypal using the SetExpressCheckout API and redirect the user to the PayPal payment page.</li>
<li>The user enters their credit card or PayPal details and pays on <a href="https://paypal.com" rel="nofollow">https://paypal.com</a>.</li>
<li>The user is then sent back to my website to be told that payment has been received (if it has) or any other alerts that they need to be aware of. The order status is updated accordingly and the order is shipped off.</li>
</ol>
<p>I am quite sure this is all possible. Is it? I am using Python and Django.</p>
<p>My only problem is that I do not want the users to have to enter their shipping/payment address TWICE (once on my website, once on the paypal payment website). I do not want the user to have to enter their shipping/payment address at the PayPal payment website. There is no need for this as I already have it. Is it possible to remove the address fields from the PayPal website, or just pre-fill them with data from my website?</p>
| 4 | 2009-08-01T02:45:23Z | 14,672,025 | <p>In your SetExpressCheckout call you can set "NOSHIPPING" to 1. This removes any shipping address details from being requested on the PayPal payment page. It also means, however, that no shipping details are attached to the payment (if you or the customer want to have that kind of information available from within your PayPal account). </p>
| 0 | 2013-02-03T11:34:37Z | [
"python",
"django",
"paypal"
] |
Removing (or prefilling) the address details for PayPal Express Checkout | 1,215,704 | <p>I am looking at using PayPal as a payment option for my custom shopping cart I have built. I already have a cart set up, and a checkout 'complete'. It asks the user for their address. Once they have completed all the fields, they hit 'Pay with PayPal'. This does not send them to PayPal yet. First it processes the data they entered, THEN redirects them off to PayPal to pay.</p>
<p>This is all using PayPal Express Checkout.</p>
<p>The desired flow is something like this.</p>
<ol>
<li>The user adds items to the cart. All this happens and is already handled by my server, with no calls to PayPal. I want the user to manage the cart on MY WEBSITE, not PayPal.</li>
<li>Once finished, the user hits 'checkout'. This then takes them to another page on my server (for example <a href="http://mywebsite.com/store/checkout/" rel="nofollow">http://mywebsite.com/store/checkout/</a>) where they confirm their shopping cart and enter their shipping address and other details.</li>
<li>Once they finish that, they click a 'Pay with PayPal' button and are sent to another page on MY server (for example, <a href="http://mywebsite.com/store/checkout/pay/" rel="nofollow">http://mywebsite.com/store/checkout/pay/</a>) where my web application processes the order and information and adds it to the database. Now, HERE is where I want the paypal magic to happen.</li>
<li>During the processing of the previous page (step three), I want my web application to contact paypal using the SetExpressCheckout API and redirect the user to the PayPal payment page.</li>
<li>The user enters their credit card or PayPal details and pays on <a href="https://paypal.com" rel="nofollow">https://paypal.com</a>.</li>
<li>The user is then sent back to my website to be told that payment has been received (if it has) or any other alerts that they need to be aware of. The order status is updated accordingly and the order is shipped off.</li>
</ol>
<p>I am quite sure this is all possible. Is it? I am using Python and Django.</p>
<p>My only problem is that I do not want the users to have to enter their shipping/payment address TWICE (once on my website, once on the paypal payment website). I do not want the user to have to enter their shipping/payment address at the PayPal payment website. There is no need for this as I already have it. Is it possible to remove the address fields from the PayPal website, or just pre-fill them with data from my website?</p>
| 4 | 2009-08-01T02:45:23Z | 14,673,250 | <p>David, it's absolutely possible for you to pass in address so it's prefilled for new PayPal customers, or to have PayaPal not ask for it at all. </p>
<p>Once you have gotten that working, however, I'd like to encourage you to also add in PayPal as a "shortcut" that skips straight from a button next to your "checkout" button to PayPal for payment, using the address the customer has on file with PayPal (which we will pass back to you, unless you suppress the address in that instance of the SetEC). Ditto, add it at the top of the page where you are otherwise asking to fill out the address.</p>
<p>For small businesses in the US, adding PayPal in this way boosts revenue by over 25 PERCENT typically, and very often by much more. You have to remember there are 55 mm active PayPal customers in the US alone, and they are habituated not to re-enter data.</p>
<p>Good luck,</p>
<p>PayPal Joel</p>
| 0 | 2013-02-03T13:59:12Z | [
"python",
"django",
"paypal"
] |
import serial error occured in Python | 1,215,889 | <p>I wrote</p>
<pre><code>import serial
</code></pre>
<p>There message are occured.</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/site-packages/serial/__init__.py", line 20, in ?
from serialposix import *
File "/usr/lib/python2.4/site-packages/serial/serialposix.py", line 13, in ?
import sys, os, fcntl, termios, struct, select, errno
ImportError: No module named termios
</code></pre>
<p>What's wrong?</p>
| 0 | 2009-08-01T05:14:51Z | 1,215,904 | <p><code>termios</code> has been in the Python standard library since 2.0 at least (I'm not very familiar with older Python versions), but it's always been a Unix-only module. Your 2.4 should be fine, IF you're running under any Unix flavor -- i.e., anything but Windows, more or less. The problem you're seeing suggests either a faulty Python install, or that you're on a non-Unix platform (and if it's not Windows I'm very curious to learn what it IS).</p>
<p><strong>Edit</strong>: OP has clarified that they're on Debian -- which has a long history of removing some crucial pieces from upstream components and hiding them in hard-to-locate packages, a history that has long hurt their Python packaging in particular.</p>
<p>I tried several package search engines but I can't find out where they hid termios for Python in particular (for any version) so all I can suggest are workarounds (unless the debian tag I just added attracts debian experts who can help) as well of course as asking on debian-specific forums (clarifying exactly what versions are in use, of course).</p>
<p>Maybe installing another Python (a REAL Python, not the "cleverly packaged", i.e. mangled into pieces and with pieces missing, Debian travesty) might help -- for example, if both sticking with Python 2.4 and using .deb are important constraints to the OP, PYTHON2.4_2.4.6-1UBUNTU3_I386.DEB (not sure how cleanly it and its dependencies install on the OP's specific Debian version, of course); or else, one might as well go with a more recent and complete Python, see for example <a href="http://weblog.patrice.ch/2009/01/14/install-python-2-6-on-debian-etch.html" rel="nofollow">here</a> (specifically for Debian Etch, but hopefully it can be adapted for the OP's exact version).</p>
| 3 | 2009-08-01T05:35:04Z | [
"python",
"serial-port",
"debian"
] |
comparing two strings with 'is' -- not performing as expected | 1,216,259 | <p>I'm attempting to compare two strings with <strong>is</strong>. One string is returned by a function, and the other is just declared in the comparison. <strong>is</strong> tests for object identity, but according to <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">this page</a>, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work:</p>
<pre><code>def uSplit(ustring):
#return user minus host
return ustring.split('!',1)[0]
user = uSplit('theuser!host')
print type(user)
print user
if user is 'theuser':
print 'ok'
else:
print 'failed'
user = 'theuser'
if user is 'theuser':
print 'ok'</code></pre>
<p>The output:</p>
<pre>type 'str'
theuser
failed
ok</pre>
<p>I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use <strong>==</strong>, but I'm just curious.</p>
| 1 | 2009-08-01T09:44:37Z | 1,216,265 | <p>That page you quoted says "If two string <strong>literals</strong> are equal, they have been put to same memory location" (emphasis mine). Python interns literal strings, but strings that are returned from some arbitrary function are separate objects. The <code>is</code> operator can be thought of as a pointer comparison, so two different objects will not compare as identical (even if they contain the same characters, ie. they are equal).</p>
| 3 | 2009-08-01T09:50:39Z | [
"python",
"string-comparison",
"string-literals"
] |
comparing two strings with 'is' -- not performing as expected | 1,216,259 | <p>I'm attempting to compare two strings with <strong>is</strong>. One string is returned by a function, and the other is just declared in the comparison. <strong>is</strong> tests for object identity, but according to <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">this page</a>, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work:</p>
<pre><code>def uSplit(ustring):
#return user minus host
return ustring.split('!',1)[0]
user = uSplit('theuser!host')
print type(user)
print user
if user is 'theuser':
print 'ok'
else:
print 'failed'
user = 'theuser'
if user is 'theuser':
print 'ok'</code></pre>
<p>The output:</p>
<pre>type 'str'
theuser
failed
ok</pre>
<p>I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use <strong>==</strong>, but I'm just curious.</p>
| 1 | 2009-08-01T09:44:37Z | 1,216,266 | <p>The site you quote says this:</p>
<blockquote>
<p>If two string literals are equal, they have been put to same memory location.</p>
</blockquote>
<p>But</p>
<pre><code>uSplit('theuser!host')
</code></pre>
<p>is not a string literal -- it's the result of an operation on the literal <code>'theuser!host'</code>.</p>
<p>Anyway, you usually shouldn't check for string equality using <code>is</code>, because this memory optimization in any case is just an implementation detail you shouldn't rely on.</p>
<p><hr /></p>
<p>Also, You should use <code>is</code> for things like <code>is None</code>. Use it for checking to see if two objects -- of classes that you designed -- are the same instance. You can't easily use it for strings or numbers because the rules for creation of those built-in classes are complex. Some strings are interned. Some numbers, similarly, are interned.</p>
| 2 | 2009-08-01T09:51:16Z | [
"python",
"string-comparison",
"string-literals"
] |
comparing two strings with 'is' -- not performing as expected | 1,216,259 | <p>I'm attempting to compare two strings with <strong>is</strong>. One string is returned by a function, and the other is just declared in the comparison. <strong>is</strong> tests for object identity, but according to <a href="http://zetcode.com/tutorials/pythontutorial/keywords/" rel="nofollow">this page</a>, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work:</p>
<pre><code>def uSplit(ustring):
#return user minus host
return ustring.split('!',1)[0]
user = uSplit('theuser!host')
print type(user)
print user
if user is 'theuser':
print 'ok'
else:
print 'failed'
user = 'theuser'
if user is 'theuser':
print 'ok'</code></pre>
<p>The output:</p>
<pre>type 'str'
theuser
failed
ok</pre>
<p>I'm guessing the reason for this is a string returned by a function is a different "type" of string than a string literal. Is there anyway to get a function to return a string literal? I know I could use <strong>==</strong>, but I'm just curious.</p>
| 1 | 2009-08-01T09:44:37Z | 1,216,268 | <p>What you have run into is the fact that Python does not always intern all of its strings. More detail here:</p>
<p><a href="http://mail.python.org/pipermail/tutor/2009-July/070157.html" rel="nofollow">http://mail.python.org/pipermail/tutor/2009-July/070157.html</a></p>
| 0 | 2009-08-01T09:52:14Z | [
"python",
"string-comparison",
"string-literals"
] |
Django newbie deployment question - ImportError: Could not import settings 'settings' | 1,216,340 | <p>The app runs fine using django internal server however when I use apache + mod_python I get the below error </p>
<p><hr /></p>
<pre><code> File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 75, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings' (Is it on sys.path? Does it have syntax errors?): No module named settings
</code></pre>
<p><hr /></p>
<p>Here is the needed information </p>
<p>1) Project directory: /root/djangoprojects/mysite</p>
<p>2) directory listing of /root/djangoprojects/mysite</p>
<pre><code>ls -ltr
total 28
-rw-r--r-- 1 root root 546 Aug 1 08:34 manage.py
-rw-r--r-- 1 root root 0 Aug 1 08:34 __init__.py
-rw-r--r-- 1 root root 136 Aug 1 08:35 __init__.pyc
-rw-r--r-- 1 root root 2773 Aug 1 08:39 settings.py
-rw-r--r-- 1 root root 1660 Aug 1 08:53 settings.pyc
drwxr-xr-x 2 root root 4096 Aug 1 09:04 polls
-rw-r--r-- 1 root root 581 Aug 1 10:06 urls.py
-rw-r--r-- 1 root root 314 Aug 1 10:07 urls.pyc
</code></pre>
<p>3) App directory : /root/djangoprojects/mysite/polls</p>
<p>4) directory listing of /root/djangoprojects/mysite/polls </p>
<pre><code>ls -ltr
total 20
-rw-r--r-- 1 root root 514 Aug 1 08:53 tests.py
-rw-r--r-- 1 root root 57 Aug 1 08:53 models.py
-rw-r--r-- 1 root root 0 Aug 1 08:53 __init__.py
-rw-r--r-- 1 root root 128 Aug 1 09:02 views.py
-rw-r--r-- 1 root root 375 Aug 1 09:04 views.pyc
-rw-r--r-- 1 root root 132 Aug 1 09:04 __init__.pyc
</code></pre>
<p>5) Anywhere in the filesystem running import django in python interpreter works fine</p>
<p>6) content of httpd.conf</p>
<pre><code><Location "/mysite">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /mysite
PythonPath "['/root/djangoprojects/', '/root/djangoprojects/mysite','/root/djangoprojects/mysite/polls', '/var/www'] + sys.path"
PythonDebug On
</Location>
</code></pre>
<p>7) PYTHONPATH variable is set to </p>
<pre><code>echo $PYTHONPATH
/root/djangoprojects/mysite
</code></pre>
<p>8) DJANGO_SETTINGS_MODULE is set to</p>
<pre><code>echo $DJANGO_SETTINGS_MODULE
mysite.settings
</code></pre>
<p>9) content of sys.path is </p>
<pre><code>import sys
>>> sys.path
['', '/root/djangoprojects/mysite', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/local/lib/python2.6/dist-packages']
</code></pre>
<p>How do I add settings location to sys.path such that it persistent across sessions ? </p>
<p>I have read umpteen no of post with people having the same issue it and I have tried a lot completely beats me as to what I need to do.</p>
<p>Looking for some help.</p>
<p>Thanks in advance
Ankur Gupta</p>
| 14 | 2009-08-01T10:34:27Z | 1,216,392 | <p>Your apache configuration should look like this:</p>
<pre><code><Location "/mysite">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonPath "['/root/djangoprojects/', '/root/djangoprojects/mysite','/root/djangoprojects/mysite/polls', '/var/www'] + sys.path"
PythonDebug On
</Location>
</code></pre>
<p>Note that the sole difference is the "mysite.settings". Don't forget to restart apache once the config has changed (apache2ctl restart). See <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/" rel="nofollow" rel="nofollow">http://docs.djangoproject.com/en/dev/howto/deployment/modpython/</a> for more info.</p>
| 5 | 2009-08-01T11:05:01Z | [
"python",
"django",
"deployment",
"mod-python"
] |
Django newbie deployment question - ImportError: Could not import settings 'settings' | 1,216,340 | <p>The app runs fine using django internal server however when I use apache + mod_python I get the below error </p>
<p><hr /></p>
<pre><code> File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 75, in __init__
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'settings' (Is it on sys.path? Does it have syntax errors?): No module named settings
</code></pre>
<p><hr /></p>
<p>Here is the needed information </p>
<p>1) Project directory: /root/djangoprojects/mysite</p>
<p>2) directory listing of /root/djangoprojects/mysite</p>
<pre><code>ls -ltr
total 28
-rw-r--r-- 1 root root 546 Aug 1 08:34 manage.py
-rw-r--r-- 1 root root 0 Aug 1 08:34 __init__.py
-rw-r--r-- 1 root root 136 Aug 1 08:35 __init__.pyc
-rw-r--r-- 1 root root 2773 Aug 1 08:39 settings.py
-rw-r--r-- 1 root root 1660 Aug 1 08:53 settings.pyc
drwxr-xr-x 2 root root 4096 Aug 1 09:04 polls
-rw-r--r-- 1 root root 581 Aug 1 10:06 urls.py
-rw-r--r-- 1 root root 314 Aug 1 10:07 urls.pyc
</code></pre>
<p>3) App directory : /root/djangoprojects/mysite/polls</p>
<p>4) directory listing of /root/djangoprojects/mysite/polls </p>
<pre><code>ls -ltr
total 20
-rw-r--r-- 1 root root 514 Aug 1 08:53 tests.py
-rw-r--r-- 1 root root 57 Aug 1 08:53 models.py
-rw-r--r-- 1 root root 0 Aug 1 08:53 __init__.py
-rw-r--r-- 1 root root 128 Aug 1 09:02 views.py
-rw-r--r-- 1 root root 375 Aug 1 09:04 views.pyc
-rw-r--r-- 1 root root 132 Aug 1 09:04 __init__.pyc
</code></pre>
<p>5) Anywhere in the filesystem running import django in python interpreter works fine</p>
<p>6) content of httpd.conf</p>
<pre><code><Location "/mysite">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE settings
PythonOption django.root /mysite
PythonPath "['/root/djangoprojects/', '/root/djangoprojects/mysite','/root/djangoprojects/mysite/polls', '/var/www'] + sys.path"
PythonDebug On
</Location>
</code></pre>
<p>7) PYTHONPATH variable is set to </p>
<pre><code>echo $PYTHONPATH
/root/djangoprojects/mysite
</code></pre>
<p>8) DJANGO_SETTINGS_MODULE is set to</p>
<pre><code>echo $DJANGO_SETTINGS_MODULE
mysite.settings
</code></pre>
<p>9) content of sys.path is </p>
<pre><code>import sys
>>> sys.path
['', '/root/djangoprojects/mysite', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/local/lib/python2.6/dist-packages']
</code></pre>
<p>How do I add settings location to sys.path such that it persistent across sessions ? </p>
<p>I have read umpteen no of post with people having the same issue it and I have tried a lot completely beats me as to what I need to do.</p>
<p>Looking for some help.</p>
<p>Thanks in advance
Ankur Gupta</p>
| 14 | 2009-08-01T10:34:27Z | 1,363,719 | <p>Try changing to the following:</p>
<pre><code><Location "/mysite">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonOption django.root /mysite
PythonPath "['/root/djangoprojects', '/var/www'] + sys.path"
PythonDebug On
</Location>
</code></pre>
<p>Use no "/" at the end of the PythonPath entries (that may be an issue, I had problems with that at least on Windows). </p>
<p>The entries '/root/djangoprojects/mysite','/root/djangoprojects/mysite/polls' are not needed since you will be referring to your modules by full name (i.e. mysite.sttings means the settings module inside the mysite package, which is the correct way to access it in the PythonPath /root/djangoprojects).</p>
| 0 | 2009-09-01T17:43:45Z | [
"python",
"django",
"deployment",
"mod-python"
] |
Is it safe to replace a self object by another object of the same type in a method? | 1,216,356 | <p>I would like to replace an object instance by another instance inside a method like this:</p>
<pre><code>class A:
def method1(self):
self = func(self)
</code></pre>
<p>The object is retrieved from a database.</p>
| 11 | 2009-08-01T10:42:21Z | 1,216,359 | <p>Yes, all that will happen is that you won't be able to reference the current instance of your class <code>A</code> (unless you set another variable to <code>self</code> before you change it.) I wouldn't recommend it though, it makes for less readable code.</p>
<p>Note that you're only changing a variable, just like any other. Doing <code>self = 123</code> is the same as doing <code>abc = 123</code>. <code>self</code> is only a reference to the current instance within the method. You can't change your instance by setting <code>self</code>.</p>
<p>What <code>func(self)</code> should do is to change the variables of your instance:</p>
<pre><code>def func(obj):
obj.var_a = 123
obj.var_b = 'abc'
</code></pre>
<p>Then do this:</p>
<pre><code>class A:
def method1(self):
func(self) # No need to assign self here
</code></pre>
| 6 | 2009-08-01T10:44:56Z | [
"python"
] |
Is it safe to replace a self object by another object of the same type in a method? | 1,216,356 | <p>I would like to replace an object instance by another instance inside a method like this:</p>
<pre><code>class A:
def method1(self):
self = func(self)
</code></pre>
<p>The object is retrieved from a database.</p>
| 11 | 2009-08-01T10:42:21Z | 1,216,361 | <p>It is unlikely that replacing the 'self' variable will accomplish whatever you're trying to do, that couldn't just be accomplished by storing the result of func(self) in a different variable. 'self' is effectively a local variable only defined for the duration of the method call, used to pass in the instance of the class which is being operated upon. Replacing self will not actually replace references to the original instance of the class held by other objects, nor will it create a lasting reference to the new instance which was assigned to it.</p>
| 21 | 2009-08-01T10:45:18Z | [
"python"
] |
Is it safe to replace a self object by another object of the same type in a method? | 1,216,356 | <p>I would like to replace an object instance by another instance inside a method like this:</p>
<pre><code>class A:
def method1(self):
self = func(self)
</code></pre>
<p>The object is retrieved from a database.</p>
| 11 | 2009-08-01T10:42:21Z | 18,529,310 | <p>It is not a direct answer to the question, but in the posts below there's a solution for what amirouche tried to do:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/2153295/python-object-conversion">Python object conversion</a></li>
<li><a href="http://stackoverflow.com/questions/8062161/can-i-dynamically-convert-an-instance-of-one-class-to-anotheramirouche">Can I dynamically convert an instance of one class to another?</a></li>
</ul>
<p>And here's working code sample (Python 3.2.5).</p>
<pre><code>class Men:
def __init__(self, name):
self.name = name
def who_are_you(self):
print("I'm a men! My name is " + self.name)
def cast_to(self, sex, name):
self.__class__ = sex
self.name = name
def method_unique_to_men(self):
print('I made The Matrix')
class Women:
def __init__(self, name):
self.name = name
def who_are_you(self):
print("I'm a women! My name is " + self.name)
def method_unique_to_women(self):
print('I made Cloud Atlas')
men = Men('Larry')
men.who_are_you()
#>>> I'm a men! My name is Larry
men.method_unique_to_men()
#>>> I made The Matrix
men.cast_to(Women, 'Lana')
men.who_are_you()
#>>> I'm a women! My name is Lana
men.method_unique_to_women()
#>>> I made Cloud Atlas
</code></pre>
<p>Note the <code>self.__class__</code> and not <code>self.__class__.__name__</code>. I.e. this technique not only replaces class name, but actually converts an instance of a class (at least both of them have same <code>id()</code>). Also, 1) I don't know whether it is "safe to replace a self object by another object of the same type in [an object own] method"; 2) it works with different types of objects, not only with ones that are of the same type; 3) it works not exactly like amirouche wanted: you can't init class like <code>Class(args)</code>, only <code>Class()</code> (I'm not a pro and can't answer why it's like this).</p>
| 5 | 2013-08-30T09:20:57Z | [
"python"
] |
Is it safe to replace a self object by another object of the same type in a method? | 1,216,356 | <p>I would like to replace an object instance by another instance inside a method like this:</p>
<pre><code>class A:
def method1(self):
self = func(self)
</code></pre>
<p>The object is retrieved from a database.</p>
| 11 | 2009-08-01T10:42:21Z | 19,023,873 | <p>One can use the self assignment in a method, to change the class of instance to a derived class. </p>
<p>Of course one could assign it to a new object, but then the use of the new object ripples through the rest of code in the method. Reassiging it to self, leaves the rest of the method untouched.</p>
<pre><code>class aclass:
def methodA(self):
...
if condition:
self = replace_by_derived(self)
# self is now referencing to an instance of a derived class
# with probably the same values for its data attributes
# all code here remains untouched
...
self.methodB() # calls the methodB of derivedclass is condition is True
...
def methodB(self):
# methodB of class aclass
...
class derivedclass(aclass):
def methodB(self):
#methodB of class derivedclass
...
</code></pre>
<p>But apart from such a special use case, I don't see any advantages to replace self.</p>
| 0 | 2013-09-26T09:06:57Z | [
"python"
] |
Is it safe to replace a self object by another object of the same type in a method? | 1,216,356 | <p>I would like to replace an object instance by another instance inside a method like this:</p>
<pre><code>class A:
def method1(self):
self = func(self)
</code></pre>
<p>The object is retrieved from a database.</p>
| 11 | 2009-08-01T10:42:21Z | 37,658,673 | <p>As far as i understand, If you are trying to replace the current object with another object of same type (assuming func wont change the object type) from an member function. I think this will achieve that</p>
<pre><code>class A:
def method1(self):
newObj = func(self)
self.__dict__.update(newObj.__dict__)
</code></pre>
| 2 | 2016-06-06T13:23:48Z | [
"python"
] |
Newbie to python conventions, is my code on the right track? | 1,216,395 | <p>I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)</p>
<pre><code>#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
</code></pre>
| 1 | 2009-08-01T11:07:55Z | 1,216,413 | <p>There's probably a more efficient way to do this using lists and pairs instead of separate variables for each bracket's limit and rate. For instance, consider the following:</p>
<pre><code># List of (upper-limit, rate) pairs for brackets.
brackets = [ (8350, .10), (33950, .15), (82250, .25), (171550, .28), (372950, .33) ]
if __name__ == '__main__':
salary = float(raw_input("Enter your salary\n"))
accounted_for = 0 # Running total of the portion of salary already taxed
taxed = 0 # Running total of tax from portion of salary already examined
for (limit, rate) in brackets:
if salary < limit:
taxed += ( (salary - accounted_for) * rate )
accounted_for = salary
break # We've found the highest tax bracket we need to bother with
else:
taxed += ( (limit - accounted_for) * rate )
accounted_for = limit
# If we went over the max defined tax bracket, use the final rate
if accounted_for < salary:
taxed += ( (salary - accounted_for) * 0.35 )
print taxed
</code></pre>
<p>The idea is that we don't want to repeat code we don't have to just because we have multiple items of similar data to work with. Tax brackets all function the same, aside from differing rates and limits, so we want those to act as inputs to a standard computation as opposed to their own individual functions.</p>
| 13 | 2009-08-01T11:23:11Z | [
"python",
"conventions"
] |
Newbie to python conventions, is my code on the right track? | 1,216,395 | <p>I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)</p>
<pre><code>#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
</code></pre>
| 1 | 2009-08-01T11:07:55Z | 1,216,500 | <p>4 space indenting! Check out this <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">doc</a>, and the <pre><code>import this</code></pre> output for more. Looks pretty good to me though, very easy to read. </p>
| 2 | 2009-08-01T12:14:14Z | [
"python",
"conventions"
] |
Newbie to python conventions, is my code on the right track? | 1,216,395 | <p>I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)</p>
<pre><code>#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
</code></pre>
| 1 | 2009-08-01T11:07:55Z | 1,216,519 | <p>You can change lines like this:</p>
<pre><code>if salary >= 0 and salary <= first_bracket:
</code></pre>
<p>to this:</p>
<pre><code>if 0 <= salary <= first_bracket:
</code></pre>
<p>like you'd do in mathematics. It generally makes the code more readable.</p>
| 2 | 2009-08-01T12:26:13Z | [
"python",
"conventions"
] |
Newbie to python conventions, is my code on the right track? | 1,216,395 | <p>I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)</p>
<pre><code>#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
</code></pre>
| 1 | 2009-08-01T11:07:55Z | 1,216,526 | <p>Tools like <a href="http://www.logilab.org/857" rel="nofollow">PyLint</a> can catch a lot of errors and bad practices, including bad naming conventions. <a href="http://pychecker.sourceforge.net/" rel="nofollow">PyChecker</a> is nice too.</p>
| 0 | 2009-08-01T12:35:02Z | [
"python",
"conventions"
] |
Newbie to python conventions, is my code on the right track? | 1,216,395 | <p>I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)</p>
<pre><code>#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
</code></pre>
| 1 | 2009-08-01T11:07:55Z | 1,216,737 | <p>Particularly when working with financial values, you should consider using the <a href="http://docs.python.org/library/decimal.html" rel="nofollow">decimal</a> module to make sure that there are no floating-point errors in your output.</p>
<p>Not a big deal when you're just making a toy to learn a language, but good to know for future reference :)</p>
| 5 | 2009-08-01T14:49:24Z | [
"python",
"conventions"
] |
Newbie to python conventions, is my code on the right track? | 1,216,395 | <p>I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)</p>
<pre><code>#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
</code></pre>
| 1 | 2009-08-01T11:07:55Z | 1,216,804 | <p>Since those functions are fairly simple you could do something like:</p>
<pre><code>def b1(a):
return a * .10
</code></pre>
<p>you could also make one unified taxing function:</p>
<pre><code>def tax_me(salary, rate):
return salary * rate
</code></pre>
<p>Seems like Dav has ya fixed up pretty good :)</p>
<p>Have fun with Python, its a great language.</p>
| 1 | 2009-08-01T15:20:47Z | [
"python",
"conventions"
] |
Newbie to python conventions, is my code on the right track? | 1,216,395 | <p>I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?)</p>
<pre><code>#There are six brackets define by the IRS as of 2009
#Schedule X - Single
first_bracket = 8350
second_bracket = 33950
third_bracket = 82250
fourth_bracket = 171550
fifth_bracket = 372950
def b1(a):
a = a * .10
return a
def b2(a):
a = a * .15
return a
def b3(a):
a = a * .25
return a
def b4(a):
a = a * .28
return a
def b5(a):
a = a * .33
return a
def b6(a):
a = a * .35
return a
if __name__ == '__main__': #importing is fun
#Ask for salary
salary = float(raw_input("Enter your salary\n"))
#First bracket
if salary >= 0 and salary <= first_bracket:
taxed = b1(salary)
#print "You make less than $", float(first_bracket), "so your tax is $", taxed
print taxed
#Second bracket
elif salary > first_bracket and salary <= second_bracket:
taxed = b1(first_bracket) + b2(salary-first_bracket)
#print "You make between $", first_bracket+1, "and $", second_bracket, "so your tax is $", taxed
print taxed
#Thrid bracket
elif salary > second_bracket and salary <= third_bracket:
taxed = b1(first_bracket) + b2(second_bracket-first_bracket) + b3(salary-second_bracket)
print taxed
</code></pre>
| 1 | 2009-08-01T11:07:55Z | 1,217,465 | <p>Structuring the income and tax-rate data as a table (list of tuples or tuple of tuples) is a huge improvement. As shown in that example it allows one to approach the rest of the task with a table driven approach (traverse up the table to find the top rate for a given salary, then traverse from that point downward accumulating taxes and accounting for the total salary).</p>
<p>To make all of this my "Pythonic" we'd define the functionality as well as the tax rate table above the <code>if __name__==</code> line. This would implicitly allow us to import our file into any other code and use that functionary.</p>
<p>The part below the <code>if __name__ ==</code> line is then a driver which calls the functionality with any input given (or can be used to hold unit tests, so that any module can be called on to test it's own functionality).</p>
<p>So our code could look something like:</p>
<p><code>#!/usr/bin/env python</code><br>
<code>tax_table = (</code><br>
<code> (8350, 0.10),</code><br>
<code> ...</code><br>
<code> )</code><br>
<br>
<code>def compute(salary):</code><br>
<code> '''Compute taxes for a given salary'''</code><br>
<code> result = 0 </code><br>
<code> accounted_for = 0</code><br>
<code> ...</code><br>
<code> return result</code><br>
<br>
<code>if __name__ == "__main__":</code><br>
<code> import sys</code><br>
<code> try:</code><br>
<code> sal = float(raw_input("Please enter salary: ")</code><br>
<code> except EnvironmentError, err:</code><br>
<code> print >> sys.stderr, "Error with your input, aborting"</code><br>
<code> print >> sys.stderr, "The error was:", err</code><br>
<code> sys.exit(1)</code><br>
<code> print compute(sal)</code><br>
<br></p>
<p>Notice that we've now separated reusable functionality from our usage ... which allows us to re-use the code ... but also facilitates test-driven development and refactoring. We can write non-interactive test suites using our same API (so far just a call to the <strong>compute()</strong> function) and this will allow us to refactor with confidence (and without touching our usage below --- which is our "application" in this case).</p>
<p>It's not clear that this particular code would benefit from being refactored into one or more classes. Certainly the ability to instantiate a class with a different tax table would be handy. Then the tax rate could be stored elsewhere (read from a file, pulled off a web server, or queried out of a database; Python make all of those almost equally easy).</p>
<p>However, we don't have to go "OO" to add that functionality to our <strong>compute()</strong> function.</p>
<p>We could add an optional parameter to the compute function such that it would use a different tax rate table if we provide one, or default to the one we've hard-coded into the module. For that we simple change the initial function definition line to: <code>def compute(salary, table=tax_table):</code> ... and we fix up some handling for the upper limit (factoring the 0.35 rate out of the function and into the table, with either "sys.maxint" as our limit or the "None" object).</p>
<p>For such a simple exercise it's not worth much worry. But in general it's best to put significant effort into defining our desired APIs up front. If you can come up with a robust, flexible API then any conforming implementation that meets your initial requirements (correctness and acceptable performance) will allow you to deliver your application.</p>
<p>More importantly you can then re-implement at will. Perhaps a really complex tax table needs to be searched using something like the <strong>bisect</strong> module because the linear searches take too long to find the top tax rate, or some sorts of income tax credits and deductions or number of dependents need to be passed into the <strong>compute()</strong> function, etc.
Ideally such changes can be done transparently. None of your existing usage should have to change because you've done a re-implemented the internals of our module. Even when you've added functionality you shouldn't need to worry about your existing usage (optional parameters and "key word" arguments (dictionaries passed after optional arguments) let us do that for functions, and classes can add attributes and methods without disturbing any proper existing usage. (Yes, it's possible for subclassing usage to be broken by some changes; but that should not usually be a problem).</p>
<p>In Python one can write something as a simple Python module, later re-implement it as a package or re-impement it as a compiled C module or as a package containing some C modules ... all without affecting the usage. From the user's perspective the <strong>import</strong> statement works identically on Python modules, packages, and compiled modules ("shared objects" or DLLs).</p>
<p>Historically this has been a huge advantage to Python in its own development. They've been able to add considerable functionality to existing libraries and only rarely been forced through "deprecate/rename" contortions. Quite a bit of the functionality slated for Python 3.0 was able to be added to Python 2.7 for this reason.</p>
| 1 | 2009-08-01T20:50:45Z | [
"python",
"conventions"
] |
Make python __doc__ property display correctly in a Windows CMD window? | 1,216,697 | <p>In Windows, if I open a command prompt, start python, and inspect something using its __doc__ property, it doesn't display correctly. Instead of the lines being separated, I see one continuous string with the newline character every once and a while.</p>
<p>Is there a way to make it appear correctly?</p>
<p>Here's an example of what I see:</p>
<p>>>> hashlib.__doc__</p>
<p>'hashlib module - A common interface to many hash functions.\n\nnew(name, string=\'\') - returns a n
ew hash object implementing the\n given hash function; initializing the hash\n
using the given string data.\n\nNamed constructor functions are also availabl
e, these are much faster\nthan using new():\n\nmd5(), sha1(), sha224(), sha256(), sha384(), and sha5
12()\n\nMore algorithms may be available on your platform but the above are\nguaranteed to exist.\n\
nNOTE: If you want the adler32 or crc32 hash functions they are available in\nthe zlib module.\n\nCh</p>
| 1 | 2009-08-01T14:18:10Z | 1,216,700 | <p>try</p>
<pre><code>>>> print hashlib.__doc__
</code></pre>
<p>or (v3)</p>
<pre><code>>>> print(hashlib.__doc__)
</code></pre>
| 3 | 2009-08-01T14:20:26Z | [
"python",
"documentation"
] |
Make python __doc__ property display correctly in a Windows CMD window? | 1,216,697 | <p>In Windows, if I open a command prompt, start python, and inspect something using its __doc__ property, it doesn't display correctly. Instead of the lines being separated, I see one continuous string with the newline character every once and a while.</p>
<p>Is there a way to make it appear correctly?</p>
<p>Here's an example of what I see:</p>
<p>>>> hashlib.__doc__</p>
<p>'hashlib module - A common interface to many hash functions.\n\nnew(name, string=\'\') - returns a n
ew hash object implementing the\n given hash function; initializing the hash\n
using the given string data.\n\nNamed constructor functions are also availabl
e, these are much faster\nthan using new():\n\nmd5(), sha1(), sha224(), sha256(), sha384(), and sha5
12()\n\nMore algorithms may be available on your platform but the above are\nguaranteed to exist.\n\
nNOTE: If you want the adler32 or crc32 hash functions they are available in\nthe zlib module.\n\nCh</p>
| 1 | 2009-08-01T14:18:10Z | 1,217,015 | <p>Rather than pulling <code>__doc__</code> yourself, try this:</p>
<pre><code>>>> help(hashlib)
</code></pre>
<p>It will give you a nicely formatted summary of the module, including (but not limited to) the docstring.</p>
| 5 | 2009-08-01T17:00:40Z | [
"python",
"documentation"
] |
Make python __doc__ property display correctly in a Windows CMD window? | 1,216,697 | <p>In Windows, if I open a command prompt, start python, and inspect something using its __doc__ property, it doesn't display correctly. Instead of the lines being separated, I see one continuous string with the newline character every once and a while.</p>
<p>Is there a way to make it appear correctly?</p>
<p>Here's an example of what I see:</p>
<p>>>> hashlib.__doc__</p>
<p>'hashlib module - A common interface to many hash functions.\n\nnew(name, string=\'\') - returns a n
ew hash object implementing the\n given hash function; initializing the hash\n
using the given string data.\n\nNamed constructor functions are also availabl
e, these are much faster\nthan using new():\n\nmd5(), sha1(), sha224(), sha256(), sha384(), and sha5
12()\n\nMore algorithms may be available on your platform but the above are\nguaranteed to exist.\n\
nNOTE: If you want the adler32 or crc32 hash functions they are available in\nthe zlib module.\n\nCh</p>
| 1 | 2009-08-01T14:18:10Z | 18,709,639 | <pre><code>def help_(obj):
if type(obj).__name__ == 'ufunc':
print obj.__doc__
else:
help(obj)
</code></pre>
| 0 | 2013-09-10T01:58:33Z | [
"python",
"documentation"
] |
Python subprocess.Popen erroring with OSError: [Errno 12] Cannot allocate memory after period of time | 1,216,794 | <p><strong>Note</strong>: This question has been re-asked with a summary of all debugging attempts <a href="http://stackoverflow.com/questions/1367373/python-subprocess-popen-oserror-errno-12-cannot-allocate-memory">here</a>.</p>
<p><hr /></p>
<p>I have a Python script that is running as a background process executing every 60 seconds. Part of that is a call to <a href="http://docs.python.org/library/subprocess.html">subprocess.Popen</a> to get the output of <a href="http://linuxcommand.org/man%5Fpages/ps1.html">ps</a>. </p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>After running for a few days, the call is erroring with:</p>
<pre>
File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</pre>
<p>However the output of <a href="http://www.linuxcommand.org/man%5Fpages/free1.html">free</a> on the server is:</p>
<pre>
$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</pre>
<p>I have searched around for the problem and found <a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">this article</a> which says:</p>
<p>Solution is to add more swap space to your server. When the kernel is forking to start the modeler or discovery process, it first ensures there's enough space available on the swap store the new process if needed.</p>
<p>I note that there is no available swap from the free output above. Is this likely to be the problem and/or what other solutions might there be?</p>
<p><strong>Update 13th Aug 09</strong> The code above is called every 60 seconds as part of a series of monitoring functions. The process is daemonized and the check is scheduled using <a href="http://docs.python.org/library/sched.html">sched</a>. The specific code for the above function is:</p>
<pre><code>def getProcesses(self):
self.checksLogger.debug('getProcesses: start')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory before Popen - ' + str(mem))
# Get output from ps
try:
self.checksLogger.debug('getProcesses: attempting Popen')
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
except Exception, e:
import traceback
self.checksLogger.error('getProcesses: exception = ' + traceback.format_exc())
return False
self.checksLogger.debug('getProcesses: Popen success, parsing')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory after Popen - ' + str(mem))
# Split out each process
processLines = ps.split('\n')
del processLines[0] # Removes the headers
processLines.pop() # Removes a trailing empty line
processes = []
self.checksLogger.debug('getProcesses: Popen success, parsing, looping')
for line in processLines:
line = line.split(None, 10)
processes.append(line)
self.checksLogger.debug('getProcesses: completed, returning')
return processes
</code></pre>
<p>This is part of a bigger class called checks which is initialised once when the daemon is started.</p>
<p>The entire checks class can be found at <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
| 8 | 2009-08-01T15:14:30Z | 1,216,824 | <p>You might want to actually wait for all of those PS processes to finish before adding swap space.</p>
<p>It's not at all clear what "running as a background process executing every 60 seconds" means.</p>
<p>But your call to subprocess.Popen is forking a new process each time. </p>
<p><strong>Update</strong>.</p>
<p>I'd guess that you're somehow leaving all those processes running or hung in a zombie state. However, the <code>communicate</code> method <em>should</em> clean up the spawned subprocesses.</p>
| 1 | 2009-08-01T15:29:39Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen erroring with OSError: [Errno 12] Cannot allocate memory after period of time | 1,216,794 | <p><strong>Note</strong>: This question has been re-asked with a summary of all debugging attempts <a href="http://stackoverflow.com/questions/1367373/python-subprocess-popen-oserror-errno-12-cannot-allocate-memory">here</a>.</p>
<p><hr /></p>
<p>I have a Python script that is running as a background process executing every 60 seconds. Part of that is a call to <a href="http://docs.python.org/library/subprocess.html">subprocess.Popen</a> to get the output of <a href="http://linuxcommand.org/man%5Fpages/ps1.html">ps</a>. </p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>After running for a few days, the call is erroring with:</p>
<pre>
File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</pre>
<p>However the output of <a href="http://www.linuxcommand.org/man%5Fpages/free1.html">free</a> on the server is:</p>
<pre>
$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</pre>
<p>I have searched around for the problem and found <a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">this article</a> which says:</p>
<p>Solution is to add more swap space to your server. When the kernel is forking to start the modeler or discovery process, it first ensures there's enough space available on the swap store the new process if needed.</p>
<p>I note that there is no available swap from the free output above. Is this likely to be the problem and/or what other solutions might there be?</p>
<p><strong>Update 13th Aug 09</strong> The code above is called every 60 seconds as part of a series of monitoring functions. The process is daemonized and the check is scheduled using <a href="http://docs.python.org/library/sched.html">sched</a>. The specific code for the above function is:</p>
<pre><code>def getProcesses(self):
self.checksLogger.debug('getProcesses: start')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory before Popen - ' + str(mem))
# Get output from ps
try:
self.checksLogger.debug('getProcesses: attempting Popen')
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
except Exception, e:
import traceback
self.checksLogger.error('getProcesses: exception = ' + traceback.format_exc())
return False
self.checksLogger.debug('getProcesses: Popen success, parsing')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory after Popen - ' + str(mem))
# Split out each process
processLines = ps.split('\n')
del processLines[0] # Removes the headers
processLines.pop() # Removes a trailing empty line
processes = []
self.checksLogger.debug('getProcesses: Popen success, parsing, looping')
for line in processLines:
line = line.split(None, 10)
processes.append(line)
self.checksLogger.debug('getProcesses: completed, returning')
return processes
</code></pre>
<p>This is part of a bigger class called checks which is initialised once when the daemon is started.</p>
<p>The entire checks class can be found at <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
| 8 | 2009-08-01T15:14:30Z | 1,216,917 | <p>I don't think that the circumstances given in the Zenoss article you linked to is the only cause of this message, so it's not clear yet that swap space is definitely the problem. I would advise logging some more information even around successful calls, so that you can see the state of free memory every time just before you do the <code>ps</code> call.</p>
<p>One more thing - if you specify <code>shell=True</code> in the Popen call, do you see different behaviour?</p>
<p><strong>Update:</strong> If not memory, the next possible culprit is indeed file handles. I would advise running the failing command under <a href="http://en.wikipedia.org/wiki/Strace" rel="nofollow"><code>strace</code></a> to see exactly which system calls are failing.</p>
| 0 | 2009-08-01T16:15:44Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen erroring with OSError: [Errno 12] Cannot allocate memory after period of time | 1,216,794 | <p><strong>Note</strong>: This question has been re-asked with a summary of all debugging attempts <a href="http://stackoverflow.com/questions/1367373/python-subprocess-popen-oserror-errno-12-cannot-allocate-memory">here</a>.</p>
<p><hr /></p>
<p>I have a Python script that is running as a background process executing every 60 seconds. Part of that is a call to <a href="http://docs.python.org/library/subprocess.html">subprocess.Popen</a> to get the output of <a href="http://linuxcommand.org/man%5Fpages/ps1.html">ps</a>. </p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>After running for a few days, the call is erroring with:</p>
<pre>
File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</pre>
<p>However the output of <a href="http://www.linuxcommand.org/man%5Fpages/free1.html">free</a> on the server is:</p>
<pre>
$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</pre>
<p>I have searched around for the problem and found <a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">this article</a> which says:</p>
<p>Solution is to add more swap space to your server. When the kernel is forking to start the modeler or discovery process, it first ensures there's enough space available on the swap store the new process if needed.</p>
<p>I note that there is no available swap from the free output above. Is this likely to be the problem and/or what other solutions might there be?</p>
<p><strong>Update 13th Aug 09</strong> The code above is called every 60 seconds as part of a series of monitoring functions. The process is daemonized and the check is scheduled using <a href="http://docs.python.org/library/sched.html">sched</a>. The specific code for the above function is:</p>
<pre><code>def getProcesses(self):
self.checksLogger.debug('getProcesses: start')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory before Popen - ' + str(mem))
# Get output from ps
try:
self.checksLogger.debug('getProcesses: attempting Popen')
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
except Exception, e:
import traceback
self.checksLogger.error('getProcesses: exception = ' + traceback.format_exc())
return False
self.checksLogger.debug('getProcesses: Popen success, parsing')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory after Popen - ' + str(mem))
# Split out each process
processLines = ps.split('\n')
del processLines[0] # Removes the headers
processLines.pop() # Removes a trailing empty line
processes = []
self.checksLogger.debug('getProcesses: Popen success, parsing, looping')
for line in processLines:
line = line.split(None, 10)
processes.append(line)
self.checksLogger.debug('getProcesses: completed, returning')
return processes
</code></pre>
<p>This is part of a bigger class called checks which is initialised once when the daemon is started.</p>
<p>The entire checks class can be found at <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
| 8 | 2009-08-01T15:14:30Z | 1,269,829 | <p>Have you watched your process over time? </p>
<ul>
<li>lsof </li>
<li>ps -aux | grep -i pname </li>
<li>top</li>
</ul>
<p>All should give interesting information. I am thinking that the process is tying up resources that should be freed up. Is there a chance that it is tying up resource handles (memory blocks, streams, file handles, thread or process handles)? stdin, stdout, stderr from the spawned "ps". Memory handles, ... from many small incremental allocations. I would be very interested in seeing what the above commands display for your process when it has just finished launching and running for the first time and after 24 hours of "sitting" there launching the sub-process regularly.</p>
<p>Since it dies after a few days, you could have it run for only a few loops, and then restart it once a day as a workaround. That would help you in the meantime.</p>
<p>Jacob</p>
| 0 | 2009-08-13T03:08:51Z | [
"python",
"linux",
"memory"
] |
Python subprocess.Popen erroring with OSError: [Errno 12] Cannot allocate memory after period of time | 1,216,794 | <p><strong>Note</strong>: This question has been re-asked with a summary of all debugging attempts <a href="http://stackoverflow.com/questions/1367373/python-subprocess-popen-oserror-errno-12-cannot-allocate-memory">here</a>.</p>
<p><hr /></p>
<p>I have a Python script that is running as a background process executing every 60 seconds. Part of that is a call to <a href="http://docs.python.org/library/subprocess.html">subprocess.Popen</a> to get the output of <a href="http://linuxcommand.org/man%5Fpages/ps1.html">ps</a>. </p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
</code></pre>
<p>After running for a few days, the call is erroring with:</p>
<pre>
File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory
</pre>
<p>However the output of <a href="http://www.linuxcommand.org/man%5Fpages/free1.html">free</a> on the server is:</p>
<pre>
$ free -m
total used free shared buffers cached
Mem: 894 345 549 0 0 0
-/+ buffers/cache: 345 549
Swap: 0 0 0
</pre>
<p>I have searched around for the problem and found <a href="http://www.zenoss.com/community/wiki/common-error-messages-and-solutions/oserror-errno-12-cannot-allocate-memory-in-popen2.py/">this article</a> which says:</p>
<p>Solution is to add more swap space to your server. When the kernel is forking to start the modeler or discovery process, it first ensures there's enough space available on the swap store the new process if needed.</p>
<p>I note that there is no available swap from the free output above. Is this likely to be the problem and/or what other solutions might there be?</p>
<p><strong>Update 13th Aug 09</strong> The code above is called every 60 seconds as part of a series of monitoring functions. The process is daemonized and the check is scheduled using <a href="http://docs.python.org/library/sched.html">sched</a>. The specific code for the above function is:</p>
<pre><code>def getProcesses(self):
self.checksLogger.debug('getProcesses: start')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory before Popen - ' + str(mem))
# Get output from ps
try:
self.checksLogger.debug('getProcesses: attempting Popen')
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
except Exception, e:
import traceback
self.checksLogger.error('getProcesses: exception = ' + traceback.format_exc())
return False
self.checksLogger.debug('getProcesses: Popen success, parsing')
# Memory logging (case 27152)
if self.agentConfig['debugMode'] and sys.platform == 'linux2':
mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
self.checksLogger.debug('getProcesses: memory after Popen - ' + str(mem))
# Split out each process
processLines = ps.split('\n')
del processLines[0] # Removes the headers
processLines.pop() # Removes a trailing empty line
processes = []
self.checksLogger.debug('getProcesses: Popen success, parsing, looping')
for line in processLines:
line = line.split(None, 10)
processes.append(line)
self.checksLogger.debug('getProcesses: completed, returning')
return processes
</code></pre>
<p>This is part of a bigger class called checks which is initialised once when the daemon is started.</p>
<p>The entire checks class can be found at <a href="http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py">http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py</a> with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.</p>
| 8 | 2009-08-01T15:14:30Z | 1,270,171 | <p>That swap space answer is bogus. Historically Unix systems wanted swap space available like that, but they don't work that way anymore (and Linux never worked that way). You're not even close to running out of memory, so that's not likely the actual problem - you're running out of some other limited resource.</p>
<p>Given where the error is occuring (_get_handles calls os.pipe() to create pipes to the child), the only real problem you could be running into is not enough free file descriptors. I would instead look for unclosed files (lsof -p on the PID of the process doing the popen). If your program really needs to keep a lot of files open at one time, then increase the user limit and/or the system limit for open file descriptors.</p>
| 3 | 2009-08-13T05:30:15Z | [
"python",
"linux",
"memory"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.