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
sequence |
---|---|---|---|---|---|---|---|---|---|
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 9,155,056 | <p>All the answers (or: the same answer repeated over and over) are inadequate. What you want to do is this:</p>
<pre><code>from setuptools.command.easy_install import easy_install
class easy_install_default(easy_install):
""" class easy_install had problems with the fist parameter not being
an instance of Distribution, even though it was. This is due to
some import-related mess.
"""
def __init__(self):
from distutils.dist import Distribution
dist = Distribution()
self.distribution = dist
self.initialize_options()
self._dry_run = None
self.verbose = dist.verbose
self.force = None
self.help = 0
self.finalized = 0
e = easy_install_default()
import distutils.errors
try:
e.finalize_options()
except distutils.errors.DistutilsError:
pass
print e.install_dir
</code></pre>
<p>The final line shows you the installation dir. Works on Ubuntu, whereas the above ones don't. Don't ask me about windows or other dists, but since it's the exact same dir that easy_install uses by default, it's probably correct everywhere where easy_install works (so, everywhere, even macs). Have fun. Note: original code has many swearwords in it.</p>
| 13 | 2012-02-06T02:40:22Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 9,946,505 | <p>This works for me.
It will get you both dist-packages and site-packages folders.
If the folder is not on Python's path, it won't be
doing you much good anyway.</p>
<pre><code>import sys;
print [f for f in sys.path if f.endswith('packages')]
</code></pre>
<p>Output (Ubuntu installation):</p>
<pre><code>['/home/username/.local/lib/python2.7/site-packages',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']
</code></pre>
| 5 | 2012-03-30T16:01:24Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 10,694,208 | <p>This is what worked for me:</p>
<pre><code>python -m site --user-site
</code></pre>
| 33 | 2012-05-22T00:08:55Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 12,950,101 | <pre><code>>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
</code></pre>
<p>(or just first item with <code>site.getsitepackages()[0]</code>)</p>
| 404 | 2012-10-18T08:19:45Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 18,130,809 | <p>The native system packages installed with python installation can be found at :</p>
<blockquote>
<p>/usr/lib/python2.7/dist-packages/</p>
</blockquote>
<p>by using this small code :</p>
<pre><code>from distutils.sysconfig import get_python_lib
print get_python_lib()
</code></pre>
<p>However, the list of packages installed via <code>pip</code> can be found at :</p>
<blockquote>
<p>/usr/local/bin/</p>
</blockquote>
<p>Or one can simply write the following command to list all paths where python packages are.</p>
<pre><code>>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']
</code></pre>
| 8 | 2013-08-08T16:05:17Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 29,062,571 | <p>This should work on all distributions in and out of virtual environment due to it's "low-tech" nature. The os module always resides in the parent directory of 'site-packages'</p>
<pre><code>import os; print os.path.dirname(os.__file__) + '/site-packages'
</code></pre>
<p>To change dir to the site-packages dir I use the following alias (on *nix systems):</p>
<pre><code>alias cdsp='cd $(python -c "import os; print os.path.dirname(os.__file__)"); cd site-packages'
</code></pre>
| 3 | 2015-03-15T15:43:40Z | [
"python",
"installation"
] |
How do I find the location of my Python site-packages directory? | 122,327 | <p>How do I find the location of my site-packages directory?</p>
| 396 | 2008-09-23T17:04:43Z | 38,432,782 | <p>Answer to old question. But use ipython for this. </p>
<pre><code>pip install ipython
ipython
import imaplib
imaplib?
</code></pre>
<p>This will give the following output about imaplib package -</p>
<pre><code>Type: module
String form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>
File: /usr/lib/python2.7/imaplib.py
Docstring:
IMAP4 client.
Based on RFC 2060.
Public class: IMAP4
Public variable: Debug
Public functions: Internaldate2tuple
Int2AP
ParseFlags
Time2Internaldate
</code></pre>
| 1 | 2016-07-18T09:12:47Z | [
"python",
"installation"
] |
Is there an Eclipse add-on to build a python executable for distribution? | 122,524 | <p>I want to build an executable to distribute to people without python installed on their machines. </p>
<p>Is there an add-on to Eclipse that allows this? I couldn't find one. </p>
<p>If not, do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse, and bundle it all up? </p>
<p>Thanks,
Mark</p>
| 2 | 2008-09-23T17:39:32Z | 122,590 | <p>It's not eclipse, but ActiveState's <a href="http://docs.activestate.com/activepython/2.5/faq/windows/index.html#where-is-freeze-for-windows" rel="nofollow">ActivePython FAQ</a> mentions the freeze utility, which sounds like it might be close to what you're asking for.</p>
| 1 | 2008-09-23T17:50:47Z | [
"python",
"eclipse",
"bytecode"
] |
Is there an Eclipse add-on to build a python executable for distribution? | 122,524 | <p>I want to build an executable to distribute to people without python installed on their machines. </p>
<p>Is there an add-on to Eclipse that allows this? I couldn't find one. </p>
<p>If not, do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse, and bundle it all up? </p>
<p>Thanks,
Mark</p>
| 2 | 2008-09-23T17:39:32Z | 123,077 | <p>For Windows, there's the <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> project.</p>
<p>There's <a href="http://systemexit.de/bbfreeze/README.html" rel="nofollow">bbfreeze</a>, and <a href="http://pyinstaller.python-hosting.com/" rel="nofollow">PyInstaller</a>, and <a href="http://www.undefined.org/python/" rel="nofollow">py2app</a>, also.</p>
| 1 | 2008-09-23T19:04:16Z | [
"python",
"eclipse",
"bytecode"
] |
Is there an Eclipse add-on to build a python executable for distribution? | 122,524 | <p>I want to build an executable to distribute to people without python installed on their machines. </p>
<p>Is there an add-on to Eclipse that allows this? I couldn't find one. </p>
<p>If not, do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse, and bundle it all up? </p>
<p>Thanks,
Mark</p>
| 2 | 2008-09-23T17:39:32Z | 123,990 | <p><a href="http://stackoverflow.com/questions/2933/an-executable-python-app">See</a> <a href="http://stackoverflow.com/questions/106725/how-to-bundle-a-python-application-including-dependencies-for-windows">these</a> <a href="http://stackoverflow.com/questions/116657/how-do-you-create-an-osx-applicationdmg-from-a-python-package">questions</a></p>
| 1 | 2008-09-23T21:23:46Z | [
"python",
"eclipse",
"bytecode"
] |
Is there an Eclipse add-on to build a python executable for distribution? | 122,524 | <p>I want to build an executable to distribute to people without python installed on their machines. </p>
<p>Is there an add-on to Eclipse that allows this? I couldn't find one. </p>
<p>If not, do you have a builder that you recommend that would make it easy to go to my python project directory created in Eclipse, and bundle it all up? </p>
<p>Thanks,
Mark</p>
| 2 | 2008-09-23T17:39:32Z | 12,812,574 | <p>There is also PyInstaller:
<a href="http://www.pyinstaller.org/" rel="nofollow">http://www.pyinstaller.org/</a></p>
| 0 | 2012-10-10T05:34:45Z | [
"python",
"eclipse",
"bytecode"
] |
Need to create a layered dict from a flat one | 122,763 | <p>I have a dict, that looks like this:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
</code></pre>
<p>And I need to get it to look like:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
'bar': {
'opt3': 3,
'opt4': 4,
'baz': {
'opt5': 5,
'opt6': 6,
}
}
}
}
</code></pre>
<p>I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.</p>
| 6 | 2008-09-23T18:19:25Z | 122,785 | <p>Like this:</p>
<pre><code>def nest(d):
rv = {}
for key, value in d.iteritems():
node = rv
for part in key.split('/'):
node = node.setdefault(part, {})
node.update(value)
return rv
</code></pre>
| 8 | 2008-09-23T18:23:31Z | [
"python",
"algorithm",
"performance"
] |
Need to create a layered dict from a flat one | 122,763 | <p>I have a dict, that looks like this:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
</code></pre>
<p>And I need to get it to look like:</p>
<pre><code>{
'foo': {
'opt1': 1,
'opt2': 2,
'bar': {
'opt3': 3,
'opt4': 4,
'baz': {
'opt5': 5,
'opt6': 6,
}
}
}
}
</code></pre>
<p>I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.</p>
| 6 | 2008-09-23T18:19:25Z | 122,812 | <pre><code>def layer(dict):
for k,v in dict:
if '/' in k:
del dict[k]
subdict = dict.get(k[:k.find('/')],{})
subdict[k[k.find('/')+1:]] = v
layer(subdict)
</code></pre>
| 1 | 2008-09-23T18:25:51Z | [
"python",
"algorithm",
"performance"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 123,212 | <p><a href="http://docs.python.org/2/library/shutil.html"><code>shutil</code></a> has many methods you can use. One of which is:</p>
<pre><code>from shutil import copyfile
copyfile(src, dst)
</code></pre>
<p>Copy the contents of the file named <code>src</code> to a file named <code>dst</code>. The destination location must be writable; otherwise, an <code>IOError</code> exception will be raised. If <code>dst</code> already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. <code>src</code> and <code>dst</code> are path names given as strings. </p>
| 964 | 2008-09-23T19:25:35Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 123,217 | <p><a href="https://docs.python.org/library/shutil.html" rel="nofollow">shutil</a> may have what youâre looking for.</p>
| 6 | 2008-09-23T19:25:51Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 123,225 | <p>Look at module <strong>shutil</strong>.
It contains function <strong>copyfile</strong>(<em>src</em>, <em>dst</em>) </p>
| 9 | 2008-09-23T19:27:07Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 123,226 | <p>Use the <a href="https://docs.python.org/3/library/shutil.html">shutil module</a>.</p>
<pre><code>copyfile(src, dst)
</code></pre>
<p>Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function. src and dst are path names given as strings.</p>
<p>Take a look at <a href="https://docs.python.org/3/library/filesys.html">filesys</a> for all the file and directory handling functions available in standard Python modules.</p>
| 25 | 2008-09-23T19:27:23Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 123,238 | <pre><code>import shutil
shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')
</code></pre>
<p>or</p>
<pre><code>shutil.copy2('/dir/file.ext', '/new/dir')
</code></pre>
<p><code>copy2</code> is also often useful, it preserves the original modification and access info (mtime and atime) in the file metadata.</p>
| 281 | 2008-09-23T19:29:41Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 125,810 | <p>Copying a file is a relatively straightforward operation as shown by the examples below, but you should instead use the <a href="https://docs.python.org/library/shutil.html">shutil stdlib module</a> for that.</p>
<pre class="lang-py prettyprint-override"><code>def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while 1:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.write(copy_buffer)
</code></pre>
<p>If you want to copy by filename you could do something like this:</p>
<pre class="lang-py prettyprint-override"><code>def copyfile_example(source, dest):
# Beware, this example does not handle any edge cases!
with open(source, 'rb') as src, open(dest, 'wb') as dst:
copyfileobj_example(src, dst)
</code></pre>
| 54 | 2008-09-24T07:21:12Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 5,310,215 | <p>Directory and File copy example - From Tim Golden's Python Stuff:</p>
<p><a href="http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html">http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html</a></p>
<pre><code>import os
import shutil
import tempfile
filename1 = tempfile.mktemp (".txt")
open (filename1, "w").close ()
filename2 = filename1 + ".copy"
print filename1, "=>", filename2
shutil.copy (filename1, filename2)
if os.path.isfile (filename2): print "Success"
dirname1 = tempfile.mktemp (".dir")
os.mkdir (dirname1)
dirname2 = dirname1 + ".copy"
print dirname1, "=>", dirname2
shutil.copytree (dirname1, dirname2)
if os.path.isdir (dirname2): print "Success"
</code></pre>
| 20 | 2011-03-15T10:11:21Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 27,575,238 | <p>You could use <code>os.system('cp nameoffilegeneratedbyprogram /otherdirectory/')</code></p>
<p>or as I did it, </p>
<pre><code>os.system('cp '+ rawfile + ' rawdata.dat')
</code></pre>
<p>where <code>rawfile</code> is the name that I had generated inside the program.</p>
<p>This is a Linux only solution </p>
| 6 | 2014-12-19T23:18:02Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 30,359,308 | <pre><code>-------------------------------------------------------------------------
| Function |Copies Metadata|Copies Permissions|Can Specify Buffer|
-------------------------------------------------------------------------
| shutil.copy | No | Yes | No |
-------------------------------------------------------------------------
| shutil.copyfile | No | No | No |
-------------------------------------------------------------------------
| shutil.copy2 | Yes | Yes | No |
-------------------------------------------------------------------------
| shutil.copyfileobj| No | No | Yes |
-------------------------------------------------------------------------
</code></pre>
| 126 | 2015-05-20T20:01:48Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 30,431,587 | <p>For large files, what I did was read the file line by line and read each line into an array. Then, once the array reached a certain size, append it to a new file. </p>
<pre><code>for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
</code></pre>
| 2 | 2015-05-25T05:11:47Z | [
"python",
"filesystems"
] |
How do I copy a file in python? | 123,198 | <p>How do I copy a file in Python? I couldn't find anything under <a href="https://docs.python.org/2/library/os.html"><code>os</code></a>.</p>
| 819 | 2008-09-23T19:23:48Z | 36,396,465 | <pre class="lang-py prettyprint-override"><code>from subprocess import call
call("cp -p <file> <file>", shell=True)
</code></pre>
| 3 | 2016-04-04T07:08:24Z | [
"python",
"filesystems"
] |
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi | 123,499 | <p>I've got the directive</p>
<pre><code><VirtualHost *>
<Location />
AuthType Digest
AuthName "global"
AuthDigestDomain /
AuthUserFile /root/apache_users
<Limit GET>
Require valid-user
</Limit>
</Location>
WSGIScriptAlias / /some/script.wsgi
WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
WSGIProcessGroup mywsgi
ServerName some.example.org
</VirtualHost>
</code></pre>
<p>I'd like to know in the /some/script.wsgi</p>
<pre><code>def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/plain'),
])
return ['Hello']
</code></pre>
<p>What user is logged in.</p>
<p>How do I do that?</p>
| 6 | 2008-09-23T20:05:07Z | 123,526 | <p>add <code>WSGIPassAuthorization On</code>:</p>
<pre><code><VirtualHost *>
<Location />
AuthType Digest
AuthName "global"
AuthDigestDomain /
AuthUserFile /root/apache_users
<Limit GET>
Require valid-user
</Limit>
</Location>
WSGIPassAuthorization On
WSGIScriptAlias / /some/script.wsgi
WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
WSGIProcessGroup mywsgi
ServerName some.example.org
</VirtualHost>
</code></pre>
<p>Then just read <code>environ['REMOTE_USER']</code>:</p>
<pre><code>def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/plain'),
])
return ['Hello %s' % environ['REMOTE_USER']]
</code></pre>
<p>More information at <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationGuidelines#User_Authentication">mod_wsgi documentation</a>.</p>
| 13 | 2008-09-23T20:08:51Z | [
"python",
"apache",
"authentication",
"mod-wsgi",
"wsgi"
] |
Passing apache2 digest authentication information to a wsgi script run by mod_wsgi | 123,499 | <p>I've got the directive</p>
<pre><code><VirtualHost *>
<Location />
AuthType Digest
AuthName "global"
AuthDigestDomain /
AuthUserFile /root/apache_users
<Limit GET>
Require valid-user
</Limit>
</Location>
WSGIScriptAlias / /some/script.wsgi
WSGIDaemonProcess mywsgi user=someuser group=somegroup processes=2 threads=25
WSGIProcessGroup mywsgi
ServerName some.example.org
</VirtualHost>
</code></pre>
<p>I'd like to know in the /some/script.wsgi</p>
<pre><code>def application(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/plain'),
])
return ['Hello']
</code></pre>
<p>What user is logged in.</p>
<p>How do I do that?</p>
| 6 | 2008-09-23T20:05:07Z | 1,038,130 | <p>Additional information about Apache/mod_wsgi and access, authentication and authorization mechanisms can be found in:</p>
<p><a href="http://code.google.com/p/modwsgi/wiki/AccessControlMechanisms" rel="nofollow">http://code.google.com/p/modwsgi/wiki/AccessControlMechanisms</a></p>
<p>The information isn't passed by default because doing so could leak password information to applications which maybe shouldn't get it.</p>
| 2 | 2009-06-24T12:43:03Z | [
"python",
"apache",
"authentication",
"mod-wsgi",
"wsgi"
] |
How to get/set logical directory path in python | 123,958 | <p>In python is it possible to get or set a logical directory (as opposed to an absolute one).</p>
<p>For example if I have:</p>
<pre><code>/real/path/to/dir
</code></pre>
<p>and I have</p>
<pre><code>/linked/path/to/dir
</code></pre>
<p>linked to the same directory.</p>
<p>using os.getcwd and os.chdir will always use the absolute path</p>
<pre><code>>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir
</code></pre>
<p>The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.</p>
| 5 | 2008-09-23T21:19:37Z | 123,985 | <p>The underlying operational system / shell reports real paths to python. </p>
<p>So, there really is no way around it, since <code>os.getcwd()</code> is a wrapped call to C Library <code>getcwd()</code> function.</p>
<p>There are some workarounds in the spirit of the one that you already know which is launching <code>pwd</code>.</p>
<p>Another one would involve using <code>os.environ['PWD']</code>. If that environmnent variable is set you can make some <code>getcwd</code> function that respects it.</p>
<p>The solution below combines both:</p>
<pre><code>import os
from subprocess import Popen, PIPE
class CwdKeeper(object):
def __init__(self):
self._cwd = os.environ.get("PWD")
if self._cwd is None: # no environment. fall back to calling pwd on shell
self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()
self._os_getcwd = os.getcwd
self._os_chdir = os.chdir
def chdir(self, path):
if not self._cwd:
return self._os_chdir(path)
p = os.path.normpath(os.path.join(self._cwd, path))
result = self._os_chdir(p)
self._cwd = p
os.environ["PWD"] = p
return result
def getcwd(self):
if not self._cwd:
return self._os_getcwd()
return self._cwd
cwd = CwdKeeper()
print cwd.getcwd()
# use only cwd.chdir and cwd.getcwd from now on.
# monkeypatch os if you want:
os.chdir = cwd.chdir
os.getcwd = cwd.getcwd
# now you can use os.chdir and os.getcwd as normal.
</code></pre>
| 10 | 2008-09-23T21:22:43Z | [
"python",
"path",
"symlink"
] |
How to get/set logical directory path in python | 123,958 | <p>In python is it possible to get or set a logical directory (as opposed to an absolute one).</p>
<p>For example if I have:</p>
<pre><code>/real/path/to/dir
</code></pre>
<p>and I have</p>
<pre><code>/linked/path/to/dir
</code></pre>
<p>linked to the same directory.</p>
<p>using os.getcwd and os.chdir will always use the absolute path</p>
<pre><code>>>> import os
>>> os.chdir('/linked/path/to/dir')
>>> print os.getcwd()
/real/path/to/dir
</code></pre>
<p>The only way I have found to get around this at all is to launch 'pwd' in another process and read the output. However, this only works until you call os.chdir for the first time.</p>
| 5 | 2008-09-23T21:19:37Z | 27,951,538 | <p>This also does the trick for me:</p>
<pre><code>import os
os.popen('pwd').read().strip('\n')
</code></pre>
<p>Here is a demonstration in python shell:</p>
<pre><code>>>> import os
>>> os.popen('pwd').read()
'/home/projteam/staging/site/proj\n'
>>> os.popen('pwd').read().strip('\n')
'/home/projteam/staging/site/proj'
>>> # Also works if PWD env var is set
>>> os.getenv('PWD')
'/home/projteam/staging/site/proj'
>>> # This gets actual path, not symlinked path
>>> import subprocess
>>> p = subprocess.Popen('pwd', stdout=subprocess.PIPE)
>>> p.communicate()[0] # returns non-symlink path
'/home/projteam/staging/deploys/20150114-141114/site/proj\n'
</code></pre>
<p>Getting the environment variable PWD didn't always work for me so I use the popen method. Cheers!</p>
| 1 | 2015-01-14T20:09:30Z | [
"python",
"path",
"symlink"
] |
Passing around urls between applications in the same project | 124,108 | <p>I am trying to mock-up an API and am using separate apps within Django to represent different web services. I would like App A to take in a link that corresponds to App B and parse the <code>json</code> response. </p>
<p>Is there a way to dynamically construct the url to App B so that I can test the code in development and not change to much before going into production? The problem is that I can't use localhost as part of a link. </p>
<p>I am currently using urllib, but eventually I would like to do something less hacky and better fitting with the web services <code>REST</code> paradigm.</p>
| 1 | 2008-09-23T21:47:35Z | 124,137 | <p>You could do something like</p>
<pre><code>if settings.DEBUG:
other = "localhost"
else:
other = "somehost"
</code></pre>
<p>and use other to build the external URL. Generally you code in DEBUG mode and deploy in non-DEBUG mode. settings.DEBUG is a 'standard' Django thing.</p>
| 2 | 2008-09-23T21:51:15Z | [
"python",
"django",
"web-services",
"development-environment"
] |
Passing around urls between applications in the same project | 124,108 | <p>I am trying to mock-up an API and am using separate apps within Django to represent different web services. I would like App A to take in a link that corresponds to App B and parse the <code>json</code> response. </p>
<p>Is there a way to dynamically construct the url to App B so that I can test the code in development and not change to much before going into production? The problem is that I can't use localhost as part of a link. </p>
<p>I am currently using urllib, but eventually I would like to do something less hacky and better fitting with the web services <code>REST</code> paradigm.</p>
| 1 | 2008-09-23T21:47:35Z | 124,422 | <p>By "separate apps within Django" do you mean separate applications with a common settings? That is to say, two applications within the same Django site (or project)?</p>
<p>If so, the {% url %} tag will generate a proper absolute URL to any of the apps listed in the settings file.</p>
<p>If there are separate Django servers with separate settings, you have the standard internet problem of URI design. Your URI's can be consistent with only the hostname changing.</p>
<pre><code>- http://localhost/some/path - development
- http://123.45.67.78/some/path - someone's laptop who's running a server for testing
- http://qa.mysite.com/some/path - QA
- http://www.mysite.com/some/path - production
</code></pre>
<p>You never need to provide the host information, so all of your links are <code><A HREF="/some/path/"></code>.</p>
<p>This, generally, works out the best. You have can someone's random laptop being a test server; you can get the IP address using ifconfig.</p>
| 1 | 2008-09-23T22:52:54Z | [
"python",
"django",
"web-services",
"development-environment"
] |
Comparison of Python and Perl solutions to Wide Finder challenge | 124,171 | <p>I'd be very grateful if you could compare the winning <a href="http://www.cs.ucsd.edu/~sorourke/wf.pl" rel="nofollow">OâRourke's Perl solution</a> to <a href="http://effbot.org/zone/wide-finder.htm" rel="nofollow">Lundh's Python solution</a>, as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors?</p>
<p><a href="http://www.tbray.org/ongoing/When/200x/2007/10/30/WF-Results" rel="nofollow">Wide Finder: Results</a></p>
| 8 | 2008-09-23T21:57:11Z | 124,255 | <p>Perl is heavily optimized for text processing. There are so many factors that it's hard to say what's the exact difference. Text is represented completely differently internally (utf-8 versus utf-16/utf-32) and the regular expression engines are completely different too. Python's regular expression engine is a custom one and not as much used as the perl one. There are very few developers working on it (I think it's largely unmaintained) in contrast to the Perl one which is basically the "core of the language".</p>
<p>After all Perl is <em>the</em> text processing language.</p>
| 5 | 2008-09-23T22:14:18Z | [
"python",
"performance",
"perl",
"analysis"
] |
Comparison of Python and Perl solutions to Wide Finder challenge | 124,171 | <p>I'd be very grateful if you could compare the winning <a href="http://www.cs.ucsd.edu/~sorourke/wf.pl" rel="nofollow">OâRourke's Perl solution</a> to <a href="http://effbot.org/zone/wide-finder.htm" rel="nofollow">Lundh's Python solution</a>, as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors?</p>
<p><a href="http://www.tbray.org/ongoing/When/200x/2007/10/30/WF-Results" rel="nofollow">Wide Finder: Results</a></p>
| 8 | 2008-09-23T21:57:11Z | 124,357 | <p>The better regex implementation of perl is one part of the story. That can't explain however why the perl implementation scales better. The difference become bigger with more processors. For some reason the python implementation has an issue there.</p>
| 10 | 2008-09-23T22:39:07Z | [
"python",
"performance",
"perl",
"analysis"
] |
Comparison of Python and Perl solutions to Wide Finder challenge | 124,171 | <p>I'd be very grateful if you could compare the winning <a href="http://www.cs.ucsd.edu/~sorourke/wf.pl" rel="nofollow">OâRourke's Perl solution</a> to <a href="http://effbot.org/zone/wide-finder.htm" rel="nofollow">Lundh's Python solution</a>, as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors?</p>
<p><a href="http://www.tbray.org/ongoing/When/200x/2007/10/30/WF-Results" rel="nofollow">Wide Finder: Results</a></p>
| 8 | 2008-09-23T21:57:11Z | 134,803 | <p>The Perl implementation uses the <a href="http://en.wikipedia.org/wiki/Mmap" rel="nofollow">mmap</a> system call. What that call does is establish a pointer which to the process appears to be a normal segment of memory or buffer to the program. It maps the contents of a file to a region of memory. There are performances advantages of doing this vs normal file IO (read) - one is that there are no user-space library calls necessary to get access to the data, another is that there are often less copy operations necessary (eg: moving data between kernel and user space).</p>
<p>Perl's strings and regular expressions are 8-bit byte based (as opposed to utf16 for Java for example), so Perl's native 'character type' is the same encoding of the mmapped file.</p>
<p>When the regular expression engine then operates on the mmap backed variable, it is directly accessing the file data via the mamped memory region - without going through Perl's IO functions, or even libc's IO functions.</p>
<p>The mmap is probably largely responsible for the performance difference vs the Python version using the normal Python IO libraries - which additionally introduce the overhead of looking for line breaks.</p>
<p>The Perl program also supports a -J to parallelize the processing, where the oepen "-|" causes a fork() where the file handle in the parent is to the child's stdout. The child processes serialize their results to stdout and the parent de-serializes them to coordinate and summarize the results.</p>
| 1 | 2008-09-25T17:47:10Z | [
"python",
"performance",
"perl",
"analysis"
] |
Comparison of Python and Perl solutions to Wide Finder challenge | 124,171 | <p>I'd be very grateful if you could compare the winning <a href="http://www.cs.ucsd.edu/~sorourke/wf.pl" rel="nofollow">OâRourke's Perl solution</a> to <a href="http://effbot.org/zone/wide-finder.htm" rel="nofollow">Lundh's Python solution</a>, as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors?</p>
<p><a href="http://www.tbray.org/ongoing/When/200x/2007/10/30/WF-Results" rel="nofollow">Wide Finder: Results</a></p>
| 8 | 2008-09-23T21:57:11Z | 1,831,153 | <blockquote>
<p>The Perl implementation uses the mmap system call. </p>
</blockquote>
<p>This. It avoids buffer copying and provides async I/O.</p>
| 0 | 2009-12-02T07:12:44Z | [
"python",
"performance",
"perl",
"analysis"
] |
Comparison of Python and Perl solutions to Wide Finder challenge | 124,171 | <p>I'd be very grateful if you could compare the winning <a href="http://www.cs.ucsd.edu/~sorourke/wf.pl" rel="nofollow">OâRourke's Perl solution</a> to <a href="http://effbot.org/zone/wide-finder.htm" rel="nofollow">Lundh's Python solution</a>, as I don't know Perl good enough to understand what's going on there. More specifically I'd like to know what gave Perl version 3x advantage: algorithmic superiority, quality of C extensions, other factors?</p>
<p><a href="http://www.tbray.org/ongoing/When/200x/2007/10/30/WF-Results" rel="nofollow">Wide Finder: Results</a></p>
| 8 | 2008-09-23T21:57:11Z | 13,300,315 | <p>Many-core Engine (MCE) has been released for Perl. MCE does quite well at this, even when reading directly from disk with 8 workers (cold cache). Compare to wf_mmap. MCE follows a bank queuing model when reading input data. Look under the images folder for slides on it.</p>
<p>The source code is hosted at <a href="http://code.google.com/p/many-core-engine-perl/" rel="nofollow">http://code.google.com/p/many-core-engine-perl/</a></p>
<p>The perl documentation can be read at <a href="https://metacpan.org/module/MCE" rel="nofollow">https://metacpan.org/module/MCE</a></p>
<p>An implementation of the Wide Finder with MCE is provided under examples/tbray/</p>
<p><a href="https://metacpan.org/source/MARIOROY/MCE-1.514/examples/tbray/" rel="nofollow">https://metacpan.org/source/MARIOROY/MCE-1.514/examples/tbray/</a></p>
<p>Enjoy MCE.</p>
<pre><code>Script....: baseline1 baseline2 wf_mce1 wf_mce2 wf_mce3 wf_mmap
Cold cache: 1.674 1.370 1.252 1.182 1.174 3.056
Warm cache: 1.236 0.923 0.277 0.106 0.098 0.092
</code></pre>
| 3 | 2012-11-09T00:28:26Z | [
"python",
"performance",
"perl",
"analysis"
] |
What is the intended use of the DEFAULT section in config files used by ConfigParser? | 124,692 | <p>I've used ConfigParser for quite a while for simple configs. One thing that's bugged me for a long time is the DEFAULT section. I'm not really sure what's an appropriate use. I've read the documentation, but I would really like to see some clever examples of its use and how it affects other sections in the file (something that really illustrates the kind of things that are possible).</p>
| 16 | 2008-09-24T00:16:34Z | 124,785 | <p>I found an explanation <a href="http://www.enfoldsystems.com/software/proxy/docs/4.0/configuringmanually.html#the-default-section">here</a> by googling for "windows ini" "default section". Summary: whatever you put in the [DEFAULT] section gets propagated to every other section. Using the example from the linked website, let's say I have a config file called test1.ini:</p>
<pre><code>[host 1]
lh_server=192.168.0.1
vh_hosts = PloneSite1:8080
lh_root = PloneSite1
[host 2]
lh_server=192.168.0.1
vh_hosts = PloneSite2:8080
lh_root = PloneSite2
</code></pre>
<p>I can read this using ConfigParser:</p>
<pre><code>>>> cp = ConfigParser.ConfigParser()
>>> cp.read('test1.ini')
['test1.ini']
>>> cp.get('host 1', 'lh_server')
'192.168.0.1'
</code></pre>
<p>But I notice that lh_server is the same in both sections; and, indeed, I realise that it will be the same for most hosts I might add. So I can do this, as test2.ini:</p>
<pre><code>[DEFAULT]
lh_server=192.168.0.1
[host 1]
vh_root = PloneSite1
lh_root = PloneSite1
[host 2]
vh_root = PloneSite2
lh_root = PloneSite2
</code></pre>
<p>Despite the sections not having lh_server keys, I can still access them:</p>
<pre><code>>>> cp.read('test2.ini')
['test2.ini']
>>> cp.get('host 1', 'lh_server')
'192.168.0.1'
</code></pre>
<p>Read the linked page for a further example of using variable substitution in the DEFAULT section to simplify the INI file even more.</p>
| 23 | 2008-09-24T00:49:13Z | [
"python",
"parsing",
"configuration-files"
] |
What is the easiest, most concise way to make selected attributes in an instance be readonly? | 125,034 | <p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
| 8 | 2008-09-24T02:15:21Z | 125,053 | <p>There is no real way to do this. There are ways to make it more 'difficult', but there's no concept of completely hidden, inaccessible class attributes.</p>
<p>If the person using your class can't be trusted to follow the API docs, then that's their own problem. Protecting people from doing stupid stuff just means that they will do far more elaborate, complicated, and damaging stupid stuff to try to do whatever they shouldn't have been doing in the first place.</p>
| 1 | 2008-09-24T02:20:16Z | [
"python",
"attributes",
"readonly"
] |
What is the easiest, most concise way to make selected attributes in an instance be readonly? | 125,034 | <p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
| 8 | 2008-09-24T02:15:21Z | 125,058 | <pre><code>class C(object):
def __init__(self):
self.fullaccess = 0
self.__readonly = 22 # almost invisible to outside code...
# define a publicly visible, read-only version of '__readonly':
readonly = property(lambda self: self.__readonly)
def inc_readonly( self ):
self.__readonly += 1
c=C()
# prove regular attribute is RW...
print "c.fullaccess = %s" % c.fullaccess
c.fullaccess = 1234
print "c.fullaccess = %s" % c.fullaccess
# prove 'readonly' is a read-only attribute
print "c.readonly = %s" % c.readonly
try:
c.readonly = 3
except AttributeError:
print "Can't change c.readonly"
print "c.readonly = %s" % c.readonly
# change 'readonly' indirectly...
c.inc_readonly()
print "c.readonly = %s" % c.readonly
</code></pre>
<p>This outputs:</p>
<p>$ python ./p.py<br>
c.fullaccess = 0<br>
c.fullaccess = 1234<br>
c.readonly = 22<br>
Can't change c.readonly<br>
c.readonly = 22<br>
c.readonly = 23<br>
<br>
My fingers itch to be able to say</p>
<pre><code> @readonly
self.readonly = 22
</code></pre>
<p>i.e., use a decorator on an attribute. It would be so clean...</p>
| 2 | 2008-09-24T02:21:56Z | [
"python",
"attributes",
"readonly"
] |
What is the easiest, most concise way to make selected attributes in an instance be readonly? | 125,034 | <p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
| 8 | 2008-09-24T02:15:21Z | 125,061 | <p>You should use the <code>@property</code> decorator.</p>
<pre><code>>>> class a(object):
... def __init__(self, x):
... self.x = x
... @property
... def xval(self):
... return self.x
...
>>> b = a(5)
>>> b.xval
5
>>> b.xval = 6
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
</code></pre>
| 7 | 2008-09-24T02:22:16Z | [
"python",
"attributes",
"readonly"
] |
What is the easiest, most concise way to make selected attributes in an instance be readonly? | 125,034 | <p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
| 8 | 2008-09-24T02:15:21Z | 125,136 | <p>You could use a metaclass that auto-wraps methods (or class attributes) that follow a naming convention into properties (shamelessly taken from <a href="http://www.python.org/download/releases/2.2/descrintro/#metaclasses" rel="nofollow">Unifying Types and Classes in Python 2.2</a>:</p>
<pre><code>class autoprop(type):
def __init__(cls, name, bases, dict):
super(autoprop, cls).__init__(name, bases, dict)
props = {}
for name in dict.keys():
if name.startswith("_get_") or name.startswith("_set_"):
props[name[5:]] = 1
for name in props.keys():
fget = getattr(cls, "_get_%s" % name, None)
fset = getattr(cls, "_set_%s" % name, None)
setattr(cls, name, property(fget, fset))
</code></pre>
<p>This allows you to use:</p>
<pre><code>class A:
__metaclass__ = autosuprop
def _readonly(self):
return __x
</code></pre>
| 0 | 2008-09-24T02:49:37Z | [
"python",
"attributes",
"readonly"
] |
What is the easiest, most concise way to make selected attributes in an instance be readonly? | 125,034 | <p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
| 8 | 2008-09-24T02:15:21Z | 125,739 | <p>Here's how:</p>
<pre><code>class whatever(object):
def __init__(self, a, b, c, ...):
self.__foobar = 1
self.__blahblah = 2
foobar = property(lambda self: self.__foobar)
blahblah = property(lambda self: self.__blahblah)
</code></pre>
<p>(Assuming <code>foobar</code> and <code>blahblah</code> are the attributes you want to be read-only.) Prepending <b>two</b> underscores to an attribute name effectively hides it from outside the class, so the internal versions won't be accessible from the outside. This <b>only works for new-style classes inheriting from object</b> since it depends on <code>property</code>.</p>
<p>On the other hand... this is a pretty silly thing to do. Keeping variables private seems to be an obsession that comes from C++ and Java. Your users should use the public interface to your class because it's well-designed, not because you force them to.</p>
<p>Edit: Looks like Kevin already posted a similar version.</p>
| 2 | 2008-09-24T06:49:36Z | [
"python",
"attributes",
"readonly"
] |
What is the easiest, most concise way to make selected attributes in an instance be readonly? | 125,034 | <p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
| 8 | 2008-09-24T02:15:21Z | 2,704,300 | <p>I am aware that William Keller is the cleanest solution by far.. but here's something I came up with.. </p>
<pre><code>class readonly(object):
def __init__(self, attribute_name):
self.attribute_name = attribute_name
def __get__(self, instance, instance_type):
if instance != None:
return getattr(instance, self.attribute_name)
else:
raise AttributeError("class %s has no attribute %s" %
(instance_type.__name__, self.attribute_name))
def __set__(self, instance, value):
raise AttributeError("attribute %s is readonly" %
self.attribute_name)
</code></pre>
<p>And here's the usage example</p>
<pre><code>class a(object):
def __init__(self, x):
self.x = x
xval = readonly("x")
</code></pre>
<p>Unfortunately this solution can't handle private variables (__ named variables).</p>
| 0 | 2010-04-24T11:37:38Z | [
"python",
"attributes",
"readonly"
] |
Adding New Element to Text Substring | 125,102 | <p>Say I have the following string:</p>
<pre><code>"I am the most foo h4ck3r ever!!"
</code></pre>
<p>I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:</p>
<pre><code>"I am the most <span class="special">foo></span> h4ck3r ever!!"
</code></pre>
<p>BeautifulSoup seemed like the way to go, but I haven't been able to make it work.</p>
<p>I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.</p>
<p>Some advice for this would be really useful, especially in python. </p>
| 1 | 2008-09-24T02:37:49Z | 125,122 | <p>How about this:</p>
<pre><code>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def makeSpecial(mystring, special_substr):
... return mystring.replace(special_substr, '<span class="special">%s</span>
' % special_substr)
...
>>> makeSpecial("I am the most foo h4ck3r ever!!", "foo")
'I am the most <span class="special">foo</span> h4ck3r ever!!'
>>>
</code></pre>
| 3 | 2008-09-24T02:46:54Z | [
"javascript",
"jquery",
"python",
"beautifulsoup"
] |
Adding New Element to Text Substring | 125,102 | <p>Say I have the following string:</p>
<pre><code>"I am the most foo h4ck3r ever!!"
</code></pre>
<p>I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:</p>
<pre><code>"I am the most <span class="special">foo></span> h4ck3r ever!!"
</code></pre>
<p>BeautifulSoup seemed like the way to go, but I haven't been able to make it work.</p>
<p>I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.</p>
<p>Some advice for this would be really useful, especially in python. </p>
| 1 | 2008-09-24T02:37:49Z | 125,134 | <p>As far as I can tell, you're doing a simple string replace. You're replacing "foo" with "bar foo bar." So from <a href="http://docs.python.org/lib/string-methods.html" rel="nofollow" title="string methods">string</a> you could just use </p>
<pre><code>replace(old, new[, count])
</code></pre>
<p>Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. </p>
<p>So for you it would be:</p>
<pre><code>myStr.replace("foo", "<span>foo</span>")
</code></pre>
| 1 | 2008-09-24T02:49:13Z | [
"javascript",
"jquery",
"python",
"beautifulsoup"
] |
Adding New Element to Text Substring | 125,102 | <p>Say I have the following string:</p>
<pre><code>"I am the most foo h4ck3r ever!!"
</code></pre>
<p>I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:</p>
<pre><code>"I am the most <span class="special">foo></span> h4ck3r ever!!"
</code></pre>
<p>BeautifulSoup seemed like the way to go, but I haven't been able to make it work.</p>
<p>I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.</p>
<p>Some advice for this would be really useful, especially in python. </p>
| 1 | 2008-09-24T02:37:49Z | 125,142 | <p>If you wanted to do it with javascript/jQuery, take a look at this question: <a href="http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery">http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery</a></p>
| 0 | 2008-09-24T02:51:15Z | [
"javascript",
"jquery",
"python",
"beautifulsoup"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 125,226 | <p>Take a look at <a href="http://stackoverflow.com/questions/124869/how-does-the-doc-format-work" rel="nofollow" title="how the doc format works">how the doc format works</a> and <a href="http://stackoverflow.com/questions/124959/create-word-document-using-php-in-lunux" rel="nofollow" title="create word document using php in linux">create word document using PHP in linux</a>. The former is especially useful. <a href="http://www.abisource.com/" rel="nofollow" title="abiword">Abiword</a> is my recommended tool. There are <a href="http://www.abisource.com/wiki/Microsoft_Word_documents" rel="nofollow" title="Abiword limitations">limitations</a> though:</p>
<blockquote>
<p>However, if the document has complicated tables, text boxes, embedded spreadsheets, and so forth, then it might not work as expected. Developing good MS Word filters is a very difficult process, so please bear with us as we work on getting Word documents to open correctly. If you have a Word document which fails to load, please open a Bug and include the document so we can improve the importer. </p>
</blockquote>
| 4 | 2008-09-24T03:17:26Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 125,235 | <p>I'm not sure if you're going to have much luck without using COM. The .doc format is ridiculously complex, and is often called a "memory dump" of Word at the time of saving!</p>
<p>At Swati, that's in HTML, which is fine and dandy, but most word documents aren't so nice!</p>
| 2 | 2008-09-24T03:19:53Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 125,248 | <p>OpenOffice.org can be scripted with Python: <a href="http://wiki.services.openoffice.org/wiki/Python">see here</a>.</p>
<p>Since OOo can load most MS Word files flawlessly, I'd say that's your best bet.</p>
| 10 | 2008-09-24T03:23:42Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 125,386 | <p>You could make a subprocess call to <a href="http://en.wikipedia.org/wiki/Antiword">antiword</a>. Antiword is a linux commandline utility for dumping text out of a word doc. Works pretty well for simple documents (obviously it loses formatting). It's available through apt, and probably as RPM, or you could compile it yourself.</p>
| 17 | 2008-09-24T04:13:03Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 404,378 | <p>I know this is an old question, but I was recently trying to find a way to extract text from MS word files, and the best solution by far I found was with wvLib:</p>
<p><a href="http://wvware.sourceforge.net/">http://wvware.sourceforge.net/</a></p>
<p>After installing the library, using it in Python is pretty easy:</p>
<pre><code>import commands
exe = 'wvText ' + word_file + ' ' + output_txt_file
out = commands.getoutput(exe)
exe = 'cat ' + output_txt_file
out = commands.getoutput(exe)
</code></pre>
<p>And that's it. Pretty much, what we're doing is using the commands.getouput function to run a couple of shell scripts, namely wvText (which extracts text from a Word document, and cat to read the file output). After that, the entire text from the Word document will be in the out variable, ready to use.</p>
<p>Hopefully this will help anyone having similar issues in the future.</p>
| 5 | 2009-01-01T01:14:38Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 1,258,599 | <p>(Note: I posted this on <a href="http://stackoverflow.com/questions/1184747/rtf-doc-docx-text-extraction-in-program-written-in-c-qt">this question</a> as well, but it seems relevant here, so please excuse the repost.)</p>
<p>Now, this is pretty ugly and pretty hacky, but it seems to work for me for basic text extraction. Obviously to use this in a Qt program you'd have to spawn a process for it etc, but the command line I've hacked together is:</p>
<pre><code>unzip -p file.docx | grep '<w:t' | sed 's/<[^<]*>//g' | grep -v '^[[:space:]]*$'
</code></pre>
<p>So that's:</p>
<p><em>unzip -p file.docx</em>: -p == "unzip to stdout"</p>
<p><em>grep '<w:t'</em>: Grab just the lines containing '<w:t' (<w:t> is the Word 2007 XML element for "text", as far as I can tell)</p>
<p><em>sed 's/<[^<]</em>>//g'*: Remove everything inside tags</p>
<p><em>grep -v '^[[:space:]]</em>$'*: Remove blank lines</p>
<p>There is likely a more efficient way to do this, but it seems to work for me on the few docs I've tested it with.</p>
<p>As far as I'm aware, unzip, grep and sed all have ports for Windows and any of the Unixes, so it should be reasonably cross-platform. Despit being a bit of an ugly hack ;)</p>
| 4 | 2009-08-11T05:38:51Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 1,723,437 | <p>If your intention is to use purely python modules without calling a subprocess, you can use the zipfile python modude.</p>
<pre><code>content = ""
# Load DocX into zipfile
docx = zipfile.ZipFile('/home/whateverdocument.docx')
# Unpack zipfile
unpacked = docx.infolist()
# Find the /word/document.xml file in the package and assign it to variable
for item in unpacked:
if item.orig_filename == 'word/document.xml':
content = docx.read(item.orig_filename)
else:
pass
</code></pre>
<p>Your content string however needs to be cleaned up, one way of doing this is:</p>
<pre><code># Clean the content string from xml tags for better search
fullyclean = []
halfclean = content.split('<')
for item in halfclean:
if '>' in item:
bad_good = item.split('>')
if bad_good[-1] != '':
fullyclean.append(bad_good[-1])
else:
pass
else:
pass
# Assemble a new string with all pure content
content = " ".join(fullyclean)
</code></pre>
<p>But there is surely a more elegant way to clean up the string, probably using the re module.
Hope this helps.</p>
| 4 | 2009-11-12T16:18:16Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 1,967,869 | <p>benjamin's answer is a pretty good one. I have just consolidated...</p>
<pre><code>import zipfile, re
docx = zipfile.ZipFile('/path/to/file/mydocument.docx')
content = docx.read('word/document.xml')
cleaned = re.sub('<(.|\n)*?>','',content)
print cleaned
</code></pre>
| 9 | 2009-12-28T03:39:54Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 1,979,906 | <p>Use the <strong>native Python docx module</strong>. Here's how to extract all the text from a doc:</p>
<pre><code>document = docx.Document(filename)
docText = '\n\n'.join([
paragraph.text.encode('utf-8') for paragraph in document.paragraphs
])
print docText
</code></pre>
<p>See <a href="https://python-docx.readthedocs.org/en/latest/">Python DocX site</a></p>
<p>Also check out <a href="http://textract.readthedocs.org/en/latest/">Textract</a> which pulls out tables etc. </p>
<p>Parsing XML with regexs invokes cthulu. Don't do it!</p>
| 26 | 2009-12-30T12:17:09Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 10,617,686 | <p>Unoconv might also be a good alternative: <a href="http://linux.die.net/man/1/unoconv" rel="nofollow">http://linux.die.net/man/1/unoconv</a></p>
| 3 | 2012-05-16T11:35:57Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 14,829,241 | <p>Just an option for reading 'doc' files without using COM: <a href="https://github.com/rembish/Miette" rel="nofollow">miette</a>. Should work on any platform.</p>
| 1 | 2013-02-12T09:25:30Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 30,122,779 | <p>If you have LibreOffice installed, <a href="http://stackoverflow.com/questions/16516044/is-it-possible-to-read-word-files-doc-docx-in-python/30122239#30122239">you can simply call it from the command line to convert the file to text</a>, then load the text into Python.</p>
| 1 | 2015-05-08T11:31:23Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 30,582,548 | <p>Is this an old question?
I believe that such thing does not exist.
There are only answered and unanswered ones.
This one is pretty unanswered, or half answered if you wish.
Well, methods for reading *.docx (MS Word 2007 and later) documents without using COM interop are all covered.
But methods for extracting text from *.doc (MS Word 97-2000), using Python only, lacks.
Is this complicated?
To do: not really, to understand: well, that's another thing.</p>
<p>When I didn't find any finished code, I read some format specifications and dug out some proposed algorithms in other languages.</p>
<p>MS Word (*.doc) file is an OLE2 compound file.
Not to bother you with a lot of unnecessary details, think of it as a file-system stored in a file. It actually uses FAT structure, so the definition holds. (Hm, maybe you can loop-mount it in Linux???)
In this way, you can store more files within a file, like pictures etc.
The same is done in *.docx by using ZIP archive instead.
There are packages available on PyPI that can read OLE files. Like (olefile, compoundfiles, ...)
I used compoundfiles package to open *.doc file.
However, in MS Word 97-2000, internal subfiles are not XML or HTML, but binary files.
And as this is not enough, each contains an information about other one, so you have to read at least two of them and unravel stored info accordingly.
To understand fully, read the PDF document from which I took the algorithm.</p>
<p>Code below is very hastily composed and tested on small number of files.
As far as I can see, it works as intended.
Sometimes some gibberish appears at the start, and almost always at the end of text.
And there can be some odd characters in-between as well.</p>
<p>Those of you who just wish to search for text will be happy.
Still, I urge anyone who can help to improve this code to do so.</p>
<pre><code>
doc2text module:
"""
This is Python implementation of C# algorithm proposed in:
http://b2xtranslator.sourceforge.net/howtos/How_to_retrieve_text_from_a_binary_doc_file.pdf
Python implementation author is Dalen Bernaca.
Code needs refining and probably bug fixing!
As I am not a C# expert I would like some code rechecks by one.
Parts of which I am uncertain are:
* Did the author of original algorithm used uint32 and int32 when unpacking correctly?
I copied each occurence as in original algo.
* Is the FIB length for MS Word 97 1472 bytes as in MS Word 2000, and would it make any difference if it is not?
* Did I interpret each C# command correctly?
I think I did!
"""
from compoundfiles import CompoundFileReader, CompoundFileError
from struct import unpack
__all__ = ["doc2text"]
def doc2text (path):
text = u""
cr = CompoundFileReader(path)
# Load WordDocument stream:
try:
f = cr.open("WordDocument")
doc = f.read()
f.close()
except: cr.close(); raise CompoundFileError, "The file is corrupted or it is not a Word document at all."
# Extract file information block and piece table stream informations from it:
fib = doc[:1472]
fcClx = unpack("L", fib[0x01a2l:0x01a6l])[0]
lcbClx = unpack("L", fib[0x01a6l:0x01a6+4l])[0]
tableFlag = unpack("L", fib[0x000al:0x000al+4l])[0] & 0x0200l == 0x0200l
tableName = ("0Table", "1Table")[tableFlag]
# Load piece table stream:
try:
f = cr.open(tableName)
table = f.read()
f.close()
except: cr.close(); raise CompoundFileError, "The file is corrupt. '%s' piece table stream is missing." % tableName
cr.close()
# Find piece table inside a table stream:
clx = table[fcClx:fcClx+lcbClx]
pos = 0
pieceTable = ""
lcbPieceTable = 0
while True:
if clx[pos]=="\x02":
# This is piece table, we store it:
lcbPieceTable = unpack("l", clx[pos+1:pos+5])[0]
pieceTable = clx[pos+5:pos+5+lcbPieceTable]
break
elif clx[pos]=="\x01":
# This is beggining of some other substructure, we skip it:
pos = pos+1+1+ord(clx[pos+1])
else: break
if not pieceTable: raise CompoundFileError, "The file is corrupt. Cannot locate a piece table."
# Read info from pieceTable, about each piece and extract it from WordDocument stream:
pieceCount = (lcbPieceTable-4)/12
for x in xrange(pieceCount):
cpStart = unpack("l", pieceTable[x*4:x*4+4])[0]
cpEnd = unpack("l", pieceTable[(x+1)*4:(x+1)*4+4])[0]
ofsetDescriptor = ((pieceCount+1)*4)+(x*8)
pieceDescriptor = pieceTable[ofsetDescriptor:ofsetDescriptor+8]
fcValue = unpack("L", pieceDescriptor[2:6])[0]
isANSII = (fcValue & 0x40000000) == 0x40000000
fc = fcValue & 0xbfffffff
cb = cpEnd-cpStart
enc = ("utf-16", "cp1252")[isANSII]
cb = (cb*2, cb)[isANSII]
text += doc[fc:fc+cb].decode(enc, "ignore")
return "\n".join(text.splitlines())
</code></pre>
| 1 | 2015-06-01T20:20:14Z | [
"python",
"linux",
"ms-word"
] |
extracting text from MS word files in python | 125,222 | <p>for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux?
Is there any library?</p>
| 22 | 2008-09-24T03:15:13Z | 38,750,949 | <p>To read Word 2007 and later files, including .docx files, you can use the <a href="http://python-docx.readthedocs.io/en/latest/user/documents.html" rel="nofollow">python-docx</a> package:</p>
<pre><code>from docx import Document
document = Document('existing-document-file.docx')
document.save('new-file-name.docx')
</code></pre>
<p>To read .doc files from Word 2003 and earlier, make a subprocess call to <a href="http://www.winfield.demon.nl/" rel="nofollow">antiword</a>. You need to install antiword first:</p>
<pre><code>sudo apt-get install antiword
</code></pre>
<p>Then just call it from your python script:</p>
<pre><code>import os
input_word_file = "input_file.doc"
output_text_file = "output_file.txt"
os.system('antiword %s > %s' % (input_word_file, output_text_file))
</code></pre>
| 0 | 2016-08-03T18:17:37Z | [
"python",
"linux",
"ms-word"
] |
How do I modify a text file in Python? | 125,703 | <p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
| 125 | 2008-09-24T06:30:56Z | 125,713 | <p>Depends on what you want to do. To append you can open it with "a":</p>
<pre><code> with open("foo.txt", "a") as f:
f.write("new line\n")
</code></pre>
<p>If you want to preprend something you have to read from the file first:</p>
<pre><code>with open("foo.txt", "r+") as f:
old = f.read() # read everything in the file
f.seek(0) # rewind
f.write("new line\n" + old) # write the new line before
</code></pre>
| 75 | 2008-09-24T06:35:51Z | [
"python",
"file",
"text"
] |
How do I modify a text file in Python? | 125,703 | <p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
| 125 | 2008-09-24T06:30:56Z | 125,759 | <p>Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.</p>
<p>This is an operating system thing, not a Python thing. It is the same in all languages.</p>
<p>What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.</p>
<p>This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.</p>
| 100 | 2008-09-24T06:57:21Z | [
"python",
"file",
"text"
] |
How do I modify a text file in Python? | 125,703 | <p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
| 125 | 2008-09-24T06:30:56Z | 126,389 | <p>Rewriting a file in place is often done by saving the old copy with a modified name. Unix folks add a <code>~</code> to mark the old one. Windows folks do all kinds of things -- add .bak or .old -- or rename the file entirely or put the ~ on the front of the name.</p>
<pre><code>import shutil
shutil.move( afile, afile+"~" )
destination= open( aFile, "w" )
source= open( aFile+"~", "r" )
for line in source:
destination.write( line )
if <some condition>:
destination.write( >some additional line> + "\n" )
source.close()
destination.close()
</code></pre>
<p>Instead of <code>shutil</code>, you can use the following.</p>
<pre><code>import os
os.rename( aFile, aFile+"~" )
</code></pre>
| 28 | 2008-09-24T10:27:45Z | [
"python",
"file",
"text"
] |
How do I modify a text file in Python? | 125,703 | <p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
| 125 | 2008-09-24T06:30:56Z | 130,844 | <p>Python's mmap module will allow you to insert into a file. The following sample shows how it can be done in Unix (Windows mmap may be different). Note that this does not handle all error conditions and you might corrupt or lose the original file. Also, this won't handle unicode strings.</p>
<pre><code>import os
from mmap import mmap
def insert(filename, str, pos):
if len(str) < 1:
# nothing to insert
return
f = open(filename, 'r+')
m = mmap(f.fileno(), os.path.getsize(filename))
origSize = m.size()
# or this could be an error
if pos > origSize:
pos = origSize
elif pos < 0:
pos = 0
m.resize(origSize + len(str))
m[pos+len(str):] = m[pos:origSize]
m[pos:pos+len(str)] = str
m.close()
f.close()
</code></pre>
<p>It is also possible to do this without mmap with files opened in 'r+' mode, but it is less convenient and less efficient as you'd have to read and temporarily store the contents of the file from the insertion position to EOF - which might be huge.</p>
| 13 | 2008-09-25T00:41:01Z | [
"python",
"file",
"text"
] |
How do I modify a text file in Python? | 125,703 | <p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
| 125 | 2008-09-24T06:30:56Z | 1,811,866 | <p>The fileinput module of the Python standard library will rewrite a file inplace if you use the inplace=1 parameter:</p>
<pre><code>import sys
import fileinput
# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th
for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
sys.stdout.write(line.replace('sit', 'SIT')) # replace 'sit' and write
if i == 4: sys.stdout.write('\n') # write a blank line after the 5th line
</code></pre>
| 43 | 2009-11-28T07:25:54Z | [
"python",
"file",
"text"
] |
How do I modify a text file in Python? | 125,703 | <p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
| 125 | 2008-09-24T06:30:56Z | 13,464,228 | <p>As mentioned by Adam you have to take your system limitations into consideration before you can decide on approach whether you have enough memory to read it all into memory replace parts of it and re-write it. </p>
<p>If you're dealing with a small file or have no memory issues this might help:</p>
<p><strong>Option 1)</strong>
Read entire file into memory, do a regex substitution on the entire or part of the line and replace it with that line plus the extra line. You will need to make sure that the 'middle line' is unique in the file or if you have timestamps on each line this should be pretty reliable.</p>
<pre><code># open file with r+b (allow write and binary mode)
f = open("file.log", 'r+b')
# read entire content of file into memory
f_content = f.read()
# basically match middle line and replace it with itself and the extra line
f_content = re.sub(r'(middle line)', r'\1\nnew line', f_content)
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content
f.truncate()
# re-write the content with the updated content
f.write(f_content)
# close file
f.close()
</code></pre>
<p><strong>Option 2)</strong>
Figure out middle line, and replace it with that line plus the extra line. </p>
<pre><code># open file with r+b (allow write and binary mode)
f = open("file.log" , 'r+b')
# get array of lines
f_content = f.readlines()
# get middle line
middle_line = len(f_content)/2
# overwrite middle line
f_content[middle_line] += "\nnew line"
# return pointer to top of file so we can re-write the content with replaced string
f.seek(0)
# clear file content
f.truncate()
# re-write the content with the updated content
f.write(''.join(f_content))
# close file
f.close()
</code></pre>
| 7 | 2012-11-19T23:24:50Z | [
"python",
"file",
"text"
] |
How do I modify a text file in Python? | 125,703 | <p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
| 125 | 2008-09-24T06:30:56Z | 35,149,780 | <p>Wrote a small class for doing this cleanly.</p>
<pre><code>import tempfile
class FileModifierError(Exception):
pass
class FileModifier(object):
def __init__(self, fname):
self.__write_dict = {}
self.__filename = fname
self.__tempfile = tempfile.TemporaryFile()
with open(fname, 'rb') as fp:
for line in fp:
self.__tempfile.write(line)
self.__tempfile.seek(0)
def write(self, s, line_number = 'END'):
if line_number != 'END' and not isinstance(line_number, (int, float)):
raise FileModifierError("Line number %s is not a valid number" % line_number)
try:
self.__write_dict[line_number].append(s)
except KeyError:
self.__write_dict[line_number] = [s]
def writeline(self, s, line_number = 'END'):
self.write('%s\n' % s, line_number)
def writelines(self, s, line_number = 'END'):
for ln in s:
self.writeline(s, line_number)
def __popline(self, index, fp):
try:
ilines = self.__write_dict.pop(index)
for line in ilines:
fp.write(line)
except KeyError:
pass
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
with open(self.__filename,'w') as fp:
for index, line in enumerate(self.__tempfile.readlines()):
self.__popline(index, fp)
fp.write(line)
for index in sorted(self.__write_dict):
for line in self.__write_dict[index]:
fp.write(line)
self.__tempfile.close()
</code></pre>
<p>Then you can use it this way:</p>
<pre><code>with FileModifier(filename) as fp:
fp.writeline("String 1", 0)
fp.writeline("String 2", 20)
fp.writeline("String 3") # To write at the end of the file
</code></pre>
| 0 | 2016-02-02T09:42:12Z | [
"python",
"file",
"text"
] |
Python library for rendering HTML and javascript | 126,131 | <p>Is there any python module for rendering a HTML page with javascript and get back a DOM object?</p>
<p>I want to parse a page which generates almost all of its content using javascript. </p>
| 16 | 2008-09-24T09:05:57Z | 126,216 | <p>Only way I know to accomplish this would be to drive real browser, for example using <a href="http://selenium-rc.openqa.org" rel="nofollow">selenium-rc</a>.</p>
| 1 | 2008-09-24T09:33:24Z | [
"javascript",
"python",
"html"
] |
Python library for rendering HTML and javascript | 126,131 | <p>Is there any python module for rendering a HTML page with javascript and get back a DOM object?</p>
<p>I want to parse a page which generates almost all of its content using javascript. </p>
| 16 | 2008-09-24T09:05:57Z | 126,250 | <p>The big complication here is emulating the full browser environment outside of a browser. You can use stand alone javascript interpreters like Rhino and SpiderMonkey to run javascript code but they don't provide a complete browser like environment to full render a web page.</p>
<p>If I needed to solve a problem like this I would first look at how the javascript is rendering the page, it's quite possible it's fetching data via AJAX and using that to render the page. I could then use python libraries like simplejson and httplib2 to directly fetch the data and use that, negating the need to access the DOM object. However, that's only one possible situation, I don't know the exact problem you are solving.</p>
<p>Other options include the selenium one mentioned by Åukasz, some kind of webkit embedded craziness, some kind of IE win32 scripting craziness or, finally, a pyxpcom based solution (with added craziness). All these have the drawback of requiring pretty much a fully running web browser for python to play with, which might not be an option depending on your environment.</p>
| 7 | 2008-09-24T09:42:52Z | [
"javascript",
"python",
"html"
] |
Python library for rendering HTML and javascript | 126,131 | <p>Is there any python module for rendering a HTML page with javascript and get back a DOM object?</p>
<p>I want to parse a page which generates almost all of its content using javascript. </p>
| 16 | 2008-09-24T09:05:57Z | 126,286 | <p><a href="http://doc.trolltech.com/4.4/qtwebkit.html">QtWebKit</a> is contained in PyQt4, but I don't know if you can use it without showing a widget. After a cursory look over the documentation, it seems to me you can only get HTML, not a DOM tree.</p>
| 5 | 2008-09-24T09:54:22Z | [
"javascript",
"python",
"html"
] |
Python library for rendering HTML and javascript | 126,131 | <p>Is there any python module for rendering a HTML page with javascript and get back a DOM object?</p>
<p>I want to parse a page which generates almost all of its content using javascript. </p>
| 16 | 2008-09-24T09:05:57Z | 126,341 | <p>You can probably use <a href="http://code.google.com/p/pywebkitgtk/" rel="nofollow">python-webkit</a> for it. Requires a running glib and GTK, but that's probably less problematic than wrapping the parts of webkit without glib.</p>
<p>I don't know if it does everything you need, but I guess you should give it a try.</p>
| 1 | 2008-09-24T10:11:15Z | [
"javascript",
"python",
"html"
] |
Example Facebook Application using TurboGears -- pyFacebook | 126,356 | <p>I have a TurboGears application I'd like to run through Facebook, and am looking for an example TurboGears project using pyFacebook or minifb.py. pyFacebook is Django-centric, and I can probably figure it out, but this is, after all, the lazy web.</p>
| 2 | 2008-09-24T10:14:07Z | 126,399 | <p>Why is pyFacebook django centric? Looks like it works perfectly fine with all kinds of WSGI apps or Python applications in general. No need to use Django.</p>
| 3 | 2008-09-24T10:31:00Z | [
"python",
"facebook",
"turbogears"
] |
Example Facebook Application using TurboGears -- pyFacebook | 126,356 | <p>I have a TurboGears application I'd like to run through Facebook, and am looking for an example TurboGears project using pyFacebook or minifb.py. pyFacebook is Django-centric, and I can probably figure it out, but this is, after all, the lazy web.</p>
| 2 | 2008-09-24T10:14:07Z | 130,332 | <p>pyFacebook is Django-centric because it includes a Django example. I did not intend to irk, but am merely looking for a TurboGears example using pyFacebook.</p>
| 1 | 2008-09-24T22:32:28Z | [
"python",
"facebook",
"turbogears"
] |
"cannot find -lpq" when trying to install psycopg2 | 126,364 | <p><strong>Intro</strong>: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running <code>setup.py install</code>. This didn't work, telling me I needed mingw. So I downloaded and installed mingw.</p>
<p><strong>Problem</strong>: I now get the following error when running <code>setup.py build_ext --compiler=mingw32 install</code>:</p>
<pre><code>running build_ext
building 'psycopg2._psycopg' extension
writing build\temp.win32-2.4\Release\psycopg\_psycopg.def
C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.4\Release\psycopg
\psycopgmodule.o build\temp.win32-2.4\Release\psycopg\pqpath.o build\temp.win32-
2.4\Release\psycopg\typecast.o build\temp.win32-2.4\Release\psycopg\microprotoco
ls.o build\temp.win32-2.4\Release\psycopg\microprotocols_proto.o build\temp.win3
2-2.4\Release\psycopg\connection_type.o build\temp.win32-2.4\Release\psycopg\con
nection_int.o build\temp.win32-2.4\Release\psycopg\cursor_type.o build\temp.win3
2-2.4\Release\psycopg\cursor_int.o build\temp.win32-2.4\Release\psycopg\lobject_
type.o build\temp.win32-2.4\Release\psycopg\lobject_int.o build\temp.win32-2.4\R
elease\psycopg\adapter_qstring.o build\temp.win32-2.4\Release\psycopg\adapter_pb
oolean.o build\temp.win32-2.4\Release\psycopg\adapter_binary.o build\temp.win32-
2.4\Release\psycopg\adapter_asis.o build\temp.win32-2.4\Release\psycopg\adapter_
list.o build\temp.win32-2.4\Release\psycopg\adapter_datetime.o build\temp.win32-
2.4\Release\psycopg\_psycopg.def -LC:\Python24\libs -LC:\Python24\PCBuild -Lc:/P
ROGRA~1/POSTGR~1/8.3/lib -lpython24 -lmsvcr71 -lpq -lmsvcr71 -lws2_32 -ladvapi32
-o build\lib.win32-2.4\psycopg2\_psycopg.pyd
C:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot fin
d -lpq
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1
</code></pre>
<p><strong>What I've tried</strong> - I noticed the forward slashes in the -L option, so I manually entered my PostgreSQL lib directory in the library_dirs option in the setup.cfg, to no avail (the call then had a -L option with backslashes, but the error message stayed the same).</p>
| 0 | 2008-09-24T10:16:00Z | 126,494 | <p>Have you tried the <a href="http://www.stickpeople.com/projects/python/win-psycopg/" rel="nofollow">binary build</a> of psycopg2 for windows? If that works with your python then it mitigates the need to build by hand.</p>
<p>I've seen random people ask this question on various lists and it seems one recommendation is to build postgresql by hand to work around this problem.</p>
| 2 | 2008-09-24T10:59:27Z | [
"python",
"postgresql",
"trac"
] |
"cannot find -lpq" when trying to install psycopg2 | 126,364 | <p><strong>Intro</strong>: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running <code>setup.py install</code>. This didn't work, telling me I needed mingw. So I downloaded and installed mingw.</p>
<p><strong>Problem</strong>: I now get the following error when running <code>setup.py build_ext --compiler=mingw32 install</code>:</p>
<pre><code>running build_ext
building 'psycopg2._psycopg' extension
writing build\temp.win32-2.4\Release\psycopg\_psycopg.def
C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.4\Release\psycopg
\psycopgmodule.o build\temp.win32-2.4\Release\psycopg\pqpath.o build\temp.win32-
2.4\Release\psycopg\typecast.o build\temp.win32-2.4\Release\psycopg\microprotoco
ls.o build\temp.win32-2.4\Release\psycopg\microprotocols_proto.o build\temp.win3
2-2.4\Release\psycopg\connection_type.o build\temp.win32-2.4\Release\psycopg\con
nection_int.o build\temp.win32-2.4\Release\psycopg\cursor_type.o build\temp.win3
2-2.4\Release\psycopg\cursor_int.o build\temp.win32-2.4\Release\psycopg\lobject_
type.o build\temp.win32-2.4\Release\psycopg\lobject_int.o build\temp.win32-2.4\R
elease\psycopg\adapter_qstring.o build\temp.win32-2.4\Release\psycopg\adapter_pb
oolean.o build\temp.win32-2.4\Release\psycopg\adapter_binary.o build\temp.win32-
2.4\Release\psycopg\adapter_asis.o build\temp.win32-2.4\Release\psycopg\adapter_
list.o build\temp.win32-2.4\Release\psycopg\adapter_datetime.o build\temp.win32-
2.4\Release\psycopg\_psycopg.def -LC:\Python24\libs -LC:\Python24\PCBuild -Lc:/P
ROGRA~1/POSTGR~1/8.3/lib -lpython24 -lmsvcr71 -lpq -lmsvcr71 -lws2_32 -ladvapi32
-o build\lib.win32-2.4\psycopg2\_psycopg.pyd
C:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot fin
d -lpq
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1
</code></pre>
<p><strong>What I've tried</strong> - I noticed the forward slashes in the -L option, so I manually entered my PostgreSQL lib directory in the library_dirs option in the setup.cfg, to no avail (the call then had a -L option with backslashes, but the error message stayed the same).</p>
| 0 | 2008-09-24T10:16:00Z | 126,495 | <p>Compiling extensions on windows can be tricky. There are precompiled libraries available however: <a href="http://www.stickpeople.com/projects/python/win-psycopg/" rel="nofollow">http://www.stickpeople.com/projects/python/win-psycopg/</a></p>
| 1 | 2008-09-24T11:00:28Z | [
"python",
"postgresql",
"trac"
] |
Iterate a list with indexes in Python | 126,524 | <p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p>
<pre><code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code></pre>
<p>but I can't remember the name and googling "iterate list" gets nothing.</p>
| 133 | 2008-09-24T11:08:52Z | 126,533 | <pre><code>>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
</code></pre>
| 227 | 2008-09-24T11:11:41Z | [
"python",
"list"
] |
Iterate a list with indexes in Python | 126,524 | <p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p>
<pre><code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code></pre>
<p>but I can't remember the name and googling "iterate list" gets nothing.</p>
| 133 | 2008-09-24T11:08:52Z | 126,535 | <p>Yep, that would be the <a href="http://docs.python.org/library/functions.html#enumerate"><code>enumerate</code></a> function! Or more to the point, you need to do:</p>
<pre><code>list(enumerate([3,7,19]))
[(0, 3), (1, 7), (2, 19)]
</code></pre>
| 78 | 2008-09-24T11:12:14Z | [
"python",
"list"
] |
Iterate a list with indexes in Python | 126,524 | <p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p>
<pre><code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code></pre>
<p>but I can't remember the name and googling "iterate list" gets nothing.</p>
| 133 | 2008-09-24T11:08:52Z | 127,375 | <p>Here's another using the <code>zip</code> function.</p>
<pre><code>>>> a = [3, 7, 19]
>>> zip(range(len(a)), a)
[(0, 3), (1, 7), (2, 19)]
</code></pre>
| 21 | 2008-09-24T14:10:58Z | [
"python",
"list"
] |
Iterate a list with indexes in Python | 126,524 | <p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p>
<pre><code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code></pre>
<p>but I can't remember the name and googling "iterate list" gets nothing.</p>
| 133 | 2008-09-24T11:08:52Z | 18,777,094 | <p>Here it is a solution using map function:</p>
<pre><code>>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]
</code></pre>
<p>And a solution using list comprehensions:</p>
<pre><code>>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]
</code></pre>
| 6 | 2013-09-13T02:01:14Z | [
"python",
"list"
] |
Iterate a list with indexes in Python | 126,524 | <p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p>
<pre><code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code></pre>
<p>but I can't remember the name and googling "iterate list" gets nothing.</p>
| 133 | 2008-09-24T11:08:52Z | 35,429,590 | <p>If you have multiple lists, you can do this combining <code>enumerate</code> and <code>zip</code>:</p>
<pre><code>list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]
list3 = [100, 200, 300, 400, 500]
for i, (l1, l2, l3) in enumerate(zip(list1, list2, list3)):
print(i, l1, l2, l3)
</code></pre>
Output:
<pre><code>0 1 10 100
1 2 20 200
2 3 30 300
3 4 40 400
4 5 50 500
</code></pre>
<p>Note that parenthesis is required after <code>i</code>. Otherwise you get the error: <code>ValueError: need more than 2 values to unpack</code></p>
| 0 | 2016-02-16T10:12:11Z | [
"python",
"list"
] |
Iterate a list with indexes in Python | 126,524 | <p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p>
<pre><code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code></pre>
<p>but I can't remember the name and googling "iterate list" gets nothing.</p>
| 133 | 2008-09-24T11:08:52Z | 36,571,189 | <p>python <code>enumerate</code> function will be satisfied your requirements</p>
<pre><code>result = list(enumerate([1,3,7,12]))
print result
</code></pre>
<p><strong>output</strong><br></p>
<pre><code>[(0, 1), (1, 3), (2, 7),(3,12)]
</code></pre>
| 1 | 2016-04-12T10:55:14Z | [
"python",
"list"
] |
How can i move an object drawn in device context python | 126,738 | <p>I have drawn an image in the device context using python, and i want to move it somothly/animate either vertically or horizontally? What algorithm should i use? </p>
<p>Where can i get info for this kind of tasks in python?</p>
| 0 | 2008-09-24T12:12:04Z | 126,750 | <p>Once an object is drawn in a device context it stays there. If you want to move it you need to redraw it.</p>
<p>You can keep a background that's fixed and only redraw the movable elements each time they move. Basically that's how it's done.</p>
<p>To move an object smoothly over a line you have to do something like this (I don't have a program ready, so can only give you an idea):</p>
<ul>
<li>choose the start and end position: point A(x1, y1) and B(x2, y2)</li>
<li>choose in how much time the object should change position from A to B (say 10 seconds).</li>
<li>use a timer set to a certain interval (say 2 seconds)</li>
<li>calculate the delta X and Y that the object should change for each timer interval. In this case dx = (x2-x1)*2/10 and dy = (y2-y1)*2/10</li>
<li>in the timer callback increment the current object position with dx and dy and redraw the image</li>
</ul>
<p>That would be the algorithm.</p>
<p>I suggest that you also take a look to <a href="http://www.pygame.org/" rel="nofollow">PyGame</a>. Maybe you can use that and it also has some tutorials.</p>
| 1 | 2008-09-24T12:15:05Z | [
"python",
"animation"
] |
How can i move an object drawn in device context python | 126,738 | <p>I have drawn an image in the device context using python, and i want to move it somothly/animate either vertically or horizontally? What algorithm should i use? </p>
<p>Where can i get info for this kind of tasks in python?</p>
| 0 | 2008-09-24T12:12:04Z | 127,216 | <p>To smoothly move object between starting coordinate <code>(x1, y1)</code> and destination coordinate <code>(x2,y2)</code>, you need to first ask yourself, how <em>long</em> the object should take to get to its destination. Lets say you want the object to get there in <code>t</code> time units (which maybe seconds, hours, whatever). Once you have determined this it is then trivial to workout the displacement per unit time:</p>
<pre><code>dx = (x2-x1)/t
dy = (y2-y1)/t
</code></pre>
<p>Now you simply need to add <code>(dx,dy)</code> to the object's position (<code>(x,y)</code>, initially <code>(x1,y1)</code>) every unit time, and stop when the object gets within some threshold distance of the destination. This is to account for the fact errors in divisions will accumulate, so if you did an equality check like: </p>
<pre><code>(x,y)==(x2,y2)
</code></pre>
<p>It is unlikely it will ever be true. </p>
<p>Note the above method gives you constant velocity, straight line movement. You may wish to instead use some sort a slightly more complex formula to give the object the appearance of accelerating, maintaining cruise speed, then decelerating. The following formulae may then be useful:</p>
<pre><code>v(t) = u(t) + t*a(t)
x(t) = v(t) + t*v(t)
</code></pre>
<p>This is merely <a href="http://en.wikipedia.org/wiki/Eulers_Method" rel="nofollow">Euler's method</a>, and should suffice for animation purposes. </p>
| 0 | 2008-09-24T13:45:34Z | [
"python",
"animation"
] |
Checking for code changes in all imported python modules | 126,787 | <p>Almost every Python web framework has a simple server that runs a wsgi application and automatically reloads the imported modules every time the source gets changed. I know I can look at the code and see how it's done, but that may take some time and I'm asking just out of curiosity. Does anyone have any idea how this is implemented?</p>
| 1 | 2008-09-24T12:21:02Z | 126,843 | <p>As the author of one of the reloader mechanisms (the one in werkzeug) I can tell you that it doesn't work. What all the reloaders do is forking one time and restarting the child process if a monitor thread notices that one module changed on the file system.</p>
<p>Inline <code>reload()</code>ing doesn't work because references to the reloaded module are not updated.</p>
| 2 | 2008-09-24T12:28:50Z | [
"python"
] |
Checking for code changes in all imported python modules | 126,787 | <p>Almost every Python web framework has a simple server that runs a wsgi application and automatically reloads the imported modules every time the source gets changed. I know I can look at the code and see how it's done, but that may take some time and I'm asking just out of curiosity. Does anyone have any idea how this is implemented?</p>
| 1 | 2008-09-24T12:21:02Z | 126,866 | <p>reload() does not work. "Reloading" is usually implemented by forking.</p>
<p>Implementing "real" reload() is extremely difficult and even the most serious attempt, <a href="http://twistedmatrix.com/documents/current/api/twisted.python.rebuild.html" rel="nofollow">twisted.python.rebuild</a> isn't perfect.</p>
| 1 | 2008-09-24T12:34:47Z | [
"python"
] |
Find out number of capture groups in Python regular expressions | 127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="http://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| 16 | 2008-09-24T13:14:50Z | 127,089 | <p>First of all if you only need the first result of re.findall it's better to just use re.search that returns a match or None.</p>
<p>For the groups number you could count the number of open parenthesis '(' except those that are escaped by '\'. You could use another regex for that:</p>
<pre><code>def num_of_groups(regexp):
rg = re.compile(r'(?<!\\)\(')
return len(rg.findall(regexp))
</code></pre>
<p>Note that this doesn't work if the regex contains non-capturing groups and also if '(' is escaped by using it as '[(]'. So this is not very reliable. But depending on the regexes that you use it might help.</p>
| 1 | 2008-09-24T13:21:55Z | [
"python",
"regex"
] |
Find out number of capture groups in Python regular expressions | 127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="http://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| 16 | 2008-09-24T13:14:50Z | 127,092 | <p>The <code>lastindex</code> property of the match object should be what you are looking for. See the <a href="http://docs.python.org/lib/match-objects.html" rel="nofollow">re module docs</a>.</p>
| 0 | 2008-09-24T13:22:27Z | [
"python",
"regex"
] |
Find out number of capture groups in Python regular expressions | 127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="http://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| 16 | 2008-09-24T13:14:50Z | 127,097 | <p>Something from inside sre_parse might help.</p>
<p>At first glance, maybe something along the lines of:</p>
<pre><code>>>> import sre_parse
>>> sre_parse.parse('(\d)\d(\d)')
[('subpattern', (1, [('in', [('category', 'category_digit')])])),
('in', [('category', 'category_digit')]),
('subpattern', (2, [('in', [('category', 'category_digit')])]))]
</code></pre>
<p>I.e. count the items of type 'subpattern':</p>
<pre><code>import sre_parse
def count_patterns(regex):
"""
>>> count_patterns('foo: \d')
0
>>> count_patterns('foo: (\d)')
1
>>> count_patterns('foo: (\d(\s))')
1
"""
parsed = sre_parse.parse(regex)
return len([token for token in parsed if token[0] == 'subpattern'])
</code></pre>
<p>Note that we're only counting root level patterns here, so the last example only returns 1. To change this, <em>tokens</em> would need to searched recursively.</p>
| 2 | 2008-09-24T13:23:34Z | [
"python",
"regex"
] |
Find out number of capture groups in Python regular expressions | 127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="http://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| 16 | 2008-09-24T13:14:50Z | 127,105 | <p>Might be wrong, but I don't think there is a way to find the number of groups that would have been returned had the regex matched. The only way I can think of to make this work the way you want it to is to pass the number of matches your particular regex expects as an argument.</p>
<p>To clarify though: When findall succeeds, you only want the first match to be returned, but when it fails you want a list of empty strings? Because the comment seems to show all matches being returned as a list.</p>
| 0 | 2008-09-24T13:25:54Z | [
"python",
"regex"
] |
Find out number of capture groups in Python regular expressions | 127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="http://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| 16 | 2008-09-24T13:14:50Z | 127,392 | <p>Using your code as a basis:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * len(m.groups())
</code></pre>
| 1 | 2008-09-24T14:12:57Z | [
"python",
"regex"
] |
Find out number of capture groups in Python regular expressions | 127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="http://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| 16 | 2008-09-24T13:14:50Z | 136,215 | <pre><code>def num_groups(regex):
return re.compile(regex).groups
</code></pre>
| 25 | 2008-09-25T21:18:49Z | [
"python",
"regex"
] |
Find out number of capture groups in Python regular expressions | 127,055 | <p>Is there a way to determine how many capture groups there are in a given regular expression?</p>
<p>I would like to be able to do the follwing:</p>
<pre><code>def groups(regexp, s):
""" Returns the first result of re.findall, or an empty default
>>> groups(r'(\d)(\d)(\d)', '123')
('1', '2', '3')
>>> groups(r'(\d)(\d)(\d)', 'abc')
('', '', '')
"""
import re
m = re.search(regexp, s)
if m:
return m.groups()
return ('',) * num_of_groups(regexp)
</code></pre>
<p>This allows me to do stuff like:</p>
<pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456')
</code></pre>
<p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p>
<p><strong>EDIT:</strong> Following the <a href="http://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p>
<p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p>
<p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
| 16 | 2008-09-24T13:14:50Z | 28,284,530 | <pre><code>f_x = re.search(...)
len_groups = len(f_x.groups())
</code></pre>
| 0 | 2015-02-02T18:42:26Z | [
"python",
"regex"
] |
Contributing to Python | 127,454 | <p>I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?</p>
| 10 | 2008-09-24T14:20:06Z | 127,493 | <p>I guess one way would be to help with documentation (translation, updating), until you are aware enough about the language. Also following the devs and users mail groups would give you a pretty good idea of what is being done and needs to be done by the community.</p>
| 3 | 2008-09-24T14:23:58Z | [
"python"
] |
Contributing to Python | 127,454 | <p>I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?</p>
| 10 | 2008-09-24T14:20:06Z | 127,501 | <p>If you aren't up to actually working on the Python core, there are still many ways to contribute.. 2 that immediately come to mind is:</p>
<p>work on documentation.. it can ALWAYS be improved. Take your favorite modules and check out the documentation and add where you can.</p>
<p>Reporting descriptive bugs is very helpful to the development process.</p>
| 1 | 2008-09-24T14:24:47Z | [
"python"
] |
Contributing to Python | 127,454 | <p>I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?</p>
| 10 | 2008-09-24T14:20:06Z | 127,510 | <p>Get involved with the community: <a href="http://www.python.org/dev/" rel="nofollow">http://www.python.org/dev/</a></p>
| 1 | 2008-09-24T14:25:23Z | [
"python"
] |
Contributing to Python | 127,454 | <p>I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?</p>
| 10 | 2008-09-24T14:20:06Z | 127,601 | <ol>
<li><p>Add to the docs. it is downright crappy</p></li>
<li><p>Help out other users on the dev and user mailing lists. </p></li>
<li><p>TEST PYTHON. bugs in programming languages are real bad. And I have seen someone discover atleast 1 bug in python</p></li>
<li><p>Frequent the #python channel on irc.freenode.net</p></li>
</ol>
| 5 | 2008-09-24T14:43:35Z | [
"python"
] |
Contributing to Python | 127,454 | <p>I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?</p>
| 10 | 2008-09-24T14:20:06Z | 127,651 | <p>Build something cool in Python and share it with others. Small values of cool are still cool. Not everyone gets to write epic, world-changing software. </p>
<p>Every problem solved well using Python is a way of showing how cool Python is.</p>
| 4 | 2008-09-24T14:54:21Z | [
"python"
] |
Contributing to Python | 127,454 | <p>I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?</p>
| 10 | 2008-09-24T14:20:06Z | 127,787 | <p>Start by contributing to a Python project that you use and enjoy. This can be as simple as answering questions on the mailing list or IRC channel, offering to help with documentation and test writing or fixing bugs.</p>
| 0 | 2008-09-24T15:15:24Z | [
"python"
] |
Contributing to Python | 127,454 | <p>I'm a pretty inexperienced programmer (can make tk apps, text processing, sort of understand oop), but Python is so awesome that I would like to help the community. What's the best way for a beginner to contribute?</p>
| 10 | 2008-09-24T14:20:06Z | 132,237 | <p>I see two ways of going about it: working on Python directly or working on something that utilizes Python</p>
<p>Since you're a beginner, you're probably hesitant to work on the core Python language or feel that you can't contribute in a meaningful way, which is understandable. However, as a beginner, you're in a good position to help improve documentation and other items that are essential to learning Python. </p>
<p>For example, the Python tutorial is less of a tutorial (in the standard sense) and more of a feature listing, at least in my opinion. When I tried to learn from it, I never got the feeling that I was building up my knowledge, like creating an application. It felt more like I was being shown all the parts that make up Python but not how to put them together into a cohesive structure.</p>
<p>Once I became more comfortable with the language (mostly through books and lots of practice), I eventually wrote my <a href="http://www.gidnetwork.com/b-26.html" rel="nofollow">own tutorial</a>, trying to provide not only the technical information but also lessons learned and "newbie gotchas".</p>
<p>Alternatively, you can contribute to the Python world by using Python in programs. You can contribute to projects already established, e.g. Django, PyGame, etc., or you can make your own program to "scratch an itch". Either way, you not only build your knowledge of Python but you are giving back to the community. </p>
<p>Finally, you can become an advocate of Python, encouraging others to learn the language. I kept suggesting to my supervisor at my last job to use Python rather than Java when a considering what to use for a new project. I tell everyone I know about the joys of Python and encourage them to give it a try. I convinced the administrator of a computer forum I frequent to create a section for Python. And, as I already said, I wrote a tutorial for Python and I'm working on a new one for wxPython.</p>
<p>There are many ways you can contribute to Python that aren't necessarily programming related. As your programming skills grow, you may want to move further into code contributions. But you may gain more satisfaction by helping others find the same joy you found in Python.</p>
| 2 | 2008-09-25T09:01:24Z | [
"python"
] |
Editing XML as a dictionary in python? | 127,606 | <p>I'm trying to generate customized xml files from a template xml file in python. </p>
<p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p>
<pre><code>conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 8 | 2008-09-24T14:44:45Z | 127,678 | <p>I'm not sure if converting the info set to nested dicts first is easier. Using ElementTree, you can do this:</p>
<pre><code>import xml.etree.ElementTree as ET
doc = ET.parse("template.xml")
lvl1 = doc.findall("level1-name")[0]
lvl1.remove(lvl1.find("leaf1")
lvl1.remove(lvl1.find("leaf2")
# or use del lvl1[idx]
doc.write("config-new.xml")
</code></pre>
<p>ElementTree was designed so that you don't have to convert your XML trees to lists and attributes first, since it uses exactly that internally.</p>
<p>It also support as small subset of <a href="http://effbot.org/zone/element-xpath.htm" rel="nofollow">XPath</a>.</p>
| 11 | 2008-09-24T14:58:52Z | [
"python",
"xml",
"dictionary"
] |
Editing XML as a dictionary in python? | 127,606 | <p>I'm trying to generate customized xml files from a template xml file in python. </p>
<p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p>
<pre><code>conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
</code></pre>
<p>now I want to write to file, but I don't see how to get to
ElementTree.ElementTree.write() </p>
<pre><code>conf_new.write('config-new.xml')
</code></pre>
<p>Is there some way to do this, or can someone suggest doing this a different way? </p>
| 8 | 2008-09-24T14:44:45Z | 127,720 | <p>Have you tried this?</p>
<pre><code>print xml.etree.ElementTree.tostring( conf_new )
</code></pre>
| 0 | 2008-09-24T15:05:01Z | [
"python",
"xml",
"dictionary"
] |
Subsets and Splits