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
Django: Arbitrary number of unnamed urls.py parameters
249,110
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
16
2008-10-30T02:18:32Z
255,251
<p>Same answer came to me while reading the question.</p> <p>I believe model_browse view is the best way to sort the query parameters and use it as a generic router.</p>
0
2008-10-31T23:31:03Z
[ "python", "django", "django-urls" ]
Django: Arbitrary number of unnamed urls.py parameters
249,110
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
16
2008-10-30T02:18:32Z
19,378,600
<p>I think the answer of Adam is more generic than my solution, but if you like to use a fixed number of arguments in the url, you could also do something like this:</p> <p>The following example shows how to get all sales of a day for a location by entering the name of the <code>store</code> and the <code>year</code>, <code>month</code> and <code>day</code>.</p> <p><strong>urls.py</strong>:</p> <pre><code>urlpatterns = patterns('', url(r'^baseurl/location/(?P&lt;store&gt;.+)/sales/(?P&lt;year&gt;[0-9][0-9][0-9][0-9])-(?P&lt;month&gt;[0-9][0-9])-(?P&lt;day&gt;[0-9][0-9])/$', views.DailySalesAtLocationListAPIView.as_view(), name='daily-sales-at-location'), ) </code></pre> <p>Alternativly, you could also use the id of the store by changing <code>(?P&lt;store&gt;.+)</code> to <code>(?P&lt;store&gt;[0-9]+)</code>. Note that <code>location</code> and <code>sales</code> are no keywords, they just improve readability of the url.</p> <p><strong>views.py</strong></p> <pre><code>class DailySalesAtLocationListAPIView(generics.ListAPIView): def get(self, request, store, year, month, day): # here you can start using the values from the url print store print year print month print date # now start filtering your model </code></pre> <p>Hope it helps anybody!</p> <p>Best regards,</p> <p>Michael</p>
0
2013-10-15T10:15:03Z
[ "python", "django", "django-urls" ]
Django: Arbitrary number of unnamed urls.py parameters
249,110
<p>I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:</p> <pre><code>/browse/&lt;name1&gt;/&lt;value1&gt;/&lt;name2&gt;/&lt;value2&gt;/ .... etc .... </code></pre> <p>where 'name' maps to a model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.</p> <p>Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.</p> <p>Ideally each name/value pair will be passed to the view function as a parameter named <code>name1</code>, <code>name2</code>, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?</p> <p>So, it seems I need to do something like this:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:</p> <pre><code>urlpatterns = patterns('', url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"), ) </code></pre> <p>... and got the same problem, but this time <code>*args</code> only includes the last matched pattern.</p> <p>Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.*) pattern?</p>
16
2008-10-30T02:18:32Z
35,575,143
<p>I've an alternative solution, which isn't quite different from the previous but it's more refined:</p> <p><code>url(r'^my_app/(((list\/)((\w{1,})\/(\w{1,})\/(\w{1,3})\/){1,10})+)$'</code></p> <p>I've used <a href="https://docs.djangoproject.com/en/1.9/topics/http/urls/#example" rel="nofollow">unnamed url parameters</a> and a repetitive regexp. Not to get the "is not a valid regular expression: multiple repeat" i place a word at the beginning of the list.</p> <p>I'm still working at the view receiving the list. But i think ill' go through the args or kwargs.. Cannot still say it exactly.</p> <p>My 2 cents</p>
0
2016-02-23T10:37:31Z
[ "python", "django", "django-urls" ]
Jython 2.2.1, howto move a file? shutils.move is non-existant!
249,262
<pre><code>'''use Jython''' import shutil print dir(shutil) </code></pre> <p>There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython?</p>
0
2008-10-30T04:22:08Z
249,279
<p><code>os.rename()</code> to move, and <code>os.unlink()</code> to delete -- just like Python pre-<code>shutil</code>.</p>
4
2008-10-30T04:28:47Z
[ "java", "python", "jython", "file-handling", "shutil" ]
Jython 2.2.1, howto move a file? shutils.move is non-existant!
249,262
<pre><code>'''use Jython''' import shutil print dir(shutil) </code></pre> <p>There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython?</p>
0
2008-10-30T04:22:08Z
250,933
<p>If you need support for moving across filesystems, consider just copying CPython's <code>shutil.py</code> into your project. <A HREF="http://www.python.org/download/releases/2.4.2/license/" rel="nofollow">The Python License</A> is flexible enough to allow this (even for commercial projects), as long as licensing and attribution information are retained.</p>
1
2008-10-30T17:00:21Z
[ "java", "python", "jython", "file-handling", "shutil" ]
Jython 2.2.1, howto move a file? shutils.move is non-existant!
249,262
<pre><code>'''use Jython''' import shutil print dir(shutil) </code></pre> <p>There is no, shutil.move, how does one move a file with Jython? and while we at it, how does one delete a file with Jython?</p>
0
2008-10-30T04:22:08Z
2,334,425
<pre><code>f1 = File(filename_old) f1.nameTo(File(filename_new)) </code></pre>
0
2010-02-25T13:58:08Z
[ "java", "python", "jython", "file-handling", "shutil" ]
Virtualenv on Ubuntu with no site-packages
249,283
<p>I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.</p> <p>What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?</p>
24
2008-10-30T04:32:52Z
249,342
<p>One way is to add the paths to your code using sys.path.</p> <pre><code>import sys sys.path.append(somepath) </code></pre> <p>Another way is to use site, which processes .pth files in addition to adding to sys.path.</p> <pre><code>import site site.addsitedir(sitedir, known_paths=None) </code></pre> <p><a href="https://docs.python.org/library/site.html" rel="nofollow">https://docs.python.org/library/site.html</a></p> <p>But you probably don't want to add this to all your related code. </p> <p>I've seen mention of sitecustomize.py being used to perform something like this, but after some testing I couldn't get it to work as might be expected. </p> <p>Here it mentions that auto-import of sitecustomize.py ended in 2.5, if your not on 2.5 try it out. (just add one of the path add methods above to the file and drop it in the directory your program is run) A work around method is mentioned in the post for users of 2.5 and up. </p> <p><a href="http://code.activestate.com/recipes/552729/" rel="nofollow">http://code.activestate.com/recipes/552729/</a></p>
4
2008-10-30T05:22:13Z
[ "python", "ubuntu", "pygtk", "virtualenv" ]
Virtualenv on Ubuntu with no site-packages
249,283
<p>I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.</p> <p>What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?</p>
24
2008-10-30T04:32:52Z
249,708
<p>I find in this situation, symlinks, or even copying specific files (packages, modules, extensions) works really well.</p> <p>It allows the program to emulate being run in the target environment, rather than changing the application to suit the development environment.</p> <p>Same deal for something like AppEngine.</p>
1
2008-10-30T09:57:08Z
[ "python", "ubuntu", "pygtk", "virtualenv" ]
Virtualenv on Ubuntu with no site-packages
249,283
<p>I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.</p> <p>What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?</p>
24
2008-10-30T04:32:52Z
1,670,513
<pre><code>$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv $ cd myvirtualenv $ source bin/activate $ cd lib/python2.6/ $ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ $ ln -s /usr/lib/pymodules/python2.6/pygtk.pth $ ln -s /usr/lib/pymodules/python2.6/pygtk.py $ ln -s /usr/lib/pymodules/python2.6/cairo/ $ python &gt;&gt;&gt; import pygtk &gt;&gt;&gt; import gtk </code></pre>
34
2009-11-03T22:20:07Z
[ "python", "ubuntu", "pygtk", "virtualenv" ]
Virtualenv on Ubuntu with no site-packages
249,283
<p>I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.</p> <p>What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?</p>
24
2008-10-30T04:32:52Z
12,134,232
<p>Check out the postmkvirtualenv hook script here: </p> <p><a href="http://stackoverflow.com/a/9716100/60247">http://stackoverflow.com/a/9716100/60247</a></p> <p>In that case, he's using it to import PyQt and SIP after a new Virtualenv is created, but you can add the packages that you need to LIBS. </p> <p>And vote that script up because it's fantastic :)</p>
1
2012-08-26T21:56:56Z
[ "python", "ubuntu", "pygtk", "virtualenv" ]
Virtualenv on Ubuntu with no site-packages
249,283
<p>I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky. The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.</p> <p>What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?</p>
24
2008-10-30T04:32:52Z
27,471,458
<p>If you want to include the links to the relevant system's python gtk-2.0 in the virtualenv, you can just use pip to install <a href="https://pypi.python.org/pypi/ruamel.venvgtk" rel="nofollow">ruamel.venvgtk</a>:</p> <p>pip install ruamel.venvgtk You don't have import anything, the links are setup during installation.</p> <p>This is especially handy if you are using <code>tox</code>, in that case you only need to include the dependency (for tox):</p> <pre><code>deps: pytest ruamel.venvgtk </code></pre> <p>and a newly setup python2.7 environment will have the relevant links included before the tests are run.</p> <p>More detailed information on how the links are setup can be found in <a href="http://stackoverflow.com/a/27471354/1307905">this answer</a></p>
0
2014-12-14T16:38:33Z
[ "python", "ubuntu", "pygtk", "virtualenv" ]
Translate SVN path to local file system path in Python
249,330
<p>I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository.</p> <p>I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run.</p> <p>I am at the point where I am translating the path names in SVN to the path names on my local copy.</p> <p>Currently I have written the following to do the job:</p> <pre><code>def formatPaths(self, paths): newPaths = list() for path in paths: path = path[len(self.basePath):] path = path.replace("/", "\\") newPaths.append(path) return newPaths </code></pre> <p>self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1").</p> <p>Is this a good way to solve this problem or is there some magical function I missed?</p>
0
2008-10-30T05:07:18Z
249,444
<p>Hm... That would do it:</p> <pre><code>baselen = len(self.basePath) for path in paths: path = path[baselen:].replace("/", "\\") newPaths.append(path) return newPaths </code></pre> <p>If you like, you can do it like this:</p> <pre><code>baselen = len(self.basePath) return (path[baselen:].replace("/", "\\") for path in paths) </code></pre> <p>Not calculating <code>baselen</code> in every loop iteration is also good practice.</p>
0
2008-10-30T06:53:28Z
[ "python", "svn" ]
Translate SVN path to local file system path in Python
249,330
<p>I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository.</p> <p>I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run.</p> <p>I am at the point where I am translating the path names in SVN to the path names on my local copy.</p> <p>Currently I have written the following to do the job:</p> <pre><code>def formatPaths(self, paths): newPaths = list() for path in paths: path = path[len(self.basePath):] path = path.replace("/", "\\") newPaths.append(path) return newPaths </code></pre> <p>self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1").</p> <p>Is this a good way to solve this problem or is there some magical function I missed?</p>
0
2008-10-30T05:07:18Z
249,650
<p>Stay with the slice operator, but do not change the loop variable inside the loop. for fun, try the generator expression (or keep the listcomp).</p> <pre><code>baselen = len(self.basePath) return (path[baselen:].replace("/", "\\") for path in paths) </code></pre> <p>Edit: `lstrip()' is not relevant here. From the <a href="http://docs.python.org/library/stdtypes.html#string-methods" rel="nofollow">manual</a>:</p> <blockquote> <p>str.lstrip([chars])</p> <p>Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on.</p> </blockquote>
2
2008-10-30T09:23:15Z
[ "python", "svn" ]
Translate SVN path to local file system path in Python
249,330
<p>I'm writing a utility in Python that will attach changed files in Subversion to an email and send it when a subset of folders that are under source control in SVN have been changed. I am using the pysvn library to access the repository.</p> <p>I have a copy of the files on my local file system and I do an update to check if the files have changed since the last time the utility was run.</p> <p>I am at the point where I am translating the path names in SVN to the path names on my local copy.</p> <p>Currently I have written the following to do the job:</p> <pre><code>def formatPaths(self, paths): newPaths = list() for path in paths: path = path[len(self.basePath):] path = path.replace("/", "\\") newPaths.append(path) return newPaths </code></pre> <p>self.basePath would be something like "/trunk/project1" and I'm looking to just get the relative path of a subset of folders (I.e. folder1 under "/trunk/project1").</p> <p>Is this a good way to solve this problem or is there some magical function I missed?</p>
0
2008-10-30T05:07:18Z
249,743
<p>Your specific solution to the path name copy is reasonable, but your general solution to the entire problem could be improved.</p> <p>I would <code>easy_install anyvc</code>, a library developed for the <a href="http://pida.co.uk/" rel="nofollow">PIDA IDE</a> which is a uniform python interface into version control systems, and use it instead:</p> <pre><code>from anyvc import Subversion vc = Subversion('/trunk') modified = [f.relpath for f in vc.list() if f.state != 'clean'] for f in modified: print f.relpath # the relative path of the file to the source root </code></pre> <p>Additionally, I would probably attach a diff to an email rather than the actual file. But I guess that's your choice.</p>
0
2008-10-30T10:10:53Z
[ "python", "svn" ]
Python with PIL and Libjpeg on Leopard
249,388
<p>I'm having trouble getting pictures supported with PIL - it throws me this:</p> <pre><code>IOError: decoder jpeg not available </code></pre> <p>I installed PIL from binary, not realizing I needed libjpeg.</p> <p>I installed libjpeg and freetype2 through fink. </p> <p>I tried to reinstall PIL using instructions from <a href="http://timhatch.com/" rel="nofollow">http://timhatch.com/</a> (bottom of the page)</p> <ul> <li>Download PIL 1.1.6 source package and have the Developer Tools already installed</li> <li><p>Patch setup.py with this patch so it can find the Freetype you already have.</p> <p><code>patch -p0 &lt; leopard_freetype2.diff</code></p></li> <li>sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)</li> </ul> <p>But I'm still getting the same error. </p> <p>I'm on Leopard PPC. </p>
3
2008-10-30T06:00:14Z
249,406
<p>Is the python path still looking at the old binary version of libjpeg?</p> <p>You will need to modify it to point to the new place if it is.</p> <p>When you compiled the new version of the PIL did it say that it found libjpeg? It will compile happily without it (iirc) and the first sign of trouble you will see is at include time.</p> <p>You will need to adjust the path at ./configure time.</p> <p>The diff might just not work for you. You should test some more and then perhaps file a bug.</p>
0
2008-10-30T06:14:06Z
[ "python", "python-imaging-library", "libjpeg", "python-install" ]
Python with PIL and Libjpeg on Leopard
249,388
<p>I'm having trouble getting pictures supported with PIL - it throws me this:</p> <pre><code>IOError: decoder jpeg not available </code></pre> <p>I installed PIL from binary, not realizing I needed libjpeg.</p> <p>I installed libjpeg and freetype2 through fink. </p> <p>I tried to reinstall PIL using instructions from <a href="http://timhatch.com/" rel="nofollow">http://timhatch.com/</a> (bottom of the page)</p> <ul> <li>Download PIL 1.1.6 source package and have the Developer Tools already installed</li> <li><p>Patch setup.py with this patch so it can find the Freetype you already have.</p> <p><code>patch -p0 &lt; leopard_freetype2.diff</code></p></li> <li>sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)</li> </ul> <p>But I'm still getting the same error. </p> <p>I'm on Leopard PPC. </p>
3
2008-10-30T06:00:14Z
249,414
<p>I had the similar 'jpeg decoder problem' recently when deploying a django project on a product RHEL box that required PIL. I downloaded PIL, and ran 'python setup.py install' instantly, and was happy that everything was working, until I bumped into the problem. Solution: libjpeg was already installed on the system, so I installed libjpeg-devel. I went back into the source of PIL and ran 'python setup.py build', at the end of which, in the output where it shows whether PIL configure was able to detect support for jpeg, gif, freetype, etc, it said that jpeg support was ok. After installing PIL, it worked fine.</p>
1
2008-10-30T06:31:00Z
[ "python", "python-imaging-library", "libjpeg", "python-install" ]
Python with PIL and Libjpeg on Leopard
249,388
<p>I'm having trouble getting pictures supported with PIL - it throws me this:</p> <pre><code>IOError: decoder jpeg not available </code></pre> <p>I installed PIL from binary, not realizing I needed libjpeg.</p> <p>I installed libjpeg and freetype2 through fink. </p> <p>I tried to reinstall PIL using instructions from <a href="http://timhatch.com/" rel="nofollow">http://timhatch.com/</a> (bottom of the page)</p> <ul> <li>Download PIL 1.1.6 source package and have the Developer Tools already installed</li> <li><p>Patch setup.py with this patch so it can find the Freetype you already have.</p> <p><code>patch -p0 &lt; leopard_freetype2.diff</code></p></li> <li>sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)</li> </ul> <p>But I'm still getting the same error. </p> <p>I'm on Leopard PPC. </p>
3
2008-10-30T06:00:14Z
1,252,888
<p>I had the same problem and this guy's post provided the solution for me:</p> <p>rm the PIL subdir and the PIL.pth file in the Imaging-1.1.6 subdir</p> <p>full details here:</p> <p><a href="http://blog.tlensing.org/2008/12/04/kill-pil-%E2%80%93-the-python-imaging-library-headache/" rel="nofollow">http://blog.tlensing.org/2008/12/04/kill-pil-%E2%80%93-the-python-imaging-library-headache/</a></p> <p>After doing this, the selftest.py worked fine. I should also note that I am using the macports version of the jpeg library and I had already specified the JPEG_ROOT to point to the include and lib paths in my macports root</p>
1
2009-08-10T02:24:39Z
[ "python", "python-imaging-library", "libjpeg", "python-install" ]
Python with PIL and Libjpeg on Leopard
249,388
<p>I'm having trouble getting pictures supported with PIL - it throws me this:</p> <pre><code>IOError: decoder jpeg not available </code></pre> <p>I installed PIL from binary, not realizing I needed libjpeg.</p> <p>I installed libjpeg and freetype2 through fink. </p> <p>I tried to reinstall PIL using instructions from <a href="http://timhatch.com/" rel="nofollow">http://timhatch.com/</a> (bottom of the page)</p> <ul> <li>Download PIL 1.1.6 source package and have the Developer Tools already installed</li> <li><p>Patch setup.py with this patch so it can find the Freetype you already have.</p> <p><code>patch -p0 &lt; leopard_freetype2.diff</code></p></li> <li>sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)</li> </ul> <p>But I'm still getting the same error. </p> <p>I'm on Leopard PPC. </p>
3
2008-10-30T06:00:14Z
1,475,112
<p>If you build with libjpeg, but selftest fails, you probably have another install of PIL that's confusing things. Try installing it, and see if selftest works then.</p> <p>Also the direct link to the instructions referenced in the OP is <a href="http://timhatch.com/ark/2008/08/12/quick-howto-for-pil-on-leopard" rel="nofollow" title="Quick Howto for PIL on Leopard">here</a></p>
0
2009-09-25T02:18:15Z
[ "python", "python-imaging-library", "libjpeg", "python-install" ]
Python with PIL and Libjpeg on Leopard
249,388
<p>I'm having trouble getting pictures supported with PIL - it throws me this:</p> <pre><code>IOError: decoder jpeg not available </code></pre> <p>I installed PIL from binary, not realizing I needed libjpeg.</p> <p>I installed libjpeg and freetype2 through fink. </p> <p>I tried to reinstall PIL using instructions from <a href="http://timhatch.com/" rel="nofollow">http://timhatch.com/</a> (bottom of the page)</p> <ul> <li>Download PIL 1.1.6 source package and have the Developer Tools already installed</li> <li><p>Patch setup.py with this patch so it can find the Freetype you already have.</p> <p><code>patch -p0 &lt; leopard_freetype2.diff</code></p></li> <li>sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)</li> </ul> <p>But I'm still getting the same error. </p> <p>I'm on Leopard PPC. </p>
3
2008-10-30T06:00:14Z
4,533,995
<p>I have stuck to this problem for quite a few hours today. And my advice is do NOT do trial and error again and again, unless u could fix the problem in first 15 minutes.</p> <p>there are a few tools for you to diagnose the problem:</p> <p>1.check the if jpeg lib architcture matches your machine architecture:</p> <pre><code>file /usr/local/lib/libjpeg.7.dylib </code></pre> <p>2.check if the _imaging.so acutally linked to your compiled jpeg lib</p> <pre><code>cd ImageSrc python setup.py build_ext -i otool -L PIL/_imaging.so </code></pre> <p>3.try to import _imaging.so and see what's the problem</p> <pre><code>cd PIL python import _imaging </code></pre> <p>4.finally, try to remove all previous installed PIL* from python "site-package" directory to make sure set up does work</p> <pre><code>python setup.py install </code></pre> <p>For me, it's due to I am using 32 bit python on snow leopard, and solved the problem by install jpeg lib in this way:</p> <pre><code>./configure CFLAGS="-arch i386" --enable-shared --enable-static </code></pre>
0
2010-12-26T13:34:05Z
[ "python", "python-imaging-library", "libjpeg", "python-install" ]
How to determine if a directory is on same partition
249,775
<p>Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?</p> <p>What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:</p> <pre><code>target_directory = "/Volumes/externalDrive/something/" input_foldername, input_filename = os.path.split(input_file) if same_partition(input_foldername, target_directory): copy(input_file, target_directory) else: move(input_file, target_directory) </code></pre> <p><hr /></p> <p>Thanks to CesarB's answer, the <code>same_partition</code> function implemented:</p> <pre><code>import os def same_partition(f1, f2): return os.stat(f1).st_dev == os.stat(f2).st_dev </code></pre>
6
2008-10-30T10:45:42Z
249,796
<p>In C, you would use <code>stat()</code> and compare the <code>st_dev</code> field. In python, <code>os.stat</code> should do the same.</p>
11
2008-10-30T10:54:11Z
[ "python", "linux", "osx", "filesystems" ]
How to determine if a directory is on same partition
249,775
<p>Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?</p> <p>What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:</p> <pre><code>target_directory = "/Volumes/externalDrive/something/" input_foldername, input_filename = os.path.split(input_file) if same_partition(input_foldername, target_directory): copy(input_file, target_directory) else: move(input_file, target_directory) </code></pre> <p><hr /></p> <p>Thanks to CesarB's answer, the <code>same_partition</code> function implemented:</p> <pre><code>import os def same_partition(f1, f2): return os.stat(f1).st_dev == os.stat(f2).st_dev </code></pre>
6
2008-10-30T10:45:42Z
250,149
<p>Another way is the “better to ask forgiveness than permission” approach—just try to rename it, and if that fails, catch the appropriate <code>OSError</code> and try the copy approach. ie:</p> <pre><code>import errno try: os.rename(source, dest): except IOError, ex: if ex.errno == errno.EXDEV: # perform the copy instead. </code></pre> <p>This has the advantage that it will also work on Windows, where st_dev is always 0 for all partitions.</p> <p>Note that if you actually want to copy and then delete the source file (ie. perform a move), rather than just copy, then shutil.move will already do what you want:</p> <pre> Help on function move in module shutil: move(src, dst) Recursively move a file or directory to another location. If the destination is on our current filesystem, then simply use rename. Otherwise, copy src to the dst and then remove src. </pre> <p>[Edit] Updated due to Matthew Schinckel's comment to mention that shutil.move will delete the source after the copy, which isn't necessarily what is wanted, as the question just mentions copying.</p>
3
2008-10-30T13:21:02Z
[ "python", "linux", "osx", "filesystems" ]
OS X: Determine Trash location for a given path
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
1
2008-10-30T10:50:32Z
249,800
<p>The File Manager API has a pair of functions called FSMoveObjectToTrashAsync and FSPathMoveObjectToTrashSync.</p> <p>Not sure if that is exposed to Python or not.</p>
2
2008-10-30T10:57:06Z
[ "python", "osx", "filesystems" ]
OS X: Determine Trash location for a given path
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
1
2008-10-30T10:50:32Z
251,566
<p>Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code <a href="http://osx-trash.rubyforge.org/git?p=osx-trash.git;a=blob;f=bin/trash;h=26911131eacafd659b4d760bda1bd4c99dc2f918;hb=HEAD">here</a> via RubyCocoa. The the gist of it is:</p> <pre><code>url = NSURL.fileURLWithPath(path) finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder") item = finder.items.objectAtLocation(url) item.delete </code></pre> <p>You could easily do something similar with PyObjC.</p>
5
2008-10-30T20:07:26Z
[ "python", "osx", "filesystems" ]
OS X: Determine Trash location for a given path
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
1
2008-10-30T10:50:32Z
252,920
<p>Based upon code from <a href="http://www.cocoadev.com/index.pl?MoveToTrash" rel="nofollow">http://www.cocoadev.com/index.pl?MoveToTrash</a> I have came up with the following:</p> <pre><code>def get_trash_path(input_file): path, file = os.path.split(input_file) if path.startswith("/Volumes/"): # /Volumes/driveName/.Trashes/&lt;uid&gt; s = path.split(os.path.sep) # s[2] is drive name ([0] is empty, [1] is Volumes) trash_path = os.path.join("/Volumes", s[2], ".Trashes", str(os.getuid())) if not os.path.isdir(trash_path): raise IOError("Volume appears to be a network drive (%s could not be found)" % (trash_path)) else: trash_path = os.path.join(os.getenv("HOME"), ".Trash") return trash_path </code></pre> <p>Fairly basic, and there's a few things that have to be done seperatly, particularly checking if the filename already exist in trash (to avoid overwriting) and the actual moving to trash, but it seems to cover most things (internal, external and network drives)</p> <p><strong>Update:</strong> I wanted to trash a file in a Python script, so I re-implemented Dave Dribin's solution in Python:</p> <pre><code>from AppKit import NSURL from ScriptingBridge import SBApplication def trashPath(path): """Trashes a path using the Finder, via OS X's Scripting Bridge. """ targetfile = NSURL.fileURLWithPath_(path) finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder") items = finder.items().objectAtLocation_(targetfile) items.delete() </code></pre> <p>Usage is simple:</p> <pre><code>trashPath("/tmp/examplefile") </code></pre>
4
2008-10-31T09:03:45Z
[ "python", "osx", "filesystems" ]
OS X: Determine Trash location for a given path
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
1
2008-10-30T10:50:32Z
621,219
<p>A better way is <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace%5FClass/Reference/Reference.html#//apple%5Fref/doc/c%5Fref/NSWorkspaceRecycleOperation" rel="nofollow">NSWorkspaceRecycleOperation</a>, which is one of the operations you can use with <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWorkspace%5FClass/Reference/Reference.html#//apple%5Fref/occ/instm/NSWorkspace/performFileOperation:source:destination:files:tag:" rel="nofollow">-[NSWorkspace performFileOperation:source:destination:files:tag:]</a>. The constant's name is another artifact of Cocoa's NeXT heritage; its function is to move the item to the Trash.</p> <p>Since it's part of Cocoa, it should be available to both Python and Ruby.</p>
3
2009-03-07T03:03:07Z
[ "python", "osx", "filesystems" ]
OS X: Determine Trash location for a given path
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
1
2008-10-30T10:50:32Z
3,654,566
<p>Another one in ruby:</p> <pre><code>Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete </code></pre> <p>You will need <a href="http://rubygems.org/gems/rb-appscript" rel="nofollow">rb-appscript</a> gem, you can read about it <a href="http://appscript.sourceforge.net/rb-appscript/index.html" rel="nofollow">here</a></p>
1
2010-09-06T22:14:55Z
[ "python", "osx", "filesystems" ]
OS X: Determine Trash location for a given path
249,785
<p>Simply moving the file to <code>~/.Trash/</code> will not work, as if the file os on an external drive, it will move the file to the main system drive..</p> <p>Also, there are other conditions, like files on external drives get moved to <code>/Volumes/.Trash/501/</code> (or whatever the current user's ID is)</p> <p>Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python</p>
1
2008-10-30T10:50:32Z
5,012,645
<p>In Python, without using the scripting bridge, you can do this:</p> <pre><code>from AppKit import NSWorkspace, NSWorkspaceRecycleOperation source = "path holding files" files = ["file1", "file2"] ws = NSWorkspace.sharedWorkspace() ws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, "", files, None) </code></pre>
2
2011-02-16T04:56:14Z
[ "python", "osx", "filesystems" ]
How can I add post-install scripts to easy_install / setuptools / distutils?
250,038
<p>I would like to be able to add a hook to my setup.py that will be run post-install (either when easy_install'ing or when doing python setup.py install).</p> <p>In my project, <a href="http://code.google.com/p/pysmell">PySmell</a>, I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get copied in the actual egg, and the user has to fish them out and place them in his .vim or .emacs directories. What I want is either asking the user, post-installation, where would he like these files copied, or even just a message printing the location of the files and what should he do with them.</p> <p>What is the best way to do this?</p> <p>Thanks</p> <p>My setup.py looks like so:</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup version = __import__('pysmell.pysmell').pysmell.__version__ setup( name='pysmell', version = version, description = 'An autocompletion library for Python', author = 'Orestis Markou', author_email = '[email protected]', packages = ['pysmell'], entry_points = { 'console_scripts': [ 'pysmell = pysmell.pysmell:main' ] }, data_files = [ ('vim', ['pysmell.vim']), ('emacs', ['pysmell.el']), ], include_package_data = True, keywords = 'vim autocomplete', url = 'http://code.google.com/p/pysmell', long_description = """\ PySmell is a python IDE completion helper. It tries to statically analyze Python source code, without executing it, and generates information about a project's structure that IDE tools can use. The first target is Vim, because that's what I'm using and because its completion mechanism is very straightforward, but it's not limited to it. """, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Utilities', 'Topic :: Text Editors', ] ) </code></pre> <p>EDIT:</p> <p>Here's a stub which demonstrates the <code>python setup.py install</code>:</p> <pre><code>from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) print post_install_message setup( cmdclass={'install': install}, ... </code></pre> <p>No luck with the easy_install route yet.</p>
30
2008-10-30T12:42:10Z
253,103
<p>It depends on how the user installs your package. If the user actually runs "setup.py install", it's fairly easy: Just add another subcommand to the install command (say, install_vim), whose run() method will copy the files you want in the places where you want them. You can add your subcommand to install.sub_commands, and pass the command into setup().</p> <p>If you want a post-install script in a binary, it depends on the type of binary you are creating. For example, bdist_rpm, bdist_wininst, and bdist_msi have support for post-install scripts, because the underlying packing formats support post-install scripts.</p> <p>bdist_egg doesn't support a post-install mechanism by design:</p> <p><a href="http://bugs.python.org/setuptools/issue41">http://bugs.python.org/setuptools/issue41</a></p>
7
2008-10-31T10:33:46Z
[ "python", "setuptools", "distutils" ]
How can I add post-install scripts to easy_install / setuptools / distutils?
250,038
<p>I would like to be able to add a hook to my setup.py that will be run post-install (either when easy_install'ing or when doing python setup.py install).</p> <p>In my project, <a href="http://code.google.com/p/pysmell">PySmell</a>, I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get copied in the actual egg, and the user has to fish them out and place them in his .vim or .emacs directories. What I want is either asking the user, post-installation, where would he like these files copied, or even just a message printing the location of the files and what should he do with them.</p> <p>What is the best way to do this?</p> <p>Thanks</p> <p>My setup.py looks like so:</p> <pre><code>#!/usr/bin/env python # -*- coding: UTF-8 -*- from setuptools import setup version = __import__('pysmell.pysmell').pysmell.__version__ setup( name='pysmell', version = version, description = 'An autocompletion library for Python', author = 'Orestis Markou', author_email = '[email protected]', packages = ['pysmell'], entry_points = { 'console_scripts': [ 'pysmell = pysmell.pysmell:main' ] }, data_files = [ ('vim', ['pysmell.vim']), ('emacs', ['pysmell.el']), ], include_package_data = True, keywords = 'vim autocomplete', url = 'http://code.google.com/p/pysmell', long_description = """\ PySmell is a python IDE completion helper. It tries to statically analyze Python source code, without executing it, and generates information about a project's structure that IDE tools can use. The first target is Vim, because that's what I'm using and because its completion mechanism is very straightforward, but it's not limited to it. """, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development', 'Topic :: Utilities', 'Topic :: Text Editors', ] ) </code></pre> <p>EDIT:</p> <p>Here's a stub which demonstrates the <code>python setup.py install</code>:</p> <pre><code>from setuptools.command.install import install as _install class install(_install): def run(self): _install.run(self) print post_install_message setup( cmdclass={'install': install}, ... </code></pre> <p>No luck with the easy_install route yet.</p>
30
2008-10-30T12:42:10Z
7,931,715
<p>As a work-around, you could set the zip_ok option to false so that your project is installed as an unzipped directory, then it will be a little easier for your users to find the editor config file.</p> <p>In distutils2, it will be possible to install things to more directories, including custom directories, and to have pre/post-install/remove hooks.</p>
0
2011-10-28T15:56:28Z
[ "python", "setuptools", "distutils" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
250,158
<p>Just because it is "marketed" (in some general sense) as a special-purpose language for embedded script engines, does not mean that it is limited to that. In fact, WoW could probably just as well have chosen Python as their embedded scripting language.</p>
10
2008-10-30T13:24:26Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
250,168
<p>It's probably because Lua was designed as a scripting and extension language. On the <a href="http://www.lua.org/about.html">official site</a> it's described as a powerful, fast, light-weight, embeddable scripting language. There's nothing stopping you from writing general purpose programs for it (if I recall correctly it ships with an interpreter and compiler), but the language designers intended it to be used mainly as an embedded language (hence being light-weight and all)</p>
9
2008-10-30T13:28:04Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
251,372
<p>Definitely a lack of standard libraries. It's also lesser known than Python, Perl or Ruby.</p>
6
2008-10-30T19:13:31Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
252,900
<p>Lua is a cool language, light-weight and extremely fast!</p> <p>But the point is: <strong>Is performance so important for those tasks you mentioned?</strong></p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>You write those programs once, and run them once, too maybe. Why do you care about performance so much for a run-once program?</p> <p>For example:</p> <ol> <li>Cost 3 hours to write a C/C++ program, to handle data once, the program will take 1 hour to run.</li> <li>Cost 30 Minute to write a Python program to handle data once, the program will take 10 hours to run.</li> </ol> <p>If you choose the first, you save the time to run the program, but you cost your time to develop the program.</p> <p>On the other hand, if you choose the second, you waste time to run the program, but you can do other things when the program is running. <strong>How about play World of Warcraft, kill monsters with your warlock? Eat my D.O.T</strong>! :P</p> <p>That's it! Although Lua is not so difficult to write, everything about Lua is designed to be efficient.And what's more, there are little modules for Lua, but there are so many modules for Python. You don't want to port a C library for Lua just for a run-once program, do you? Instead, choose Python and use those module to achieve your task easily might be a better idea.</p> <p>FYI: Actually, I have tried to use Lua to do webscraping, but finally, I realized I do not have to care so much about language performance. <strong>The bottleneck of webscraping is not on the performance of the language</strong>. The bottleneck is on network I/O, HTML parsing and multitasking. All I have to do is make sure the program works and find the bottleneck. Finally, I chose Python rather than Lua. There is so many excellent Python modules; I have no reason to build my own.</p> <p>According to my experience about webscraping, I chose Twisted for network I/O and lxml for html parsing as the backend of my webscraping program. I have wrote an article for an introduction to this technology.</p> <p><a href="http://blog.ez2learn.com/2009/09/26/the-best-choice-to-grab-data-from-websites-python-twisted-lxml/">The best choice to grab data from websites: Python + Twisted + lxml</a></p> <p>Hope this is helpful.</p>
33
2008-10-31T08:48:29Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
253,659
<p>I think the answer about it being a "marketing" thing is probably correct, along with the lack of a large set of libraries to choose from. I would like to point out another case of this: Ruby. Ruby is meant to be a general purpose scripting language. The problem is that since Ruby on Rails has risen to be so popular, it is becoming hard to find something that is unrelated to Rails. I'm afraid Lua will suffer this as well, being popular because of a few major things using it, but never able to break free of that stigma.</p>
3
2008-10-31T14:15:15Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
253,755
<p>Lua has fewer libraries than Python. But be sure to have a look at <a href="http://luaforge.net/">LuaForge</a>. It has a lot of interesting libs, like <a href="http://luaforge.net/projects/luacurl/">LuaCURL</a>, <a href="http://wxlua.sourceforge.net/">wxLua</a> or <a href="http://luaforge.net/projects/getopt/">getopt</a>.</p> <p>Then, visit <a href="http://luarocks.org/">LuaRocks</a>, the package management system for Lua. With it, you can search and install most mature Lua modules with dependencies. It feels like <a href="http://en.wikipedia.org/wiki/RubyGems">RubyGems</a> or <a href="http://en.wikipedia.org/wiki/Aptitude%5F%28software%29">aptitude</a>.</p> <p>The site <a href="http://lua-users.org/">lua-users.org</a> has a lot of interesting resources too, like tutorials or the <a href="http://lua-users.org/wiki">Lua Wiki</a>.</p> <p>What I like about Lua is not its speed, it's its minimal core language, flexibility and extensibility.</p> <p>That said, I would probably use Python for the tasks you mentionned because of the larger community doing such things in Python.</p>
21
2008-10-31T14:40:55Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
326,660
<p>This is a sociological question, not a programming question.</p> <p>I use Lua for general-purpose scripting almost exclusively. But I had to write a few hundred lines of code so that Lua would play better with the shell. This included such tricks as </p> <ul> <li>Quoting a string so it is seen as one word by the shell</li> <li>Writing a function to capture the output of a command as in shell $(command)</li> <li>Writing a function to crawl the filesystem using the Lua posix library and expand shell globbing patterns</li> </ul> <p>(For those who may be interested, I've left the code in my <a href="http://www.cs.tufts.edu/~nr/drop/lua/">Lua drop box</a>, which also contains some other stuff. The interesting stuff is probably in <code>osutil</code> in <code>os.quote</code>, <code>os.runf</code>, <code>os.capture</code>, and maybe <code>os.execve</code>. The globbing is in <a href="http://www.cs.tufts.edu/~nr/drop/lua/posixutil.lua"><code>posixutil.lua</code></a>. They both use Luiz Henrique de Figuereido's <a href="http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/">Lua Posix library</a>.)</p> <p>To me, the extra effort is worth it because I can deal with simple syntax and great data structures. To others, a more direct connection with the shell might be preferred.</p>
8
2008-11-28T20:56:38Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
370,746
<p>Lack of standard library. Period. Even listing all the files in a directory require <a href="http://www.keplerproject.org/luafilesystem" rel="nofollow">a non-standard module</a>.</p> <p>There are good reasons for that (keeping strict ANSI portability, not requiring POSIX) but the result is that, for general programming, I prefer Python.</p>
4
2008-12-16T08:56:51Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
568,728
<p>There has been a recent push to create a batteries included installation for Lua on Windows. The result can be found at the <a href="http://luaforge.net/projects/luaforwindows/" rel="nofollow">Lua for Windows</a> project at LuaForge. It includes the interpreter and a large collection of extra modules allowing useful scripts and applications to be written and used out of the box.</p> <p>I know that various Linux distros are including Lua and some modules now, and more to come.</p> <p>There are also a couple of proposed module libraries under discussion in the mailing list, but the community hasn't yet settled on one as the "official" mechanism.</p> <p>I use Lua both as a scripting language and as the "main" loop of my typical application, supported by one or more DLLs containing code that was better implemented in C, or wrapping existing libraries or API functions that are needed by a particular project. Used with a GUI toolkit such as <a href="https://sourceforge.net/projects/iup/" rel="nofollow">IUP</a> or <a href="http://wxlua.sourceforge.net/" rel="nofollow">wxLua</a> (a Lua binding for wxWindows), Lua makes writing small to mid-sized GUI applications quite pleasant.</p>
4
2009-02-20T08:31:28Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
781,316
<p>In order for Lua to be easy to embed it has to have few dependencies and be small. That makes it poorly suited as a general purpose scripting language. Because using it as a general purpose script language would require a lot of standard libraries. But if Lua had a lot of standard libraries it would be harder to embed (due to dependencies and memory footprint.)</p>
3
2009-04-23T11:32:02Z
[ "python", "scripting", "lua" ]
Lua as a general-purpose scripting language?
250,151
<p>When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".</p> <p>Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?</p> <p>Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:</p> <ul> <li>Renaming a bunch of files</li> <li>Download some files from the web</li> <li>Webscraping</li> </ul> <p>Is it the lack of the standard library?</p>
33
2008-10-30T13:21:41Z
1,537,777
<p>Lua is used in <a href="http://www.luatex.org/" rel="nofollow">LuaTeX</a>, a TeX extension, as an embedded language, and has gained popularity rapidly among TeX developers because of that. It is used as a scripting language for some utilities in the TeX Live distribution, be it only because now there is a <code>luatex</code> binary, available on all platforms, that can also be used as a Lua interpreter (with some vital modules added – slnunicode, luafilesystem, etc.) That's very important for Windows installations, that relied on additional Unix scripting tools earlier (ActivePerl, etc.) The ConTeXt macro language uses Lua scripts extensively nowadays.</p> <p>That's admittedly a very special field :-) But completely unrelated to games!</p>
3
2009-10-08T13:24:02Z
[ "python", "scripting", "lua" ]
How can I optimize this Google App Engine code?
250,209
<p>I'm relatively new to the python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
5
2008-10-30T13:40:19Z
250,294
<p>Looks pretty tight to me.</p> <p>I see one thing that may make a small improvement. Your calling, "self.request.get('links')" twice.</p> <p>So adding:</p> <pre><code>unsplitlinks = self.request.get('links') </code></pre> <p>And referencing, "unsplitlinks" could help.</p> <p>Other than that the loop is the only area I see that would be a target for optimization. Is it possible to prep the data and then add it to the db at once, instead of doing a db add per link? (I assume the .put() command adds the link to the database)</p>
3
2008-10-30T14:13:15Z
[ "python", "google-app-engine", "optimization" ]
How can I optimize this Google App Engine code?
250,209
<p>I'm relatively new to the python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
5
2008-10-30T13:40:19Z
250,318
<p>How frequently is this getting called? This doesn't look that bad... especially after removing the duplicate request.</p>
0
2008-10-30T14:21:41Z
[ "python", "google-app-engine", "optimization" ]
How can I optimize this Google App Engine code?
250,209
<p>I'm relatively new to the python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
5
2008-10-30T13:40:19Z
250,322
<p>You can dramatically reduce the interaction between your app and the database by just storing the complete <code>self.request.get('links')</code> in a text field in the database.</p> <ul> <li>only one <code>put()</code> per <code>post(self)</code></li> <li>the hash isn't stored n-times (for every link, which makes no sense and is really a waste of space)</li> </ul> <p>And you save yourself the parsing of the textfield when someone actually calls the page....</p>
2
2008-10-30T14:22:26Z
[ "python", "google-app-engine", "optimization" ]
How can I optimize this Google App Engine code?
250,209
<p>I'm relatively new to the python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
5
2008-10-30T13:40:19Z
250,395
<p>The main overhead here is the multiple individual puts to the datastore. If you can, store the links as a single entity, as Andre suggests. You can always split the links into an array and store it in a ListProperty.</p> <p>If you do need an entity for each link, try this:</p> <pre><code># For each line in the input, add to the database groups = [] for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x groups.append(newGroup) db.put(groups) </code></pre> <p>It will reduce the datastore roundtrips to one, and it's the roundtrips that are really killing your high CPU cap.</p>
7
2008-10-30T14:41:19Z
[ "python", "google-app-engine", "optimization" ]
How can I optimize this Google App Engine code?
250,209
<p>I'm relatively new to the python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
5
2008-10-30T13:40:19Z
250,465
<p>Can I query against the ListProperty?</p> <p>Something like </p> <pre><code>SELECT * FROM LinkGrouping WHERE links.contains('http://www.google.com') </code></pre> <p>I have future plans where I would need that functionality.</p> <p>I'll definitely implement the single db.put() to reduce usage.</p>
0
2008-10-30T14:58:50Z
[ "python", "google-app-engine", "optimization" ]
How can I optimize this Google App Engine code?
250,209
<p>I'm relatively new to the python world, but this seems very straight forward.</p> <p>Google is yelling at me that this code needs to be optimized:</p> <pre><code>class AddLinks(webapp.RequestHandler): def post(self): # Hash the textarea input to generate pseudo-unique value hash = md5.new(self.request.get('links')).hexdigest() # Seperate the input by line allLinks = self.request.get('links').splitlines() # For each line in the input, add to the database for x in allLinks: newGroup = LinkGrouping() newGroup.reference = hash newGroup.link = x newGroup.put() # testing vs live #baseURL = 'http://localhost:8080' baseURL = 'http://linkabyss.appspot.com' # Build template parameters template_values = { 'all_links': allLinks, 'base_url': baseURL, 'reference': hash, } # Output the template path = os.path.join(os.path.dirname(__file__), 'addLinks.html') self.response.out.write(template.render(path, template_values)) </code></pre> <p>The dashboard is telling me that this is using a ton of CPU.</p> <p>Where should I look for improvements?</p>
5
2008-10-30T13:40:19Z
264,785
<p>no/ you can not use something like "links.contains('<a href="http://www.google.com" rel="nofollow">http://www.google.com</a>')" GQL not support this</p>
0
2008-11-05T10:25:38Z
[ "python", "google-app-engine", "optimization" ]
Python Regex - How to Get Positions of Matches
250,271
<p>How can I get the start and end positions of all matches using the <code>re</code> module? For example given the pattern <code>r'[a-z]'</code> and the string <code>'a1b2c3d4'</code> I'd want to get the positions where it finds each letter (ideally I'd like to get the text of the match back too).</p>
50
2008-10-30T14:04:33Z
250,303
<pre><code>import re p = re.compile("[a-z]") for m in p.finditer('a1b2c3d4'): print m.start(), m.group() </code></pre>
65
2008-10-30T14:15:39Z
[ "python", "regex" ]
Python Regex - How to Get Positions of Matches
250,271
<p>How can I get the start and end positions of all matches using the <code>re</code> module? For example given the pattern <code>r'[a-z]'</code> and the string <code>'a1b2c3d4'</code> I'd want to get the positions where it finds each letter (ideally I'd like to get the text of the match back too).</p>
50
2008-10-30T14:04:33Z
250,306
<p>Taken from </p> <p><a href="http://docs.python.org/3.3/howto/regex.html"><em>Regular Expression HOWTO</em></a></p> <blockquote> <p>span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.</p> </blockquote> <pre><code>&gt;&gt;&gt; p = re.compile('[a-z]+') &gt;&gt;&gt; print p.match('::: message') None &gt;&gt;&gt; m = p.search('::: message') ; print m &lt;re.MatchObject instance at 80c9650&gt; &gt;&gt;&gt; m.group() 'message' &gt;&gt;&gt; m.span() (4, 11) </code></pre> <p>Combine that with:</p> <p>In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.</p> <pre><code>&gt;&gt;&gt; p = re.compile( ... ) &gt;&gt;&gt; iterator = p.finditer('12 drummers drumming, 11 ... 10 ...') &gt;&gt;&gt; iterator &lt;callable-iterator object at 0x401833ac&gt; &gt;&gt;&gt; for match in iterator: ... print match.span() ... (0, 2) (22, 24) (29, 31) </code></pre> <p>you should be able to do something on the order of</p> <pre><code>for match in re.finditer(r'[a-z]', 'a1b2c3d4'): print match.span() </code></pre>
27
2008-10-30T14:16:02Z
[ "python", "regex" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
250,330
<p>I don't think there's any one module that you can easily download to implement scp, however you might find this helpful: <a href="http://www.ibm.com/developerworks/linux/library/l-twist4.html" rel="nofollow">http://www.ibm.com/developerworks/linux/library/l-twist4.html</a></p>
-2
2008-10-30T14:25:06Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
250,402
<p>if you install putty on win32 you get an pscp (putty scp).</p> <p>so you can use the os.system hack on win32 too.</p> <p>(and you can use the putty-agent for key-managment)</p> <p><hr /></p> <p>sorry it is only a hack (but you can wrap it in a python class)</p>
4
2008-10-30T14:42:42Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
250,786
<p>You might be interested in trying <a href="http://www.noah.org/wiki/Pexpect">Pexpect</a> (<a href="http://sourceforge.net/projects/pexpect/">SourceForge project</a>). This would allow you to deal with interactive prompts for your password.</p> <p>Here's a snip of example usage (for ftp) from the main website:</p> <pre> # This connects to the openbsd ftp site and # downloads the recursive directory listing. import pexpect child = pexpect.spawn ('ftp ftp.openbsd.org') child.expect ('Name .*: ') child.sendline ('anonymous') child.expect ('Password:') child.sendline ('[email protected]') child.expect ('ftp> ') child.sendline ('cd pub') child.expect('ftp> ') child.sendline ('get ls-lR.gz') child.expect('ftp> ') child.sendline ('bye') </pre>
11
2008-10-30T16:18:00Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
250,797
<p>Hmmm, perhaps another option would be to use something like <a href="http://fuse.sourceforge.net/sshfs.html" rel="nofollow">sshfs</a> (there an <a href="http://code.google.com/p/macfuse/wiki/MACFUSE_FS_SSHFS" rel="nofollow">sshfs</a> for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.</p>
1
2008-10-30T16:20:46Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
251,625
<p>You could also check out <a href="http://www.lag.net/paramiko/">paramiko</a>. There's no scp module (yet), but it fully supports sftp.</p> <p>[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don't want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.</p> <p><a href="https://github.com/jbardin/scp.py">scp.py for paramiko</a></p>
8
2008-10-30T20:22:43Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
4,282,261
<p>Try the module <a href="https://github.com/jbardin/scp.py">paramiko_scp</a>. It's very easy to use. See the following example:</p> <pre><code>def createSSHClient(server, port, user, password): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, port, user, password) return client ssh = createSSHClient(server, port, user, password) scp = SCPClient(ssh.get_transport()) </code></pre> <p>Then call scp.get() or scp.put() to do scp operations.</p> <p>(<a href="https://github.com/jbardin/scp.py/blob/master/scp.py">SCPClient code</a>)</p>
62
2010-11-26T03:03:37Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
8,247,987
<p>Have a look at <a href="http://www.fabfile.org/" rel="nofollow">fabric</a>. An example can be found <a href="http://stackoverflow.com/questions/5314711/how-do-i-copy-a-directory-to-a-remote-machine-using-fabric">here</a>.</p>
3
2011-11-23T19:30:26Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
10,685,789
<p>I while ago I put together a python SCP copy script that depends on paramiko. It includes code to handle connections with a private key or SSH key agent with a fallback to password authentication.</p> <p><a href="http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/" rel="nofollow">http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/</a></p>
1
2012-05-21T13:03:59Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
24,049,247
<p>If you are on *nix you can use <a href="http://sourceforge.net/projects/sshpass/" rel="nofollow">sshpass</a></p> <pre><code>sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path </code></pre>
0
2014-06-04T23:26:21Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
24,587,238
<p>It has been quite a while since this question was asked, and in the meantime, another library that can handle this has cropped up: You can use the <a href="http://plumbum.readthedocs.org/en/latest/api/path.html#plumbum.path.utils.copy" rel="nofollow">copy</a> function included in the <a href="http://plumbum.readthedocs.org/en/latest/index.html" rel="nofollow">Plumbum</a> library:</p> <pre><code>import plumbum r = plumbum.machines.RemoteMachine("example.net", user="username", keyfile=".ssh/some_key") fro = plumbum.local.path("some_file") to = r.path("/path/to/destination/") plumbum.path.utils.copy(fro, to) </code></pre>
3
2014-07-05T14:08:32Z
[ "python", "ssh", "scp" ]
How to scp in python?
250,283
<p>What's the most pythonic way to scp a file in Python? The only route I'm aware of is </p> <pre><code>os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) </code></pre> <p>which is a hack, and which doesn't work outside linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.</p> <p>I'm aware of Twisted's <code>conch</code>, but I'd prefer to avoid implementing scp myself via low-level ssh modules.</p> <p>I'm aware of <code>paramiko</code>, a Python module that supports ssh and sftp; but it doesn't support scp.</p> <p>Background: I'm connecting to a router which doesn't support sftp but does support ssh/scp, so sftp isn't an option.</p> <p><strong>EDIT</strong>: This is a duplicate of <a href="http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh">http://stackoverflow.com/questions/68335/how-do-i-copy-a-file-to-a-remote-server-in-python-using-scp-or-ssh</a>. <strong>However</strong>, that question doesn't give an scp-specific answer that deals with keys from within python. I'm hoping for a way to run code kind of like</p> <pre><code>import scp client = scp.Client(host=host, user=user, keyfile=keyfile) # or client = scp.Client(host=host, user=user) client.use_system_keys() # or client = scp.Client(host=host, user=user, password=password) # and then client.transfer('/etc/local/filename', '/etc/remote/filename') </code></pre>
97
2008-10-30T14:09:21Z
38,556,344
<p>Couldn't find a straight answer, and this "scp.Client" module doesn't exist. Instead, <a href="https://pypi.python.org/pypi/scp" rel="nofollow">this</a> suits me:</p> <pre><code>from paramiko import SSHClient from scp import SCPClient ssh = SSHClient() ssh.load_system_host_keys() ssh.connect('example.com') with SCPClient(ssh.get_transport()) as scp: scp.put('test.txt', 'test2.txt') scp.get('test2.txt') </code></pre>
1
2016-07-24T20:14:37Z
[ "python", "ssh", "scp" ]
Truncate a string without ending in the middle of a word
250,357
<p>I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.</p> <p>For example:</p> <pre> Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." </pre> <p>I'm looking for a way to accomplish the "smart" truncate from above.</p>
31
2008-10-30T14:32:20Z
250,373
<p>I actually wrote a solution for this on a recent project of mine. I've compressed the majority of it down to be a little smaller.</p> <pre><code>def smart_truncate(content, length=100, suffix='...'): if len(content) &lt;= length: return content else: return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix </code></pre> <p>What happens is the if-statement checks if your content is already less than the cutoff point. If it's not, it truncates to the desired length, splits on the space, removes the last element (so that you don't cut off a word), and then joins it back together (while tacking on the '...').</p>
49
2008-10-30T14:36:03Z
[ "python", "truncate" ]
Truncate a string without ending in the middle of a word
250,357
<p>I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.</p> <p>For example:</p> <pre> Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." </pre> <p>I'm looking for a way to accomplish the "smart" truncate from above.</p>
31
2008-10-30T14:32:20Z
250,406
<p>Here's a slightly better version of the last line in Adam's solution:</p> <pre><code>return content[:length].rsplit(' ', 1)[0]+suffix </code></pre> <p>(This is slightly more efficient, and returns a more sensible result in the case there are no spaces in the front of the string.)</p>
36
2008-10-30T14:43:16Z
[ "python", "truncate" ]
Truncate a string without ending in the middle of a word
250,357
<p>I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.</p> <p>For example:</p> <pre> Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." </pre> <p>I'm looking for a way to accomplish the "smart" truncate from above.</p>
31
2008-10-30T14:32:20Z
250,409
<pre><code>def smart_truncate(s, width): if s[width].isspace(): return s[0:width]; else: return s[0:width].rsplit(None, 1)[0] </code></pre> <p>Testing it:</p> <pre><code>&gt;&gt;&gt; smart_truncate('The quick brown fox jumped over the lazy dog.', 23) + "..." 'The quick brown fox...' </code></pre>
3
2008-10-30T14:44:05Z
[ "python", "truncate" ]
Truncate a string without ending in the middle of a word
250,357
<p>I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.</p> <p>For example:</p> <pre> Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." </pre> <p>I'm looking for a way to accomplish the "smart" truncate from above.</p>
31
2008-10-30T14:32:20Z
250,471
<pre><code>def smart_truncate1(text, max_length=100, suffix='...'): """Returns a string of at most `max_length` characters, cutting only at word-boundaries. If the string was truncated, `suffix` will be appended. """ if len(text) &gt; max_length: pattern = r'^(.{0,%d}\S)\s.*' % (max_length-len(suffix)-1) return re.sub(pattern, r'\1' + suffix, text) else: return text </code></pre> <p>OR</p> <pre><code>def smart_truncate2(text, min_length=100, suffix='...'): """If the `text` is more than `min_length` characters long, it will be cut at the next word-boundary and `suffix`will be appended. """ pattern = r'^(.{%d,}?\S)\s.*' % (min_length-1) return re.sub(pattern, r'\1' + suffix, text) </code></pre> <p>OR</p> <pre><code>def smart_truncate3(text, length=100, suffix='...'): """Truncates `text`, on a word boundary, as close to the target length it can come. """ slen = len(suffix) pattern = r'^(.{0,%d}\S)\s+\S+' % (length-slen-1) if len(text) &gt; length: match = re.match(pattern, text) if match: length0 = match.end(0) length1 = match.end(1) if abs(length0+slen-length) &lt; abs(length1+slen-length): return match.group(0) + suffix else: return match.group(1) + suffix return text </code></pre>
7
2008-10-30T14:59:41Z
[ "python", "truncate" ]
Truncate a string without ending in the middle of a word
250,357
<p>I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.</p> <p>For example:</p> <pre> Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." </pre> <p>I'm looking for a way to accomplish the "smart" truncate from above.</p>
31
2008-10-30T14:32:20Z
250,684
<p>There are a few subtleties that may or may not be issues for you, such as handling of tabs (Eg. if you're displaying them as 8 spaces, but treating them as 1 character internally), handling various flavours of breaking and non-breaking whitespace, or allowing breaking on hyphenation etc. If any of this is desirable, you may want to take a look at the textwrap module. eg:</p> <pre><code>def truncate(text, max_size): if len(text) &lt;= max_size: return text return textwrap.wrap(text, max_size-3)[0] + "..." </code></pre> <p>The default behaviour for words greater than max_size is to break them (making max_size a hard limit). You can change to the soft limit used by some of the other solutions here by passing break_long_words=False to wrap(), in which case it will return the whole word. If you want this behaviour change the last line to:</p> <pre><code> lines = textwrap.wrap(text, max_size-3, break_long_words=False) return lines[0] + ("..." if len(lines)&gt;1 else "") </code></pre> <p>There are a few other options like expand_tabs that may be of interest depending on the exact behaviour you want.</p>
11
2008-10-30T15:47:04Z
[ "python", "truncate" ]
Truncate a string without ending in the middle of a word
250,357
<p>I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.</p> <p>For example:</p> <pre> Original: "This is really awesome." "Dumb" truncate: "This is real..." "Smart" truncate: "This is really..." </pre> <p>I'm looking for a way to accomplish the "smart" truncate from above.</p>
31
2008-10-30T14:32:20Z
20,821,663
<pre><code>&gt;&gt;&gt; import textwrap &gt;&gt;&gt; textwrap.wrap('The quick brown fox jumps over the lazy dog', 12) ['The quick', 'brown fox', 'jumps over', 'the lazy dog'] </code></pre> <p>You just take the first element of that and you're done...</p>
4
2013-12-29T02:54:59Z
[ "python", "truncate" ]
What do you like about Django?
250,397
<p>I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.<br /> Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything.</p> <p>So i would like to know your opinion about Django. </p> <p>What do you like about it?<br /> What made you switch/use it?<br /> What features you would like it to have that aren't there?<br /> What would make you switch to it?<br /> How fast is it in production?<br /> How hard is it to master it? </p>
6
2008-10-30T14:41:38Z
250,459
<p><strong><em>What do I like about it :</em></strong></p> <ul> <li>Very simple ORM</li> <li>clear separation of template / controller</li> <li>django-admin</li> <li>pluggable apps : it seems to me that the Django community really nailed that one !</li> </ul> <p><strong><em>What made me switch :</em></strong></p> <ul> <li>mainly curiosity</li> <li>I heard a lot of good things about it from a colleague</li> <li>I wanted something more lightweight than the Java I do for a living</li> <li>I had a side project heavily data-driven for which the Django-Admin interface is very useful</li> </ul> <p><strong><em>What features I'd like :</em></strong></p> <ul> <li>better / simpler control of the transactions (configuring different types of transactions (read only / read write / some tweaking here and there) isnt as easy as i am used to. Having a session in view model, where the transaction is still open in the view doesnt make me all that comfortable, I would prefer if the transactions didnt leave a service layer. But again, there isnt really a service layer in the Django model.</li> <li>better model for business logic (maybe that's just me, but I miss the service oriented approach of enterprise java, I never know if I should put the business logic in the view, in the form or in the model. None of those solution make me feel warm and fuzzy ... at the same time, I dont have heavy business logic in the application I develop for the moment, and I would probably still use Java for those)</li> <li>stability (in the sense of not changing, not in the sense of not crashing). Again, coming from Java, where I'm still working on Java 1.4 for a lot of projects, having a project that just released 1.0 and all the refactoring that went with it is not very reassuring. It did take some work to follow trunk and using 0.96 was not particularly compelling. I dont think I would feel comfortable to use it on a mission critical enterprise project yet.</li> </ul> <p>I realize that there is quite a few improvements that I would like. Dont understand me wrong, I love Django and I will stick to it for a lot of projects. I jsut wont put it everywhere yet ...</p>
8
2008-10-30T14:57:22Z
[ "python", "django" ]
What do you like about Django?
250,397
<p>I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.<br /> Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything.</p> <p>So i would like to know your opinion about Django. </p> <p>What do you like about it?<br /> What made you switch/use it?<br /> What features you would like it to have that aren't there?<br /> What would make you switch to it?<br /> How fast is it in production?<br /> How hard is it to master it? </p>
6
2008-10-30T14:41:38Z
250,461
<h3>What do you like about it?</h3> <p>URL dispatching: I was never a big fan of "/foo.php" is the file "foo.php" on my server, and if I want nicer URLs I need to mess around with mod_rewrite and keep that in line with what my logic in foo expects.</p> <p>ORM: Because 90%+ of your queries, in my experience, do not need to be written by hand. Smart caching is much more important for performance, in general. You can <em>always</em> drop to raw SQL as needed.</p> <p>Middleware and Signals: Easy to extend most parts of the request / response / view / render cycle without touching Django code itself.</p> <h3>What made you switch/use it?</h3> <p>It came out when I was disappointed with the Python web framework offerings. An easy sell for me.</p> <h3>How fast is it in production?</h3> <p>Hmm, to be honest, I've never cared too much. The webserver part of your app is (in my opinion) always the easiest to scale. As long as you use 'best practices' and share nothing, all you need to do is add a software load balancer and you can add new webservers until the cows come home. The first bottleneck people generally hit is database load - but Django gives you great caching APIs that help you alleviate that.</p> <p>That said, I only skimmed this but it seems faster than Rails and the well known PHP frameworks: <a href="http://wiki.rubyonrails.org/rails/pages/Framework+Performance">http://wiki.rubyonrails.org/rails/pages/Framework+Performance</a></p> <h3>How hard is it to master it?</h3> <p>I guess it depends how you define 'master'. The documentation is great, over the course of a decent sized site/app I think you'll use a little bit of everything, which is a great start.</p>
8
2008-10-30T14:57:53Z
[ "python", "django" ]
What do you like about Django?
250,397
<p>I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.<br /> Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything.</p> <p>So i would like to know your opinion about Django. </p> <p>What do you like about it?<br /> What made you switch/use it?<br /> What features you would like it to have that aren't there?<br /> What would make you switch to it?<br /> How fast is it in production?<br /> How hard is it to master it? </p>
6
2008-10-30T14:41:38Z
250,487
<p>I haven't had had the opportunity to use it much. That said, my absolute favorite part of django is the built in administration console.</p>
3
2008-10-30T15:03:57Z
[ "python", "django" ]
What do you like about Django?
250,397
<p>I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.<br /> Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything.</p> <p>So i would like to know your opinion about Django. </p> <p>What do you like about it?<br /> What made you switch/use it?<br /> What features you would like it to have that aren't there?<br /> What would make you switch to it?<br /> How fast is it in production?<br /> How hard is it to master it? </p>
6
2008-10-30T14:41:38Z
251,984
<h2><strong>Likes</strong></h2> <p>The excellent Documentation. Together with help from stackoverflow I have learned a lot in only a few days. It writting in Python. It has the wonderful contrib.admin which is even modular and extensible to embed it into the web app proper.</p> <h2>Dislikes</h2> <p>None so far. I am still enchanted</p> <h2>Switch</h2> <p>Its my first web framework, so no switch. After using Python for some years Django seemed the natural selection to me, mainly for its clean design.</p>
4
2008-10-30T22:26:47Z
[ "python", "django" ]
What do you like about Django?
250,397
<p>I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.<br /> Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything.</p> <p>So i would like to know your opinion about Django. </p> <p>What do you like about it?<br /> What made you switch/use it?<br /> What features you would like it to have that aren't there?<br /> What would make you switch to it?<br /> How fast is it in production?<br /> How hard is it to master it? </p>
6
2008-10-30T14:41:38Z
263,440
<h2>What do you like about it?</h2> <ul> <li>the templates, specifically the inheritance feature, was amazing after dealing with jsps</li> <li>not having to write sql anymore</li> </ul> <h2>What made you switch/use it?</h2> <p>A friend had been following its progress before it was publicly released, and I've been using it for personal projects ever since.</p> <h2>What features you would like it to have that aren't there?</h2> <p>I realize this isn't a trivial problem, and I think Google summer of codes have been spent on this, but I would like to see better ways to evolve the db (which rails seems to do a pretty good job of).</p> <h2>What would make you switch to it?</h2> <p>I already use it at home, and I don't make those decisions at work.</p> <h2>How fast is it in production?</h2> <p>I've never run into issues, though for the most part django seems to stay out of the way, so performance seems based more on python or the db.</p> <h2>How hard is it to master it? </h2> <p>The documentation is pretty amazing, and enough people use it that answers are often available when that doesn't help. Additionally, when I've had to go into the source code, its been clean and documented as well, so I would say its easier to master than most frameworks, web based or otherwise.</p>
4
2008-11-04T21:03:33Z
[ "python", "django" ]
What do you like about Django?
250,397
<p>I started to learn Django a few days ago, and as i dive into it it seems that I'm starting to like it even more.<br /> Trying to migrate from other language. I won't say which one, as the purpose of this question is not to bash anything.</p> <p>So i would like to know your opinion about Django. </p> <p>What do you like about it?<br /> What made you switch/use it?<br /> What features you would like it to have that aren't there?<br /> What would make you switch to it?<br /> How fast is it in production?<br /> How hard is it to master it? </p>
6
2008-10-30T14:41:38Z
264,913
<p>Likes:</p> <ul> <li>Pythonic (I can easily grok the language) and thus extend any part easily</li> <li>Documentation,</li> <li>community (I belong to the french one and they're very nice)</li> <li>a full load of projects around it</li> <li>full-integrated test engine. You can almost test a whole application without firing a web browser, just by writing tests.</li> <li>the custom commands just rock. It allows you to perform custom tasks very easily, in a snap. I often use it to run batch tasks (cleanup a database, for example, or check for integrity on a production server - tests use their own database, not the actual data in your application).</li> </ul> <p>Why switch?</p> <ul> <li>got bored of PHP-from-scratch.</li> <li>had a RSI at the back of my hand, very painful. after switching to a semicolon-free language, it vanished (it's TRUE!)</li> <li>much more solid developpement (TDD), and faster (you can buid a CMS in minutes) - as many other web framework, though.</li> </ul> <p>Dislikes:</p> <ul> <li>no smooth data model migration. You often have to change your model because of an unexpected feature. That is painful, and you have to build it by hand, and it may be risky sometimes.</li> </ul> <p>How hard to master?</p> <ul> <li>If you already have Python skills, you can build up things in a few hours.</li> <li>If you don't, first dive into Python (heh) - that'd take a few days.</li> <li>"Mastering" it may take some time... And you often discover gems in Django documentation that will make you yell "I love Django!" (well, it works for me)</li> </ul>
3
2008-11-05T11:46:12Z
[ "python", "django" ]
How to specify relations using SQLAlchemy declarative syntax?
250,398
<p>I can't find any proper documentation on how to specify relations using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax?<br /> I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addresses = OneToMany(Address)" and let the framework handle the details.. I know that Elixir can do that, but I was wondering if "plain" SQLA could do it too.<br /> Thanks for your help!</p>
3
2008-10-30T14:41:50Z
251,077
<p>Assuming you are referring to <a href="http://www.sqlalchemy.org/docs/04/plugins.html#plugins_declarative" rel="nofollow">the declarative plugin</a>, where everything I am about to say is documented with examples:</p> <pre><code>class User(Base): __tablename__ = 'users' id = Column('id', Integer, primary_key=True) addresses = relation("Address", backref="user") class Address(Base): __tablename__ = 'addresses' id = Column('id', Integer, primary_key=True) user_id = Column('user_id', Integer, ForeignKey('users.id')) </code></pre>
3
2008-10-30T17:37:28Z
[ "python", "sqlalchemy" ]
How to specify relations using SQLAlchemy declarative syntax?
250,398
<p>I can't find any proper documentation on how to specify relations using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax?<br /> I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addresses = OneToMany(Address)" and let the framework handle the details.. I know that Elixir can do that, but I was wondering if "plain" SQLA could do it too.<br /> Thanks for your help!</p>
3
2008-10-30T14:41:50Z
1,094,626
<p>Look at the "Configuring Relations" section of the <a href="http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html" rel="nofollow">Declarative docs</a>. Not quite as high level as "OneToMany" but better than fully specifying the relation. </p> <pre><code>class Address(Base): __tablename__ = 'addresses' id = Column(Integer, primary_key=True) email = Column(String(50)) user_id = Column(Integer, ForeignKey('users.id')) </code></pre>
0
2009-07-07T20:19:52Z
[ "python", "sqlalchemy" ]
Is it possible to communicate with a sub subprocess with subprocess.Popen?
250,700
<p>I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:</p> <pre><code>sudo mod args </code></pre> <p>where mod is a perl script; so in python I would do </p> <pre><code>proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) </code></pre> <p>The problem is that this mod script needs a few questions answered. For this I thought that the traditional </p> <pre><code>(stdout, stderr) = proc.communicate(input='y') </code></pre> <p>would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?</p>
5
2008-10-30T15:50:51Z
250,804
<p>The simplest thing to do would be the run the controlling script (the Python script) via <code>sudo</code>. Are you able to do that, or is that not an option?</p>
1
2008-10-30T16:22:51Z
[ "python", "subprocess" ]
Is it possible to communicate with a sub subprocess with subprocess.Popen?
250,700
<p>I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:</p> <pre><code>sudo mod args </code></pre> <p>where mod is a perl script; so in python I would do </p> <pre><code>proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) </code></pre> <p>The problem is that this mod script needs a few questions answered. For this I thought that the traditional </p> <pre><code>(stdout, stderr) = proc.communicate(input='y') </code></pre> <p>would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?</p>
5
2008-10-30T15:50:51Z
250,819
<p>I think you should remove the <code>sudo</code> in your <code>Popen</code> call and require the user of <em>your</em> script to type <code>sudo</code>.</p> <p>This additionally makes more explicit the need for elevated privileges in your script, instead of hiding it inside <code>Popen</code>.</p>
3
2008-10-30T16:26:41Z
[ "python", "subprocess" ]
Is it possible to communicate with a sub subprocess with subprocess.Popen?
250,700
<p>I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:</p> <pre><code>sudo mod args </code></pre> <p>where mod is a perl script; so in python I would do </p> <pre><code>proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) </code></pre> <p>The problem is that this mod script needs a few questions answered. For this I thought that the traditional </p> <pre><code>(stdout, stderr) = proc.communicate(input='y') </code></pre> <p>would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?</p>
5
2008-10-30T15:50:51Z
251,052
<p>We need more information.</p> <ol> <li>Is sudo asking you for a password?</li> <li>What kind of interface does the mod script have for asking questions?</li> </ol> <p>Because these kind of things are not handled as normal over the pipe.</p> <p>A solution for both of these might be <a href="http://www.noah.org/wiki/Pexpect" rel="nofollow">Pexpect</a>, which is rather expert at handling funny scripts that ask for passwords, and various other input issues.</p>
0
2008-10-30T17:29:43Z
[ "python", "subprocess" ]
Is it possible to communicate with a sub subprocess with subprocess.Popen?
250,700
<p>I'm trying to write a python script that packages our software. This script needs to build our product, and package it. Currently we have other scripts that do each piece individually which include csh, and perl scripts. One such script is run like:</p> <pre><code>sudo mod args </code></pre> <p>where mod is a perl script; so in python I would do </p> <pre><code>proc = Popen(['sudo', 'mod', '-p', '-c', 'noresource', '-u', 'dtt', '-Q'], stderr=PIPE, stdout=PIPE, stdin=PIPE) </code></pre> <p>The problem is that this mod script needs a few questions answered. For this I thought that the traditional </p> <pre><code>(stdout, stderr) = proc.communicate(input='y') </code></pre> <p>would work. I don't think it's working because the process that Popen is controlling is sudo, not the mod script that is asking the question. Is there any way to communicate with the mod script and still run it through sudo?</p>
5
2008-10-30T15:50:51Z
252,100
<p>I would choose to go with Pexpect. </p> <pre><code>import pexpect child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q') child.expect ('First question:') child.sendline ('Y') child.expect ('Second question:') child.sendline ('Yup') </code></pre>
4
2008-10-30T23:10:26Z
[ "python", "subprocess" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
251,469
<pre><code>my_function.func_name </code></pre> <p>There are also other fun properties of functions. Type <code>dir(func_name)</code> to list them. <code>func_name.func_code.co_code</code> is the compiled function, stored as a string.</p> <pre><code>import dis dis.dis(my_function) </code></pre> <p>will display the code in <em>almost</em> human readable format. :)</p>
32
2008-10-30T19:39:19Z
[ "python", "string", "function" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
255,297
<pre><code>my_function.__name__ </code></pre> <p>Using <code>__name__</code> is the preferred method as it applies uniformly. Unlike <code>func_name</code>, it works on built-in functions as well:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.time.func_name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'func_name' &gt;&gt;&gt; time.time.__name__ 'time' </code></pre> <p>Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a <code>__name__</code> attribute too, so you only have remember one special name.</p>
357
2008-11-01T00:07:17Z
[ "python", "string", "function" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
13,514,318
<p>You could also use</p> <pre><code>import sys this_function_name = sys._getframe().f_code.co_name </code></pre>
116
2012-11-22T13:59:49Z
[ "python", "string", "function" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
18,543,271
<p>sys._getframe() is not guaranteed to be available in all implementations of Python (<a href="http://docs.python.org/2/library/sys.html">see ref</a>) ,you can use the traceback module to do the same thing, eg.</p> <pre><code>import traceback def who_am_i(): stack = traceback.extract_stack() filename, codeline, funcName, text = stack[-2] return funcName </code></pre> <p>A call to stack[-1] will return the current process details.</p>
6
2013-08-31T00:34:37Z
[ "python", "string", "function" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
20,714,270
<p>This function will return the caller's function name.</p> <pre><code>def func_name(): import traceback return traceback.extract_stack(None, 2)[0][2] </code></pre> <p>It is like Albert Vonpupp's answer with a friendly wrapper.</p>
21
2013-12-21T00:59:58Z
[ "python", "string", "function" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
25,130,006
<p>For readability, as string are highlighted by most editors, I would just create an object like this:</p> <pre><code>def my_function(): f_name = 'my_function' </code></pre> <p>Which is less code characters than the "correct" way to fetch:</p> <pre><code>def my_function(): f_name = my_function.__name__ </code></pre> <p>seems needless if you're going to have to type out the function name anyway to access its </p> <pre><code>.__name__ </code></pre> <p>you don't just put the thing in quotes and call it good.</p>
-6
2014-08-05T01:38:44Z
[ "python", "string", "function" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
36,228,241
<p>As an extension of <a href="http://stackoverflow.com/a/20714270/109941">@Demyn's answer</a>, I created some utility functions which print the current function's name and current function's arguments:</p> <pre><code>import inspect import logging import traceback def get_function_name(): return traceback.extract_stack(None, 2)[0][2] def get_function_parameters_and_values(): frame = inspect.currentframe().f_back args, _, _, values = inspect.getargvalues(frame) return ([(i, values[i]) for i in args]) def my_func(a, b, c=None): logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')') pass logger = logging.getLogger() handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s [%(levelname)s] -&gt; %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -&gt; Running my_func([('a', 1), ('b', 3), ('c', None)]) </code></pre>
1
2016-03-25T21:21:23Z
[ "python", "string", "function" ]
How to get a function name as a string in Python?
251,464
<p>In Python, how do I get a function name as a string without calling the function?</p> <pre><code>def my_function(): pass print get_function_name_as_string(my_function) # my_function is not in quotes </code></pre> <p>should output <code>"my_function"</code>.</p> <p>Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?</p>
306
2008-10-30T19:38:24Z
38,453,402
<p>I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:</p> <pre><code>class EnterExitLog(): def __init__(self, funcName): self.funcName = funcName def __enter__(self): gLog.debug('Started: %s' % self.funcName) self.init_time = datetime.datetime.now() return self def __exit__(self, type, value, tb): gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time)) def func_timer_decorator(func): def func_wrapper(*args, **kwargs): with EnterExitLog(func.__name__): return func(*args, **kwargs) return func_wrapper </code></pre> <p>so now all you have to do with your function is decorate it and voila</p> <pre><code>@func_timer_decorator def my_func(): </code></pre>
0
2016-07-19T08:37:30Z
[ "python", "string", "function" ]
script languages on windows mobile - something similar to python @ nokia s60
251,506
<p>I try to find something similar to nokia's <strong>python for windows mobile</strong> based devices - a script interpreter [in this case also able to create standalone apps] with easy access to all phone interfaces - ability to make a phone call, send SMS, make a photo, send a file over GPRS, etc...</p> <p>While there is 2.5 <strong>pythonce</strong> available for windows mobile it is pure python interpreter and what I look for are all those "libraries" that nokia's python has like "import camera", "import messaging", ability to control the phone programatically. Also the bluetooth console of nokia python is great.</p> <p>I do not want to use .NET CF as even there (AFAIK) to control camera you need to use some indirect methods (for example: <a href="http://blogs.msdn.com/marcpe/archive/2006/03/03/542941.aspx" rel="nofollow">http://blogs.msdn.com/marcpe/archive/2006/03/03/542941.aspx</a>). </p> <p>Appreciate any help you can provide, thanks in advance.</p> <p>I hope there is something I was unable to locate via google. </p>
3
2008-10-30T19:48:59Z
251,533
<p>Well there is <a href="http://www.sto-helit.de/index.php?module=download&amp;action=list&amp;category=18" rel="nofollow">Mortscript</a>. a widely used scripting for Windows Mobile. Not sure if it can access all the phones functions. I believe there is <a href="http://www.kocjan.org/tclmentor/1-tcl/17-tcl-on-windows-mobile-introduction.html" rel="nofollow">TCL</a> for Windows Mobile as well.</p>
0
2008-10-30T19:56:46Z
[ "python", "windows-mobile", "mobile" ]
script languages on windows mobile - something similar to python @ nokia s60
251,506
<p>I try to find something similar to nokia's <strong>python for windows mobile</strong> based devices - a script interpreter [in this case also able to create standalone apps] with easy access to all phone interfaces - ability to make a phone call, send SMS, make a photo, send a file over GPRS, etc...</p> <p>While there is 2.5 <strong>pythonce</strong> available for windows mobile it is pure python interpreter and what I look for are all those "libraries" that nokia's python has like "import camera", "import messaging", ability to control the phone programatically. Also the bluetooth console of nokia python is great.</p> <p>I do not want to use .NET CF as even there (AFAIK) to control camera you need to use some indirect methods (for example: <a href="http://blogs.msdn.com/marcpe/archive/2006/03/03/542941.aspx" rel="nofollow">http://blogs.msdn.com/marcpe/archive/2006/03/03/542941.aspx</a>). </p> <p>Appreciate any help you can provide, thanks in advance.</p> <p>I hope there is something I was unable to locate via google. </p>
3
2008-10-30T19:48:59Z
252,150
<p>It sounds as if this is an opportunity for you to develop some C extension modules for the PythonCE project.</p>
3
2008-10-30T23:36:00Z
[ "python", "windows-mobile", "mobile" ]
script languages on windows mobile - something similar to python @ nokia s60
251,506
<p>I try to find something similar to nokia's <strong>python for windows mobile</strong> based devices - a script interpreter [in this case also able to create standalone apps] with easy access to all phone interfaces - ability to make a phone call, send SMS, make a photo, send a file over GPRS, etc...</p> <p>While there is 2.5 <strong>pythonce</strong> available for windows mobile it is pure python interpreter and what I look for are all those "libraries" that nokia's python has like "import camera", "import messaging", ability to control the phone programatically. Also the bluetooth console of nokia python is great.</p> <p>I do not want to use .NET CF as even there (AFAIK) to control camera you need to use some indirect methods (for example: <a href="http://blogs.msdn.com/marcpe/archive/2006/03/03/542941.aspx" rel="nofollow">http://blogs.msdn.com/marcpe/archive/2006/03/03/542941.aspx</a>). </p> <p>Appreciate any help you can provide, thanks in advance.</p> <p>I hope there is something I was unable to locate via google. </p>
3
2008-10-30T19:48:59Z
252,399
<p>IronPython?</p>
0
2008-10-31T01:53:11Z
[ "python", "windows-mobile", "mobile" ]
What is the best way to serve static web pages from within a Django application?
252,035
<p>I am building a relatively simple <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> application and apart from the main page where most of the dynamic parts of the application are, there are a few pages that I will need that will not be dynamic at all (<em>About</em>, <em>FAQ</em>, etc.). What is the best way to integrate these into Django, idealing still using the Django template engine? Should I just create a template for each and then have a view that simply renders that template?</p>
3
2008-10-30T22:47:20Z
252,039
<p>Have you looked at <a href="http://docs.djangoproject.com/en/dev/ref/contrib/flatpages/#ref-contrib-flatpages" rel="nofollow">flat pages</a> in Django? It probably does everything you're looking for.</p>
6
2008-10-30T22:49:35Z
[ "python", "django", "static", "templates" ]
What is the best way to serve static web pages from within a Django application?
252,035
<p>I am building a relatively simple <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="nofollow">Django</a> application and apart from the main page where most of the dynamic parts of the application are, there are a few pages that I will need that will not be dynamic at all (<em>About</em>, <em>FAQ</em>, etc.). What is the best way to integrate these into Django, idealing still using the Django template engine? Should I just create a template for each and then have a view that simply renders that template?</p>
3
2008-10-30T22:47:20Z
252,057
<p>If you want to just create a template for each of them, you could use the <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template" rel="nofollow"><code>direct_to_template</code></a> generic view to serve it up.</p> <p>Another option would be the <a href="https://docs.djangoproject.com/en/1.4/ref/contrib/flatpages/" rel="nofollow"><code>django.contrib.flatpages</code></a> app, which would let you configure the static URLs and content via the database.</p>
6
2008-10-30T22:57:13Z
[ "python", "django", "static", "templates" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
252,296
<p>What if it doesn't mean anything, what if it is just a neat design they came up with?</p>
2
2008-10-31T00:58:21Z
[ "python" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
252,329
<p>I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best.</p> <p>Which block do you like best?</p>
5
2008-10-31T01:11:56Z
[ "python" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
252,344
<p>Well, I can't see an immediate pattern. But if you are testing IP, why not take two blocks of 4 as a single binary number.</p>
0
2008-10-31T01:18:59Z
[ "python" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
252,345
<p>I think it's <em>simply</em> a design, nothing secret, or mysterious.</p>
5
2008-10-31T01:20:12Z
[ "python" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
260,580
<p>I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"</p>
15
2008-11-04T01:46:39Z
[ "python" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
260,595
<p>It says: "You are getting closer".</p>
1
2008-11-04T02:05:50Z
[ "python" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
483,491
<p>Probably it's a base 4 notation?</p> <p>I would try that, but I don't have any approach to this.</p>
0
2009-01-27T14:02:38Z
[ "python" ]
Possible Google Riddle?
252,221
<p>My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.</p> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a></p> <p>So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.</p> <p>My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.</p> <p>Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.</p> <p>I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.</p> <p>I hope someone knows better.</p> <pre><code>#This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print </code></pre> <p><a href="http://2.bp.blogspot.com/_iQVgmEEAit4/SPkKHA3e8fI/AAAAAAAAAB8/ugUerJjuBw8/s1600-h/GWO-tshirt.jpg" rel="nofollow">t-shirt</a>.</p>
11
2008-10-31T00:14:12Z
3,260,996
<p>It reminded me of cellular automata:</p> <p><a href="http://www.wolframalpha.com/input/?i=rule+110" rel="nofollow">http://www.wolframalpha.com/input/?i=rule+110</a></p> <p>Anyone going that direction?</p>
0
2010-07-16T00:01:32Z
[ "python" ]
Bizarre python ImportError
252,287
<p>Here's my setup: a Mac, running OS X Tiger. Windows XP running in a virtual machine (Parallels). Windows XP has my Mac home directory mapped as a network drive.</p> <p>I have two files in a directory of my Mac home directory:</p> <h3>foo.py</h3> <pre><code>pass </code></pre> <h3>test.py</h3> <pre><code>import foo </code></pre> <p>If I run test.py from within my virtual machine by typing 'python test.py', I get this:</p> <pre><code>Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; import foo ImportError: No module named foo </code></pre> <p>If I try to import foo from the console (running python under Windows from the same directory), all is well:</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. &gt;&gt;&gt; import foo &gt;&gt;&gt; </code></pre> <p>If I run test.py with Mac python, all is well.</p> <p>If I copy test.py and foo.py to a different directory, I can run test.py under Windows without problems.</p> <p>There is an <strong>init</strong>.py in the original directory, but it is empty. Furthermore, copying it with the other files doesn't break anything in the previous paragraph.</p> <p>There are no python-related environment variables set.</p> <p>Any ideas?</p>
3
2008-10-31T00:54:55Z
252,299
<p>Add import sys; print sys.path to the start of test.py. See what it prints out in the failing case. If "." isn't on the list, that may be your problem.</p>
2
2008-10-31T00:58:31Z
[ "python", "import", "windows-xp" ]
Bizarre python ImportError
252,287
<p>Here's my setup: a Mac, running OS X Tiger. Windows XP running in a virtual machine (Parallels). Windows XP has my Mac home directory mapped as a network drive.</p> <p>I have two files in a directory of my Mac home directory:</p> <h3>foo.py</h3> <pre><code>pass </code></pre> <h3>test.py</h3> <pre><code>import foo </code></pre> <p>If I run test.py from within my virtual machine by typing 'python test.py', I get this:</p> <pre><code>Traceback (most recent call last): File "test.py", line 1, in &lt;module&gt; import foo ImportError: No module named foo </code></pre> <p>If I try to import foo from the console (running python under Windows from the same directory), all is well:</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. &gt;&gt;&gt; import foo &gt;&gt;&gt; </code></pre> <p>If I run test.py with Mac python, all is well.</p> <p>If I copy test.py and foo.py to a different directory, I can run test.py under Windows without problems.</p> <p>There is an <strong>init</strong>.py in the original directory, but it is empty. Furthermore, copying it with the other files doesn't break anything in the previous paragraph.</p> <p>There are no python-related environment variables set.</p> <p>Any ideas?</p>
3
2008-10-31T00:54:55Z
254,355
<p>As a random guess: are the permissions on foo.py accessable from the windows client? (eg try opening with notepad from the virtual machine).</p> <p>If that's OK, try running:</p> <pre><code>python -v -v test.py </code></pre> <p>and looking at the output (alternatively, set PYTHONVERBOSE=2). This should list all the places it tries to import foo from. Comparing it with a similar trace on the working machine may give some further clues.</p>
1
2008-10-31T17:49:25Z
[ "python", "import", "windows-xp" ]