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
list
Running Java, Python, Ruby and Perl programs in .NET
2,593,519
<p>I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console? </p> <p>Do I need to install something else also, for running these language files?</p> <p>In case there is a need for something extra to be installed and after i ...
0
2010-04-07T15:02:08Z
2,593,537
<p>Do you want to run programs in these languages inside the .NET platform? You'd need IronPython or IronRuby (I don't think anything like IronPerl exists).</p> <p>If you want to run "normal" Python/Ruby/Perl/Java programs, then yes, you'll need to install a Python interpreter, a Ruby interpreter, a Perl interpreter a...
8
2010-04-07T15:05:03Z
[ "java", ".net", "python", "ruby", "perl" ]
Running Java, Python, Ruby and Perl programs in .NET
2,593,519
<p>I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console? </p> <p>Do I need to install something else also, for running these language files?</p> <p>In case there is a need for something extra to be installed and after i ...
0
2010-04-07T15:02:08Z
2,593,544
<p>Perl is a bit of a problem, see <a href="http://stackoverflow.com/questions/370078/why-is-there-no-ironperl-perl-for-net">this SO question</a>. <a href="http://ironruby.net/" rel="nofollow">IronRuby</a> and <a href="http://ironpython.net/" rel="nofollow">IronPython</a> cover those two languages. For Java, I think ...
3
2010-04-07T15:05:57Z
[ "java", ".net", "python", "ruby", "perl" ]
Running Java, Python, Ruby and Perl programs in .NET
2,593,519
<p>I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console? </p> <p>Do I need to install something else also, for running these language files?</p> <p>In case there is a need for something extra to be installed and after i ...
0
2010-04-07T15:02:08Z
2,593,551
<p>None of those languages are supported natively with .NET. You can try IronPython or IronRuby for those languages, but to run Java or Perl I think you'll actually need to download and install a Java VM and a perl interpreter.</p>
3
2010-04-07T15:06:33Z
[ "java", ".net", "python", "ruby", "perl" ]
Running Java, Python, Ruby and Perl programs in .NET
2,593,519
<p>I've .NET framework 3.5 installed in my laptop. Just .NET alone, no Visual Studio. How can I run Java, Python, Ruby and Perl programs from the console? </p> <p>Do I need to install something else also, for running these language files?</p> <p>In case there is a need for something extra to be installed and after i ...
0
2010-04-07T15:02:08Z
2,593,556
<p>There's no practical common virtual machine or binary for the options you list. You will require a separate install for each of these (note that all are unrelated to .NET)</p>
1
2010-04-07T15:07:11Z
[ "java", ".net", "python", "ruby", "perl" ]
Is there a way to backup everything in an app-engine blobstore?
2,593,756
<p>bulkloader.py is very handy. </p> <p>But as far as I can tell it doesn't appear to fetch items from the blobstore, so you can be left with broken entity relationships if you needed to dump/restore your application.</p> <p>Does anyone know a method for completely backing up their data from app-engine including blob...
3
2010-04-07T15:31:40Z
2,594,009
<p>In Java, you would instantiate a BlobInfoFactory and use BlobInfoFactory.queryBlobInfos. </p> <p>Then for each blob, you would run BlobstoreService.serve(...) with the BlobKeys returned from the BlobInfos. You still might end up with broken entity relationships - there's no way to guarantee each blob will end up w...
2
2010-04-07T16:08:52Z
[ "python", "google-app-engine", "blobstore" ]
Running python batch file that has a path with SPACE character
2,594,190
<p>The batch file is something like this, I put the python in some directory that has SPACE character in its path. </p> <pre> C:\"Documents and Settings"\Administrator\Desktop\bracket\python\python C:\\"Documents and Settings"\\Administrator\\Desktop\\bracket\\[10,20]\\brackettest.py </pre> <p>When I run this one, I...
0
2010-04-07T16:33:03Z
2,594,224
<p>There's no backslash escaping in the Windows console, it should read</p> <pre><code>"C:\Documents and Settings\Administrator\Desktop\bracket\python\python" "C:\Documents and Settings\Administrator\Desktop\bracket\[10,20]\brackettest.py" </code></pre>
4
2010-04-07T16:38:08Z
[ "python", "windows", "path", "batch-file" ]
Running python batch file that has a path with SPACE character
2,594,190
<p>The batch file is something like this, I put the python in some directory that has SPACE character in its path. </p> <pre> C:\"Documents and Settings"\Administrator\Desktop\bracket\python\python C:\\"Documents and Settings"\\Administrator\\Desktop\\bracket\\[10,20]\\brackettest.py </pre> <p>When I run this one, I...
0
2010-04-07T16:33:03Z
2,594,277
<p>Looks like you almost had it; just replace the double-slashes with single slashes.<br> If you're ever unsure and need a reminder of the right format. Try using the tab key to automatically complete your folder or filename. For example, at your command prompt just type:<br> C:\docu<br> then hit the tab key and it w...
2
2010-04-07T16:44:31Z
[ "python", "windows", "path", "batch-file" ]
Running python batch file that has a path with SPACE character
2,594,190
<p>The batch file is something like this, I put the python in some directory that has SPACE character in its path. </p> <pre> C:\"Documents and Settings"\Administrator\Desktop\bracket\python\python C:\\"Documents and Settings"\\Administrator\\Desktop\\bracket\\[10,20]\\brackettest.py </pre> <p>When I run this one, I...
0
2010-04-07T16:33:03Z
2,594,319
<p>Can you</p> <pre><code>cd "\Documents and Settings" cd "\Documents and Settings\Administrator\Desktop\bracket\python\python" cd "\Documents and Settings\Administrator\Desktop\bracket\" cd "\Documents and Settings\Administrator\Desktop\bracket\[10,20]\" </code></pre> <p>If all that works, do</p> <pre><code>cd "\Do...
0
2010-04-07T16:49:36Z
[ "python", "windows", "path", "batch-file" ]
Running python batch file that has a path with SPACE character
2,594,190
<p>The batch file is something like this, I put the python in some directory that has SPACE character in its path. </p> <pre> C:\"Documents and Settings"\Administrator\Desktop\bracket\python\python C:\\"Documents and Settings"\\Administrator\\Desktop\\bracket\\[10,20]\\brackettest.py </pre> <p>When I run this one, I...
0
2010-04-07T16:33:03Z
25,650,129
<pre><code>path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv" </code></pre> <p>Closing the path in <em>r"string"</em> also solved this problem very well. This tells python that it is <em>exactly</em> that string and avoids backslash and space errors. I use it for my files because it allows me to copy and ...
1
2014-09-03T17:15:54Z
[ "python", "windows", "path", "batch-file" ]
How to write a shell in Python
2,594,560
<p>I've written a small console application that can perform certain tasks. The user interface is similar to things like version control systems or yum etc. So basically you can think of it as a domain specific language. Now I'd like to write a (bash like) shell that can execute and auto-complete this language and has ...
19
2010-04-07T17:31:13Z
2,594,589
<p>You should check out the <a href="http://docs.python.org/library/cmd.html" rel="nofollow">cmd</a> and <a href="https://bitbucket.org/catherinedevlin/cmd2" rel="nofollow">cmd2</a> modules. I think they will do what you want. There was a PyCon <a href="http://pyvideo.org/video/306/pycon-2010--easy-command-line-applica...
18
2010-04-07T17:35:47Z
[ "python", "shell" ]
How to write a shell in Python
2,594,560
<p>I've written a small console application that can perform certain tasks. The user interface is similar to things like version control systems or yum etc. So basically you can think of it as a domain specific language. Now I'd like to write a (bash like) shell that can execute and auto-complete this language and has ...
19
2010-04-07T17:31:13Z
2,594,666
<p>If you need an administrative shell to be accessed via network <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a> python framework's manhole is a good solution. Example:</p> <p><a href="http://www.devshed.com/c/a/Python/SSH-with-Twisted/3/" rel="nofollow">http://www.devshed.com/c/a/Python/SSH-with-Twiste...
1
2010-04-07T17:49:02Z
[ "python", "shell" ]
Pylons paginator question
2,594,604
<blockquote> <p>Only comments associated with the current page should be listed, so once again the query is modified to include the page ID. In this case, though, we also have to pass the pageid argument, which will in turn get passed to any h.url_for() calls in the paginator.</p> </blockquote> <p>from <a href="http...
2
2010-04-07T17:38:24Z
2,597,459
<p>You need to pass the pageid to the method url_for because the pageid is required by the route.</p> <pre><code>map.connect('/page/{pageid}/{controller}/{action}', requirements={'pageid':'\d+'}) map.connect('/page/{pageid}/{controller}/{action}/{id}', requirements={'pageid':'\d+', 'id':'\d+'}) </code></pre> <p>The p...
1
2010-04-08T03:48:07Z
[ "python", "pylons" ]
Trying to set up nested while loops using a boolean switch
2,594,735
<p>I'm trying to set up a <code>while</code> loop that will ask the user for the employee name, hours worked and hourly wage until the user enters 'DONE'. Eventually I'll modify the code to calculate the weekly pay and write it to a list, but one thing at a time. The problem is once the main <code>while</code> loop exe...
1
2010-04-07T18:00:57Z
2,594,779
<p>The problem is that after the first loop, <code>employeeName</code> and the other variables will already have values, so your inner while loops will be skipped. This leads to the outer loop repeating infinitely without doing anything.</p> <p>I would just remove the inner while loops: you don't really need them, bec...
3
2010-04-07T18:07:37Z
[ "python", "while-loop", "nested-loops" ]
Trying to set up nested while loops using a boolean switch
2,594,735
<p>I'm trying to set up a <code>while</code> loop that will ask the user for the employee name, hours worked and hourly wage until the user enters 'DONE'. Eventually I'll modify the code to calculate the weekly pay and write it to a list, but one thing at a time. The problem is once the main <code>while</code> loop exe...
1
2010-04-07T18:00:57Z
2,594,812
<p><code>getHours</code> and <code>getWage</code> assume the input is respectively in <code>int</code> and <code>float</code> format. So the checks for <code>...lower()=="done"</code> can never possibly be satisfied: if the user had entered <code>done</code> at the prompt in either of these functions, the program woul...
1
2010-04-07T18:14:02Z
[ "python", "while-loop", "nested-loops" ]
Removing non-breaking spaces from strings using Python
2,594,810
<p>I am having some trouble with a very basic string issue in Python (that I can't figure out). Basically, I am trying to do the following:</p> <pre><code>'# read file into a string myString = file.read() '# Attempt to remove non breaking spaces myString = myString.replace("\u00A0"," ") '# however, when I print ...
18
2010-04-07T18:13:25Z
2,594,837
<p>There is no indication in what you write that you're necessarily doing anything wrong: if the original string had a non-breaking space between 'Foo' and 'Bar', you now have a normal space there instead. This assumes that at some point you've decoded your input string (which I imagine is a bytestring, unless you're ...
0
2010-04-07T18:18:26Z
[ "python", "string", "unicode", "text" ]
Removing non-breaking spaces from strings using Python
2,594,810
<p>I am having some trouble with a very basic string issue in Python (that I can't figure out). Basically, I am trying to do the following:</p> <pre><code>'# read file into a string myString = file.read() '# Attempt to remove non breaking spaces myString = myString.replace("\u00A0"," ") '# however, when I print ...
18
2010-04-07T18:13:25Z
2,594,932
<p>No, <code>u"\u00A0"</code> is the escape code for non-breaking spaces. <code>"\u00A0"</code> is 6 characters that are not any sort of escape code. <a href="http://farmdev.com/talks/unicode/" rel="nofollow">Read this</a>.</p>
4
2010-04-07T18:29:52Z
[ "python", "string", "unicode", "text" ]
Removing non-breaking spaces from strings using Python
2,594,810
<p>I am having some trouble with a very basic string issue in Python (that I can't figure out). Basically, I am trying to do the following:</p> <pre><code>'# read file into a string myString = file.read() '# Attempt to remove non breaking spaces myString = myString.replace("\u00A0"," ") '# however, when I print ...
18
2010-04-07T18:13:25Z
2,594,942
<p>You don't have a unicode string, but a UTF-8 list of bytes (which are what strings are in Python 2.x).</p> <p>Try</p> <pre><code>myString = myString.replace("\xc2\xa0", " ") </code></pre> <p>Better would be two switch to unicode -- see <a href="http://boodebr.org/main/python/all-about-python-and-unicode#UNITEXT_I...
25
2010-04-07T18:32:48Z
[ "python", "string", "unicode", "text" ]
Behavior of object in set operations
2,594,920
<p>I'm trying to create a custom object that behaves properly in set operations.</p> <p>I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods....
8
2010-04-07T18:28:15Z
2,595,090
<p>Nope, it's not deterministic. The problem is that you've broken equals' and hash's invariant, that two objects are equivalent when they are equal. Fix your object, don't try to be clever and abuse how set's implementation works. If the meta value is part of MyObject's identity, it should be included in eq and hash.<...
4
2010-04-07T18:56:02Z
[ "python", "object", "set" ]
Behavior of object in set operations
2,594,920
<p>I'm trying to create a custom object that behaves properly in set operations.</p> <p>I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods....
8
2010-04-07T18:28:15Z
2,595,161
<p>Order doesn't appear to matter:</p> <pre><code>&gt;&gt;&gt; [ (u.value, u.meta) for u in set([b,d]).intersection(set([a,c,e])) ] [('1', 'right'), ('2', 'right')] &gt;&gt;&gt; [ (u.value, u.meta) for u in set([a,c,e]).intersection(set([b,d])) ] [('1', 'right'), ('2', 'right')] </code></pre> <p>However, if you do t...
1
2010-04-07T19:08:01Z
[ "python", "object", "set" ]
Behavior of object in set operations
2,594,920
<p>I'm trying to create a custom object that behaves properly in set operations.</p> <p>I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods....
8
2010-04-07T18:28:15Z
2,596,787
<p>Let's say your objects have two different types of attributes: <em>key</em> attributes and <em>data</em> attributes. In your example, <code>MyObject.value</code> is a <em>key</em> attribute. </p> <p>Store all your objects as values in a dictionary, keyed by the <em>key</em> attributes, making sure that only your pr...
0
2010-04-08T00:24:03Z
[ "python", "object", "set" ]
How to display specific cookie?
2,594,947
<p>I'm using ActivePython 2.5.1 and the cookielib package to retrieve web pages.</p> <p>I'd like to display a given cookie from the cookiejar instead of the whole thing:</p> <pre><code>#OK to display all the cookies for index, cookie in enumerate(cj): print index, ' : ', cookie #How to display just PHP...
2
2010-04-07T18:33:55Z
2,595,463
<p>The cookiejar does not have a dict-like interface, only iteration is supported. So you have to implement a lookup method yourself.</p> <p>I am not sure what cookie attribute you want do do the lookup on. Example, using name:</p> <pre><code>def get_cookie_by_name(cj, name): return [cookie for cookie in cj if co...
4
2010-04-07T19:55:37Z
[ "python", "cookielib" ]
Google App Engine: Difficulty with Users API (or maybe just a Python syntax problem)
2,595,073
<p>I have a simple GAE app that includes a login/logout link. This app is running on the dev server at the moment.</p> <p>The base page handler gets the current user, and creates a login/logout url appropriately. It then puts this information into a <code>_template_data</code> dictionary, for convenience of subclasses...
1
2010-04-07T18:53:02Z
2,595,112
<p>I believe the problem is the <code>_user</code> attribute.</p> <p>Currently, the <code>_user</code> attribute is bound when the module containing the class is imported (probably when the application starts). You need to get the current user for each request.</p> <p>I would rewrite into something like:</p> <pre><c...
2
2010-04-07T18:58:44Z
[ "python", "google-app-engine", "syntax" ]
Python glob and bracket characters ('[]')
2,595,119
<p>/Users/smcho/Desktop/bracket/[10,20] directory has "abc.txt", but when I run this Python code</p> <pre><code>import glob import os.path path1 = "/Users/smcho/Desktop/bracket/\[10,20\]" pathName = os.path.join(path1, "*.txt") print glob.glob(pathName) </code></pre> <p>It returns an empty list. </p> <ul> <li>Can't...
8
2010-04-07T19:00:10Z
2,595,162
<p>The brackets in <code>glob</code> are used for character classes (e.g. <code>[a-z]</code> will match lowercase letters). You can put each bracket in a character class to force them being matched:</p> <pre><code>path1 = "/Users/smcho/Desktop/bracket/[[]10,20[]]" </code></pre> <p><code>[[]</code> is a character clas...
10
2010-04-07T19:08:06Z
[ "python", "glob" ]
Python glob and bracket characters ('[]')
2,595,119
<p>/Users/smcho/Desktop/bracket/[10,20] directory has "abc.txt", but when I run this Python code</p> <pre><code>import glob import os.path path1 = "/Users/smcho/Desktop/bracket/\[10,20\]" pathName = os.path.join(path1, "*.txt") print glob.glob(pathName) </code></pre> <p>It returns an empty list. </p> <ul> <li>Can't...
8
2010-04-07T19:00:10Z
2,595,211
<p><code>glob</code> uses <code>fnmatch</code> under the hood. You could use it directly:</p> <pre><code>import fnmatch, os names = os.listdir("/Users/smcho/Desktop/bracket/[10,20]") print fnmatch.filter(names, '*.txt') </code></pre> <p>Or using (non-public) <code>glob.glob1()</code> (it is present at least in Pytho...
4
2010-04-07T19:15:25Z
[ "python", "glob" ]
Python glob and bracket characters ('[]')
2,595,119
<p>/Users/smcho/Desktop/bracket/[10,20] directory has "abc.txt", but when I run this Python code</p> <pre><code>import glob import os.path path1 = "/Users/smcho/Desktop/bracket/\[10,20\]" pathName = os.path.join(path1, "*.txt") print glob.glob(pathName) </code></pre> <p>It returns an empty list. </p> <ul> <li>Can't...
8
2010-04-07T19:00:10Z
11,988,233
<p>You could use <code>path.replace('[', '[[]')</code> to have arbitrary input paths handled by <code>glob</code> correctly.</p>
2
2012-08-16T13:28:31Z
[ "python", "glob" ]
Python glob and bracket characters ('[]')
2,595,119
<p>/Users/smcho/Desktop/bracket/[10,20] directory has "abc.txt", but when I run this Python code</p> <pre><code>import glob import os.path path1 = "/Users/smcho/Desktop/bracket/\[10,20\]" pathName = os.path.join(path1, "*.txt") print glob.glob(pathName) </code></pre> <p>It returns an empty list. </p> <ul> <li>Can't...
8
2010-04-07T19:00:10Z
23,979,183
<p>In Python 3.4 you can use <a href="https://docs.python.org/3.4/library/glob.html#glob.escape" rel="nofollow"><code>glob.escape</code></a>.</p>
2
2014-06-01T11:04:01Z
[ "python", "glob" ]
Iterating over a database column in Django
2,595,296
<p>I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column:</p> <pre><code>import MySQLdb import sys try: co...
0
2010-04-07T19:30:17Z
2,595,404
<pre><code>from django.db.models.loading import get_model app_name = 'your_app_name' for model_name in ['foo','bar']: model = get_model(app_name, model_name) model_values = model.objects.values('foorbar1','foobar2') # this is a ValuesQuerySet. # you...
1
2010-04-07T19:46:05Z
[ "python", "mysql", "database", "django" ]
Iterating over a database column in Django
2,595,296
<p>I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column:</p> <pre><code>import MySQLdb import sys try: co...
0
2010-04-07T19:30:17Z
2,595,428
<p>Database microoptimalisation is not a strong part of Django ORM. However, when speed is so important, I wonder if the exec is the right way to do it.</p> <p>Anyways, You write "iterate through the values of a column", this means you have multiple values in single column separated by a separator (not seen in your co...
1
2010-04-07T19:49:18Z
[ "python", "mysql", "database", "django" ]
Iterating over a database column in Django
2,595,296
<p>I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column:</p> <pre><code>import MySQLdb import sys try: co...
0
2010-04-07T19:30:17Z
2,595,622
<p>Look into Django docs for only() and iterator():</p> <p><a href="http://docs.djangoproject.com/en/1.1/ref/models/querysets/#only-fields" rel="nofollow">http://docs.djangoproject.com/en/1.1/ref/models/querysets/#only-fields</a></p> <p><a href="http://docs.djangoproject.com/en/1.1/ref/models/querysets/#iterator" rel...
1
2010-04-07T20:17:37Z
[ "python", "mysql", "database", "django" ]
Django extending user model and displaying form
2,595,362
<p>I am writing website and i`d like to implement profile managment. Basic thing would be to edit some of user details by themself, like first and last name etc. Now, i had to extend User model to add my own stuff, and email address. </p> <p>I am having troubles with displaying form. Example will describe better wha...
1
2010-04-07T19:39:45Z
2,595,548
<p>You should create another form, that excludes the fields you don't want (or simply don't specify them in the fields list). Then pass the 2 different forms to the registration and edit-profile views.</p>
0
2010-04-07T20:08:22Z
[ "python", "django-models", "django-forms" ]
Django extending user model and displaying form
2,595,362
<p>I am writing website and i`d like to implement profile managment. Basic thing would be to edit some of user details by themself, like first and last name etc. Now, i had to extend User model to add my own stuff, and email address. </p> <p>I am having troubles with displaying form. Example will describe better wha...
1
2010-04-07T19:39:45Z
2,595,586
<p>Try removing 'username' and 'email' from fields in <code>Meta</code>:</p> <pre><code>class Meta: model = User fields = ('first_name', 'last_name') </code></pre>
0
2010-04-07T20:12:44Z
[ "python", "django-models", "django-forms" ]
Django extending user model and displaying form
2,595,362
<p>I am writing website and i`d like to implement profile managment. Basic thing would be to edit some of user details by themself, like first and last name etc. Now, i had to extend User model to add my own stuff, and email address. </p> <p>I am having troubles with displaying form. Example will describe better wha...
1
2010-04-07T19:39:45Z
2,663,174
<p>What i did is i created new form and used it and it worked. It allows to edit fields from User model not only UserExtended. Thanks for help.</p> <p>class UserProfileForm(forms.ModelForm):</p> <pre><code>def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) try: ...
0
2010-04-18T17:28:04Z
[ "python", "django-models", "django-forms" ]
Python's Popen cleanup
2,595,602
<p>I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |").</p> <p>I go to the subprocess module and try this:</p> <pre><code>p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE) </code></pre> <p>This w...
7
2010-04-07T20:14:59Z
2,595,659
<p>How did you executed this process?</p> <p>Proper way is to use</p> <pre><code>p.communicate() </code></pre> <p>See docs for more details. </p>
0
2010-04-07T20:25:02Z
[ "python", "popen", "resource-cleanup" ]
Python's Popen cleanup
2,595,602
<p>I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |").</p> <p>I go to the subprocess module and try this:</p> <pre><code>p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE) </code></pre> <p>This w...
7
2010-04-07T20:14:59Z
2,596,719
<p>After you open the pipe, you can work with the command output: <code>p.stdout</code>:</p> <pre><code>for line in p.stdout: # do stuff p.stdout.close() </code></pre>
2
2010-04-08T00:05:41Z
[ "python", "popen", "resource-cleanup" ]
Python's Popen cleanup
2,595,602
<p>I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |").</p> <p>I go to the subprocess module and try this:</p> <pre><code>p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE) </code></pre> <p>This w...
7
2010-04-07T20:14:59Z
2,603,164
<p>You need to <code>wait</code> for the process to finish:</p> <pre><code>import subprocess p = subprocess.Popen("cat /mach_kernel", shell=True) p.wait() </code></pre> <p>Alternatively, you can capture the program's standard output (as you have), and perhaps its standard error, and then call <code>communicate</code>...
0
2010-04-08T20:21:31Z
[ "python", "popen", "resource-cleanup" ]
Python's Popen cleanup
2,595,602
<p>I wanted to use a python equivalent to piping some shell commands in perl. Something like the python version of open(PIPE, "command |").</p> <p>I go to the subprocess module and try this:</p> <pre><code>p = subprocess.Popen("zgrep thingiwant largefile", shell=True, stdout=subprocess.PIPE) </code></pre> <p>This w...
7
2010-04-07T20:14:59Z
2,603,306
<p>The issue is that the <code>pipe</code> is full. The subprocess stops, waiting for the pipe to empty out, but then your process (the Python interpreter) quits, breaking its end of the pipe (hence the error message).</p> <p><code>p.wait()</code> will not help you:</p> <blockquote> <p><strong>Warning</strong> This...
8
2010-04-08T20:41:33Z
[ "python", "popen", "resource-cleanup" ]
Error when following along with the tutorial on the Django website
2,595,618
<p>I am following the django tutorial <a href="http://docs.djangoproject.com/en/1.1/intro/tutorial01/" rel="nofollow">here</a>. I have copied everything exactly. After the part where you enter the python manage.py sql polls command, it returns:</p> <pre><code>Error:App with the label polls could not be found. Are you ...
1
2010-04-07T20:16:54Z
2,595,657
<ul> <li>Is there an <code>__init__.py</code> file in the <code>polls</code> directory?</li> <li>Is <code>/home/kevin/crossen</code> on your python path?</li> </ul> <p>To check the path, do:</p> <pre><code>$ python -c "import sys; print sys.path" </code></pre>
1
2010-04-07T20:24:55Z
[ "python", "django" ]
Error when following along with the tutorial on the Django website
2,595,618
<p>I am following the django tutorial <a href="http://docs.djangoproject.com/en/1.1/intro/tutorial01/" rel="nofollow">here</a>. I have copied everything exactly. After the part where you enter the python manage.py sql polls command, it returns:</p> <pre><code>Error:App with the label polls could not be found. Are you ...
1
2010-04-07T20:16:54Z
29,846,169
<p>open 'site/settings.py' file and change the INSTALLED_APPS setting to include the string 'your_app' </p>
0
2015-04-24T11:20:53Z
[ "python", "django" ]
NoneType has no attribute Append
2,595,727
<p>I'm new to Python. I can't understand why a variable is <code>None</code> at a certain point in my code:</p> <pre><code>class UsersInRoom(webapp.RequestHandler): def get(self): room_id = self.request.get("room_id") username = self.request.get("username") UserInRoom_entities = UserInRoom....
3
2010-04-07T20:34:55Z
2,596,157
<p>Since it appears that my comment to the question had the answer to this, I'll repeat it as an answer, with the hope of gaining some reputation points:</p> <p>Is the <code>UserInRoom</code> instance initialized properly? I am not familiar with the GAE data model, but I could imagine that the <code>put()</code> ing t...
3
2010-04-07T21:43:16Z
[ "python", "google-app-engine", "syntax" ]
NoneType has no attribute Append
2,595,727
<p>I'm new to Python. I can't understand why a variable is <code>None</code> at a certain point in my code:</p> <pre><code>class UsersInRoom(webapp.RequestHandler): def get(self): room_id = self.request.get("room_id") username = self.request.get("username") UserInRoom_entities = UserInRoom....
3
2010-04-07T20:34:55Z
2,596,579
<p>To make sure that you're not the one raising exception, you can do something like:</p> <pre><code> UserInRoom_entities = [] # raised? then your .append is missing otherwise something else is wrong UserInRoom_entities.append UserInRoom_entities.append(user_in_room) </co...
0
2010-04-07T23:24:56Z
[ "python", "google-app-engine", "syntax" ]
Using python code in ASP.NET Web forms app
2,595,876
<p>I would like to use some code written in python (it uses built in modules) in a regular ASP.NET/C# web application. I am a newbie in python and have heard of IronPython and how ASP.NET now allows us to create IronPython apps.</p> <p>Any thoughts on which way I should proceed? The python code is the on <a href="http...
1
2010-04-07T20:58:34Z
2,596,036
<p>Some links:</p> <ul> <li><a href="http://aspnet.codeplex.com/wikipage?title=Dynamic%20Language%20Support&amp;ProjectName=aspnet" rel="nofollow">http://aspnet.codeplex.com/wikipage?title=Dynamic%20Language%20Support&amp;ProjectName=aspnet</a></li> <li><a href="http://stackoverflow.com/questions/441838/ironpython-on-...
2
2010-04-07T21:22:17Z
[ ".net", "asp.net", "python", "ironpython" ]
Compiling scipy on Windows 32-bit: linker error with libf77blas.a
2,596,069
<p>Has anyone tried compiling SciPy 0.7.1 on Windows using numpy-1.3.0 that was built with the pre-built ATLAS libraries (<code>atlas3.6.0_WinNT_P4SSE2.zip</code>) linked in the <a href="http://www.scipy.org/Installing_SciPy/Windows#head-cd37d819e333227e327079e4c2a2298daf625624" rel="nofollow">installation document</a>...
0
2010-04-07T21:28:48Z
2,687,944
<p>Our installation instructions are awfully out of date. First, you should use the binary installer unless you have a very good reason not to on windows. Here you are linking against an ATLAS which is different than the one numpy itself was built on, which is unlikely to work well (numpy and scipy would use different ...
1
2010-04-22T02:49:11Z
[ "python", "windows", "scipy", "linker-error", "atlas" ]
Why does `print foo.communicate()[0]` differ from `print foo.communicate()`"
2,596,261
<p>Here is the situation:</p> <p>I've got a command I'm running:</p> <pre><code>import subprocess foo = subprocess.Popen('ls /', shell=True, stdout=subprocess.PIPE,\ stderr=subprocess.STDOUT) </code></pre> <p>Pretty basic, right? And I've figured out that I can do stuff with the output with <code>.communicate()</cod...
1
2010-04-07T22:04:19Z
2,596,283
<p><code>foo.communicate()</code> returns a <code>tuple</code>. If you write <code>foo.communicate()[0]</code> you retrieve a first element in that tuple. Since this element is just a string, python interpreter prints it to your screen, printing <code>\n</code> as newlines.</p> <p>When you print a tuple from <code>foo...
2
2010-04-07T22:09:24Z
[ "python" ]
Why does `print foo.communicate()[0]` differ from `print foo.communicate()`"
2,596,261
<p>Here is the situation:</p> <p>I've got a command I'm running:</p> <pre><code>import subprocess foo = subprocess.Popen('ls /', shell=True, stdout=subprocess.PIPE,\ stderr=subprocess.STDOUT) </code></pre> <p>Pretty basic, right? And I've figured out that I can do stuff with the output with <code>.communicate()</cod...
1
2010-04-07T22:04:19Z
2,596,304
<p>In Python when you call something like <code>print obj</code>, you're actually calling the <code>__str__</code> on the object and then interpreting the result as a string.</p> <p>So for example say you have:</p> <pre><code> &gt;&gt;&gt; a = ('foo\nbar', '5') &gt;&gt;&gt; print a ('foo\nbar', '5') ...
3
2010-04-07T22:13:45Z
[ "python" ]
Scope of "library" methods
2,596,610
<p>I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.</p> <p>Background:<br> I'm using the</p> <pre><code>if __name__ == "__main__" </code></pre> <p>construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their ...
2
2010-04-07T23:33:39Z
2,596,631
<p>"Global scope" doesn't actually exist in Python. What is commonly called "global scope" is actually <strong>module scope</strong>. That is to say, names defined at the module level. Putting the function in another module means that its module scope changes.</p>
2
2010-04-07T23:39:10Z
[ "python", "import", "module", "scope" ]
Scope of "library" methods
2,596,610
<p>I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.</p> <p>Background:<br> I'm using the</p> <pre><code>if __name__ == "__main__" </code></pre> <p>construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their ...
2
2010-04-07T23:33:39Z
2,596,681
<p><strong>eval</strong> accepts two optional parameters -- <strong>global</strong> and <strong>local</strong> -- which you can specify as the context to evaluate your source:</p> <pre><code>print("%s = '%s'" % (var_in, eval(var_in, globals()))) </code></pre>
0
2010-04-07T23:53:59Z
[ "python", "import", "module", "scope" ]
Scope of "library" methods
2,596,610
<p>I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.</p> <p>Background:<br> I'm using the</p> <pre><code>if __name__ == "__main__" </code></pre> <p>construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their ...
2
2010-04-07T23:33:39Z
2,596,830
<p>In python each file is its own namespace. A function, when called, resolves its variables in the following order:</p> <ol> <li>local variables (that includes captured variables or in a closure)</li> <li>(module) global variables</li> <li>builtins</li> </ol> <p>You can use the (interpreter specific) <code>inspect</...
2
2010-04-08T00:33:07Z
[ "python", "import", "module", "scope" ]
Scope of "library" methods
2,596,610
<p>I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.</p> <p>Background:<br> I'm using the</p> <pre><code>if __name__ == "__main__" </code></pre> <p>construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their ...
2
2010-04-07T23:33:39Z
2,597,432
<p>I would recommend passing the locals() to the function, like so...</p> <pre><code>def pprint_var(var_name, D): print "%s = %r" % (var_name, D[var_name]) </code></pre> <p>...</p> <pre><code>pprint_var(var_name, locals()) </code></pre> <p>if you don't want that, you can use the inspect module or sys._getframe ...
1
2010-04-08T03:37:56Z
[ "python", "import", "module", "scope" ]
Scope of "library" methods
2,596,610
<p>I'm apparently laboring under a poor understanding of Python scoping. Perhaps you can help.</p> <p>Background:<br> I'm using the</p> <pre><code>if __name__ == "__main__" </code></pre> <p>construct to perform "self-tests" in my module(s). Each self test makes calls to the various public methods and prints their ...
2
2010-04-07T23:33:39Z
2,602,243
<p>The basic issue I'm running into is that Python has no sense of <strong>name</strong> for simple objects. For methods, classes, etc. yes, for simple objects, no.</p> <p>So in languages that feature variables, my 'ppvar' function would look something like this (pseudo-code):</p> <pre><code>ppvar( var_name ): p...
0
2010-04-08T17:50:06Z
[ "python", "import", "module", "scope" ]
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
<p>From the Python 2.6 shell:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.getdefaultencoding() ascii &gt;&gt;&gt; print u'\xe9' é &gt;&gt;&gt; </code></pre> <p>I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't...
113
2010-04-08T00:03:08Z
2,596,727
<p>The Python REPL tries to pick up what encoding to use from your environment. If it finds something sane then it all Just Works. It's when it can't figure out what's going on that it bugs out.</p> <pre><code>&gt;&gt;&gt; print sys.stdout.encoding UTF-8 </code></pre>
7
2010-04-08T00:07:43Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
<p>From the Python 2.6 shell:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.getdefaultencoding() ascii &gt;&gt;&gt; print u'\xe9' é &gt;&gt;&gt; </code></pre> <p>I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't...
113
2010-04-08T00:03:08Z
2,596,728
<p>You <em>have</em> specified an encoding by entering an explicit Unicode string. Compare the results of not using the <code>u</code> prefix.</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getdefaultencoding() 'ascii' &gt;&gt;&gt; '\xe9' '\xe9' &gt;&gt;&gt; u'\xe9' u'\xe9' &gt;&gt;&gt; print u'\xe9' é &gt;...
6
2010-04-08T00:08:07Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
<p>From the Python 2.6 shell:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.getdefaultencoding() ascii &gt;&gt;&gt; print u'\xe9' é &gt;&gt;&gt; </code></pre> <p>I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't...
113
2010-04-08T00:03:08Z
2,597,260
<p>When Unicode characters are printed to stdout, <code>sys.stdout.encoding</code> is used. A non-Unicode character is assumed to be in <code>sys.stdout.encoding</code> and is just sent to the terminal. On my system:</p> <pre><code>&gt;&gt;&gt; import unicodedata as ud &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.stdout...
19
2010-04-08T02:47:04Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
<p>From the Python 2.6 shell:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.getdefaultencoding() ascii &gt;&gt;&gt; print u'\xe9' é &gt;&gt;&gt; </code></pre> <p>I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't...
113
2010-04-08T00:03:08Z
21,968,640
<p>Thanks to bits and pieces from various replies, I think we can stitch up an explanation. </p> <p>By trying to print an unicode string, u'\xe9', Python implicitly try to encode that string using the encoding scheme currently stored in sys.stdout.encoding. Python actually picks up this setting from the environment it...
62
2014-02-23T13:09:38Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
Why does Python print unicode characters when the default encoding is ASCII?
2,596,714
<p>From the Python 2.6 shell:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.getdefaultencoding() ascii &gt;&gt;&gt; print u'\xe9' é &gt;&gt;&gt; </code></pre> <p>I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't...
113
2010-04-08T00:03:08Z
25,261,403
<p>It works for me: </p> <pre><code>import sys stdin, stdout = sys.stdin, sys.stdout reload(sys) sys.stdin, sys.stdout = stdin, stdout sys.setdefaultencoding('utf-8') </code></pre>
0
2014-08-12T09:57:56Z
[ "python", "unicode", "encoding", "ascii", "python-2.x" ]
Python (pdb) - Queueing up commands to execute
2,596,738
<p>I am implementing a "breakpoint" system for use in my Python development that will allow me to call a function that, in essence, calls pdb.set_trace();</p> <p>Some of the functionality that I would like to implement requires me to control pdb from code <em>while</em> I am within a set_trace context.</p> <p>Example...
2
2010-04-08T00:10:29Z
2,599,465
<p>You could invoke lower-level methods to get more control over the debugger:</p> <pre><code>def debug(): import pdb import sys # set up the debugger debugger = pdb.Pdb() debugger.reset() # your custom stuff here debugger.do_where(None) # run the "where" command # invoke the interac...
4
2010-04-08T11:38:30Z
[ "python", "debugging", "pdb" ]
Regex to split on successions of newline characters
2,596,771
<p>I'm trying to split a string on newline characters (catering for Windows, OS X, and Unix text file newline characters). If there are any succession of these, I want to split on that too and not include <em>any</em> in the result.</p> <p>So, for when splitting the following:</p> <pre><code>"Foo\r\n\r\nDouble Window...
8
2010-04-08T00:20:56Z
2,596,780
<pre><code>re.split(r'[\n\r]+', line) </code></pre>
3
2010-04-08T00:22:43Z
[ "python", "regex", "python-3.x" ]
Regex to split on successions of newline characters
2,596,771
<p>I'm trying to split a string on newline characters (catering for Windows, OS X, and Unix text file newline characters). If there are any succession of these, I want to split on that too and not include <em>any</em> in the result.</p> <p>So, for when splitting the following:</p> <pre><code>"Foo\r\n\r\nDouble Window...
8
2010-04-08T00:20:56Z
2,596,784
<p>The simplest pattern for this purpose is <code>r'[\r\n]+'</code> which you can pronounce as "one or more carriage-return or newline characters".</p>
6
2010-04-08T00:23:27Z
[ "python", "regex", "python-3.x" ]
Regex to split on successions of newline characters
2,596,771
<p>I'm trying to split a string on newline characters (catering for Windows, OS X, and Unix text file newline characters). If there are any succession of these, I want to split on that too and not include <em>any</em> in the result.</p> <p>So, for when splitting the following:</p> <pre><code>"Foo\r\n\r\nDouble Window...
8
2010-04-08T00:20:56Z
2,596,836
<pre><code>&gt;&gt;&gt; s="Foo\r\n\r\nDouble Windows\r\rDouble OS X\n\nDouble Unix\r\nWindows\rOS X\nUnix" &gt;&gt;&gt; import re &gt;&gt;&gt; re.split("[\r\n]+",s) ['Foo', 'Double Windows', 'Double OS X', 'Double Unix', 'Windows', 'OS X', 'Unix'] </code></pre>
1
2010-04-08T00:34:50Z
[ "python", "regex", "python-3.x" ]
Regex to split on successions of newline characters
2,596,771
<p>I'm trying to split a string on newline characters (catering for Windows, OS X, and Unix text file newline characters). If there are any succession of these, I want to split on that too and not include <em>any</em> in the result.</p> <p>So, for when splitting the following:</p> <pre><code>"Foo\r\n\r\nDouble Window...
8
2010-04-08T00:20:56Z
2,597,365
<p>If there are no spaces at the starts or ends of the lines, you can use <code>line.split()</code> with no arguments. It will remove doubles. . If not, you can use <code>[a for a a.split("\r\n") if a]</code>.</p> <p>EDIT: the <code>str</code> type also has a method called "splitlines".</p> <p><code>"Foo\r\n\r\nDoubl...
18
2010-04-08T03:19:33Z
[ "python", "regex", "python-3.x" ]
Regex to split on successions of newline characters
2,596,771
<p>I'm trying to split a string on newline characters (catering for Windows, OS X, and Unix text file newline characters). If there are any succession of these, I want to split on that too and not include <em>any</em> in the result.</p> <p>So, for when splitting the following:</p> <pre><code>"Foo\r\n\r\nDouble Window...
8
2010-04-08T00:20:56Z
32,635,719
<p>Paying attention to the greediness rules for patterns:</p> <pre><code>pattern = re.compile(r'(\r\n){2,}|(\n\r){2,}|(\r){2,}|(\n){2,}') paragraphs = pattern.split(text) </code></pre>
0
2015-09-17T16:44:55Z
[ "python", "regex", "python-3.x" ]
Python Mindstorms RCX
2,596,929
<p>I've got 30 unopened Lego Mindstorms kits that I'd love to use in my intro programming class to do some simple robotics stuff at the end of the year. We're using Python in the class, so I'd prefer there to be a way for the kids to write the programs in Python. Unfortunately, these are old kits with RCX bricks - not ...
13
2010-04-08T01:05:41Z
2,601,028
<p>I doubt it.</p> <p>The RCX bricks used an 8 bit microcontroller. While it might be possible to run some sort of a Python interpreter on it, I haven't seen one ported to it.</p> <p>The closest you can get is Java:</p> <p><a href="http://lejos.sourceforge.net/" rel="nofollow">http://lejos.sourceforge.net/</a></p> ...
2
2010-04-08T15:09:20Z
[ "python", "mindstorms", "lego" ]
Python Mindstorms RCX
2,596,929
<p>I've got 30 unopened Lego Mindstorms kits that I'd love to use in my intro programming class to do some simple robotics stuff at the end of the year. We're using Python in the class, so I'd prefer there to be a way for the kids to write the programs in Python. Unfortunately, these are old kits with RCX bricks - not ...
13
2010-04-08T01:05:41Z
2,609,471
<p>Running Python on the brick itself is probably hard (for the reason others already stated - size of the interpreter, available RAM on the brick for example) but this might be of interest:</p> <p><a href="http://mail.python.org/pipermail/python-list/2001-November/thread.html#691919" rel="nofollow">According to this ...
3
2010-04-09T17:18:25Z
[ "python", "mindstorms", "lego" ]
CherryPy sessions for same domain, different port
2,597,024
<p>Consider the script below. It will launch two subprocesses, each one a CherryPy app (hit Ctrl+C or whatever the KeyboardInterrupt combo is on your system to end them both). If you run it with CP 3.0 (taking care to change the 3.0/3.1 specific lines in "StartServer"), then visit:</p> <p><a href="http://localhost:150...
4
2010-04-08T01:35:12Z
2,621,432
<p>The cookie, where session identifier is stored, is bound to host, not host+port. When you visit the first site you get new session id <strong>in 3.1 (but not in 3.0)</strong>, then you fill session data and can see it. After that you go to other port with this session id, but now it's invalid (I believe you can see ...
3
2010-04-12T10:53:49Z
[ "python", "session", "cherrypy" ]
Break the nested (double) loop in Python
2,597,104
<p>I use the following method to break the double loop in Python.</p> <pre><code>for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break </code></pre> <p>Is there a better way to ...
26
2010-04-08T02:06:55Z
2,597,129
<p>Refactor using functions so you can return when you find your "bingo".</p> <p>The proposal to allow explicit breaking out of nested loops has been rejected: <a href="http://www.python.org/dev/peps/pep-3136/" rel="nofollow">http://www.python.org/dev/peps/pep-3136/</a></p>
3
2010-04-08T02:13:25Z
[ "python", "nested-loops" ]
Break the nested (double) loop in Python
2,597,104
<p>I use the following method to break the double loop in Python.</p> <pre><code>for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break </code></pre> <p>Is there a better way to ...
26
2010-04-08T02:06:55Z
2,597,351
<p>Probably not what you are hoping for, but usually you would want to have a <code>break</code> after setting <code>find</code> to <code>True</code></p> <pre><code>for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 ...
25
2010-04-08T03:13:41Z
[ "python", "nested-loops" ]
Break the nested (double) loop in Python
2,597,104
<p>I use the following method to break the double loop in Python.</p> <pre><code>for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break </code></pre> <p>Is there a better way to ...
26
2010-04-08T02:06:55Z
2,597,355
<p>Most times you can use a number of methods to make a single loop that does the same thing as a double loop.</p> <p>In your example, you can use <a href="http://docs.python.org/library/itertools.html#itertools.product">itertools.product</a> to replace your code snippet with</p> <pre><code>import itertools for word1...
7
2010-04-08T03:15:15Z
[ "python", "nested-loops" ]
Break the nested (double) loop in Python
2,597,104
<p>I use the following method to break the double loop in Python.</p> <pre><code>for word1 in buf1: find = False for word2 in buf2: ... if res == res1: print "BINGO " + word1 + ":" + word2 find = True if find: break </code></pre> <p>Is there a better way to ...
26
2010-04-08T02:06:55Z
4,553,525
<p>The recommended way in Python for breaking nested loops is... Exception</p> <pre><code>class Found(Exception): pass try: for i in range(100): for j in range(1000): for k in range(10000): if i + j + k == 777: raise Found except Found: print i, j, k </code...
24
2010-12-29T11:06:31Z
[ "python", "nested-loops" ]
Sorting elements in string with Python
2,597,119
<p>I need to sort string, and I came up with the following function.</p> <pre> def mysort(comb_): str = [] size = len(comb_) for c in comb_: str.append(c) str.sort() return ''.join(str) </pre> <p>Is there any way to make it compact?</p>
6
2010-04-08T02:11:35Z
2,597,134
<pre><code>return ''.join(sorted(comb_)) </code></pre>
18
2010-04-08T02:13:54Z
[ "python", "sorting" ]
Sorting elements in string with Python
2,597,119
<p>I need to sort string, and I came up with the following function.</p> <pre> def mysort(comb_): str = [] size = len(comb_) for c in comb_: str.append(c) str.sort() return ''.join(str) </pre> <p>Is there any way to make it compact?</p>
6
2010-04-08T02:11:35Z
2,597,154
<pre><code>def sortstr(comb_): return ''.join(sorted(comb_)) </code></pre> <p>e:f;b :(</p>
3
2010-04-08T02:17:44Z
[ "python", "sorting" ]
Sorting elements in string with Python
2,597,119
<p>I need to sort string, and I came up with the following function.</p> <pre> def mysort(comb_): str = [] size = len(comb_) for c in comb_: str.append(c) str.sort() return ''.join(str) </pre> <p>Is there any way to make it compact?</p>
6
2010-04-08T02:11:35Z
11,148,592
<p>If you want to get a string back do this:</p> <pre><code>def sort_string(string): return "".join(sorted(string)) </code></pre> <p>But if you want a list back, do this:</p> <pre><code>def sort_string(string): return sorted(string) </code></pre>
2
2012-06-22T00:08:54Z
[ "python", "sorting" ]
Sorting elements in string with Python
2,597,119
<p>I need to sort string, and I came up with the following function.</p> <pre> def mysort(comb_): str = [] size = len(comb_) for c in comb_: str.append(c) str.sort() return ''.join(str) </pre> <p>Is there any way to make it compact?</p>
6
2010-04-08T02:11:35Z
13,209,735
<pre><code>def sort_string(s): def sort_string_to_a_list(s): return sorted(s, lambda x,y: cmp(x.lower(), y.lower()) or cmp(x,y)) sorted_list = sort_string_to_a_list(s) return ''.join(sorted_list) </code></pre>
1
2012-11-03T13:43:36Z
[ "python", "sorting" ]
Make dictionary from list with python
2,597,166
<p>I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.</p> <pre> x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} </pre> <pre> def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 ...
19
2010-04-08T02:20:43Z
2,597,173
<pre><code>x = (1,'a',2,'b',3,'c') d = dict(x[n:n+2] for n in xrange(0, len(x), 2)) print d </code></pre>
3
2010-04-08T02:22:07Z
[ "python", "list", "dictionary" ]
Make dictionary from list with python
2,597,166
<p>I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.</p> <pre> x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} </pre> <pre> def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 ...
19
2010-04-08T02:20:43Z
2,597,178
<pre><code>dict(x[i:i+2] for i in range(0, len(x), 2)) </code></pre>
26
2010-04-08T02:22:29Z
[ "python", "list", "dictionary" ]
Make dictionary from list with python
2,597,166
<p>I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.</p> <pre> x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} </pre> <pre> def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 ...
19
2010-04-08T02:20:43Z
2,597,182
<pre><code>dict(zip(*[iter(val_)] * 2)) </code></pre>
10
2010-04-08T02:23:19Z
[ "python", "list", "dictionary" ]
Make dictionary from list with python
2,597,166
<p>I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.</p> <pre> x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} </pre> <pre> def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 ...
19
2010-04-08T02:20:43Z
2,597,275
<p>Here are a couple of ways for <strong>Python3</strong> using dict comprehensions</p> <pre><code>&gt;&gt;&gt; x = (1,'a',2,'b',3,'c') &gt;&gt;&gt; {k:v for k,v in zip(*[iter(x)]*2)} {1: 'a', 2: 'b', 3: 'c'} &gt;&gt;&gt; {x[i]:x[i+1] for i in range(0,len(x),2)} {1: 'a', 2: 'b', 3: 'c'} </code></pre>
10
2010-04-08T02:50:04Z
[ "python", "list", "dictionary" ]
Make dictionary from list with python
2,597,166
<p>I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.</p> <pre> x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'} </pre> <pre> def set(self, val_): i = 0 for val in val_: if i == 0: i = 1 ...
19
2010-04-08T02:20:43Z
2,597,381
<pre><code>&gt;&gt;&gt; x=(1,'a',2,'b',3,'c') &gt;&gt;&gt; dict(zip(x[::2],x[1::2])) {1: 'a', 2: 'b', 3: 'c'} </code></pre>
9
2010-04-08T03:23:19Z
[ "python", "list", "dictionary" ]
Django: Odd mark_safe behaviour?
2,597,184
<p>I wrote this little function for writing out HTML tags:</p> <pre><code>def html_tag(tag, content=None, close=True, attrs={}): lst = ['&lt;',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' /&gt;') ...
3
2010-04-08T02:24:10Z
5,119,089
<p>The <code>render</code> method of your widget is called by the <code>BoundField.__unicode__</code> function, which returns SafeString instead (of a subclass of <code>unicode</code>.)</p> <p>Many places in Django (e.g. <code>django.template.VariableNode.render</code>) will actually call <code>force_unicode</code> on...
7
2011-02-25T15:29:56Z
[ "python", "django" ]
virtualenvwrapper .hook problem
2,597,257
<p>I've used <em>virtualenvwrapper</em>, but I'm having problems running it on a new computer. My <em>.bashrc</em> file is updated per the instructions: </p> <pre><code>export WORKON_HOME=$DEV_HOME/projects source /usr/local/bin/virtualenvwrapper.sh </code></pre> <p>But when <em>source</em> is run, I get the followin...
4
2010-04-08T02:45:09Z
4,479,400
<p>Try storing your virtualenvs directory somewhere you are guaranteed not to have any permissions errors (and maybe even try using the absolute path). Also, are you sure you created the 'projects' directory manually? </p> <p>For reference, my bashrc file looks something like this:</p> <pre><code>export WORKON_HOME=/...
1
2010-12-18T18:25:51Z
[ "python", "wrapper", "virtualenv", "dollar-sign" ]
Python: load variables in a dict into namespace
2,597,278
<p>I want to use a bunch of local variables defined in a function, outside of the function. So I am passing <code>x=locals()</code> in the return value. </p> <p>How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using <code>x['var...
25
2010-04-08T02:50:31Z
2,597,440
<p>Consider the <code>Bunch</code> alternative:</p> <pre><code>class Bunch(object): def __init__(self, adict): self.__dict__.update(adict) </code></pre> <p>so if you have a dictionary <code>d</code> and want to access (read) its values with the syntax <code>x.foo</code> instead of the clumsier <code>d['foo']</c...
50
2010-04-08T03:40:50Z
[ "python", "variables", "locals" ]
Python: load variables in a dict into namespace
2,597,278
<p>I want to use a bunch of local variables defined in a function, outside of the function. So I am passing <code>x=locals()</code> in the return value. </p> <p>How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using <code>x['var...
25
2010-04-08T02:50:31Z
4,014,070
<p>This is perfectly valid case to import variables in one local space into another local space as long as one is aware of what he/she is doing. I have seen such code many times being used in useful ways. Just need to be careful not to pollute common global space.</p> <p>You can do the following:</p> <pre><code>adict...
11
2010-10-25T11:24:40Z
[ "python", "variables", "locals" ]
Python: load variables in a dict into namespace
2,597,278
<p>I want to use a bunch of local variables defined in a function, outside of the function. So I am passing <code>x=locals()</code> in the return value. </p> <p>How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using <code>x['var...
25
2010-04-08T02:50:31Z
4,906,299
<p>Importing variables into a local namespace is a valid problem and often utilized in templating frameworks.</p> <p>Return all local variables from a function:</p> <pre><code>return locals() </code></pre> <p>Then import as follows:</p> <pre><code>r = fce() for key in r.keys(): exec(key + " = r['" + key + "']") ...
7
2011-02-05T10:20:25Z
[ "python", "variables", "locals" ]
Python: load variables in a dict into namespace
2,597,278
<p>I want to use a bunch of local variables defined in a function, outside of the function. So I am passing <code>x=locals()</code> in the return value. </p> <p>How can I load all the variables defined in that dictionary into the namespace outside the function, so that instead of accessing the value using <code>x['var...
25
2010-04-08T02:50:31Z
39,539,722
<p>There's Always this option, I don't know that it is the best method out there, but it sure does work. Assuming type(x) = dict</p> <pre><code>for key, val in x.items(): # unpack the keys from the dictionary to individual variables exec (key + '=val') </code></pre>
0
2016-09-16T20:35:15Z
[ "python", "variables", "locals" ]
random.randint(1,n) in Python
2,597,444
<p>Most of us know that the command <code>random.randint(1,n)</code> in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ?</p>
7
2010-04-08T03:41:31Z
2,597,446
<p><code>randint()</code> works with long integers, so there is no upper limit:</p> <pre><code>&gt;&gt;&gt; random.randint(1,123456789012345678901234567890) 113144971884331658209492153398L </code></pre>
9
2010-04-08T03:43:26Z
[ "python", "random" ]
random.randint(1,n) in Python
2,597,444
<p>Most of us know that the command <code>random.randint(1,n)</code> in Python (2.X.X) would generate a number in random (pseudo-random) between 1 and n. I am interested in knowing what is the upper limit for n ?</p>
7
2010-04-08T03:41:31Z
2,597,749
<p>No doubt you have a bounded amount of memory, and address space, on your machine; for example, for a good 64-bit machine, 64 GB of RAM [[about <code>2**36</code> bytes]] and a couple of TB of disk (usable as swap space for virtual memory) [[about <code>2**41</code> bytes]]. So, the "upper bound" of a Python long in...
2
2010-04-08T05:24:29Z
[ "python", "random" ]
deletion of folders
2,597,501
<p>how can i delete a folder using python script?and what are the return values??</p>
0
2010-04-08T04:03:48Z
2,597,508
<p>If you want to delete a folder that's empty use <a href="http://docs.python.org/library/os.html#os.rmdir" rel="nofollow">os.rmdir</a>:</p> <pre><code>import os os.rmdir('/mypath') </code></pre> <p>If you want to delete a folder that's not empty use <a href="http://docs.python.org/library/shutil.html#shutil.rmtree"...
4
2010-04-08T04:06:11Z
[ "python", "directory" ]
deletion of folders
2,597,501
<p>how can i delete a folder using python script?and what are the return values??</p>
0
2010-04-08T04:03:48Z
2,597,538
<p>you can use <code>os.rmdir()</code> to remove a directory. To remove a directory tree recursively, you can use <code>shutil.rmtree</code>. If you know that you already have empty directory nodes, you can also check out <code>os.removedirs()</code></p>
0
2010-04-08T04:13:30Z
[ "python", "directory" ]
How to "uninstantiate" an object?
2,597,596
<p>I wrote a function in Python:</p> <pre><code>def instantiate(c): if inspect.isclass(c): return c() elif isinstance(c, object): return c else: raise Exception, '%s is not an object or class.' % c </code></pre> <p>Now I want to do the opposite: get the class from an already instantiated object so that I ...
0
2010-04-08T04:34:53Z
2,597,604
<p>To get the class of x</p> <pre><code>x.__class__ </code></pre>
3
2010-04-08T04:37:52Z
[ "python", "syntax" ]
How to "uninstantiate" an object?
2,597,596
<p>I wrote a function in Python:</p> <pre><code>def instantiate(c): if inspect.isclass(c): return c() elif isinstance(c, object): return c else: raise Exception, '%s is not an object or class.' % c </code></pre> <p>Now I want to do the opposite: get the class from an already instantiated object so that I ...
0
2010-04-08T04:34:53Z
2,597,605
<p>The class of object <code>c</code> is <code>type(c)</code>.</p>
2
2010-04-08T04:38:02Z
[ "python", "syntax" ]
Encoding in XML declaration python
2,597,622
<p>I have created an XML file using python. But the XML declaration has only version info. How can I include encoding with XML declaration like:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; </code></pre>
6
2010-04-08T04:44:38Z
2,597,717
<pre><code>&gt;&gt;&gt; from xml.dom.minidom import Document &gt;&gt;&gt; a=Document() &gt;&gt;&gt; a.toprettyxml(encoding="utf-8") '&lt;?xml version="1.0" encoding="utf-8"?&gt;\n' </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; a.toxml(encoding="utf-8") '&lt;?xml version="1.0" encoding="utf-8"?&gt;' </code></pre> <...
6
2010-04-08T05:13:25Z
[ "python", "xml", "encoding", "declaration" ]
Memcache in python
2,597,738
<p>I want to memcache an xmldata using python,also needs to update the cache with the refreshed xmldata retreived from webserver,could any one help me with sample code. </p>
3
2010-04-08T05:19:45Z
2,597,756
<p>This could be of some help:</p> <p><a href="http://code.google.com/appengine/docs/python/memcache/" rel="nofollow">http://code.google.com/appengine/docs/python/memcache/</a></p> <p>Quite a few nice code samples are included.</p>
2
2010-04-08T05:27:43Z
[ "python", "memcached" ]
Designing a Tag table that tells how many times it's used
2,597,751
<p>I am trying to design a tagging system with a model like this:</p> <pre><code>Tag: content = CharField creator = ForeignKey used = IntergerField </code></pre> <p>It is a many-to-many relationship between tags and what's been tagged.</p> <p>Everytime I insert a record into the assotication table, <strong...
1
2010-04-08T05:25:04Z
2,597,785
<p>I don't think it's a good idea to denormalize your data like that.</p> <p>I think a more elegant solution is to use django aggregation to track how many times the tag has been used <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/db/agg...
1
2010-04-08T05:36:50Z
[ "python", "django", "database-design", "tagging" ]
Designing a Tag table that tells how many times it's used
2,597,751
<p>I am trying to design a tagging system with a model like this:</p> <pre><code>Tag: content = CharField creator = ForeignKey used = IntergerField </code></pre> <p>It is a many-to-many relationship between tags and what's been tagged.</p> <p>Everytime I insert a record into the assotication table, <strong...
1
2010-04-08T05:25:04Z
2,599,630
<p>If your database support <a href="http://en.wikipedia.org/wiki/Materialized_view" rel="nofollow">materialized indexed views</a> then you might want to create one for this. You can get a large performance boost for frequently run queries that aggregate data, which I think you have here.</p> <p>your view would be on...
1
2010-04-08T12:08:32Z
[ "python", "django", "database-design", "tagging" ]
Is there a way to loop through and execute all of the functions in a Python class?
2,597,827
<p>I have</p> <pre><code>class Foo(): function bar(): pass function foobar(): pass </code></pre> <p>Rather than executing each function one by one as follows:</p> <pre><code>x = Foo() x.bar() x.foobar() </code></pre> <p>is there a built-in way to loop through and execute each function in th...
5
2010-04-08T05:51:15Z
2,597,838
<p>No. You can access <code>Foo.__dict__</code>, and call each value in turn (catching errors for non-callable members), but the order is not preserved.</p> <pre><code>for callable in Foo.__dict__.values(): try: callable() except TypeError: pass </code></pre> <p>This assumes none of the f...
6
2010-04-08T05:53:58Z
[ "python", "reflection", "class" ]
Is there a way to loop through and execute all of the functions in a Python class?
2,597,827
<p>I have</p> <pre><code>class Foo(): function bar(): pass function foobar(): pass </code></pre> <p>Rather than executing each function one by one as follows:</p> <pre><code>x = Foo() x.bar() x.foobar() </code></pre> <p>is there a built-in way to loop through and execute each function in th...
5
2010-04-08T05:51:15Z
2,597,844
<p>Since Python stores the methods (and other attributes) of a class in a dictionary, which is fundamentally unordered, this is impossible.</p> <p>If you don't care about order, use the class's <code>__dict__</code>:</p> <pre><code>x = Foo() results = [] for name, method in Foo.__dict__.iteritems(): if callable(m...
5
2010-04-08T05:55:48Z
[ "python", "reflection", "class" ]
Is there a way to loop through and execute all of the functions in a Python class?
2,597,827
<p>I have</p> <pre><code>class Foo(): function bar(): pass function foobar(): pass </code></pre> <p>Rather than executing each function one by one as follows:</p> <pre><code>x = Foo() x.bar() x.foobar() </code></pre> <p>is there a built-in way to loop through and execute each function in th...
5
2010-04-08T05:51:15Z
2,597,895
<pre><code>def assignOrder(order): @decorator def do_assignment(to_func): to_func.order = order return to_func return do_assignment class Foo(): @assignOrder(1) def bar(self): print "bar" @assignOrder(2) def foo(self): print "foo" #don't decorate functions you don't want called def...
8
2010-04-08T06:06:58Z
[ "python", "reflection", "class" ]
Is there a way to loop through and execute all of the functions in a Python class?
2,597,827
<p>I have</p> <pre><code>class Foo(): function bar(): pass function foobar(): pass </code></pre> <p>Rather than executing each function one by one as follows:</p> <pre><code>x = Foo() x.bar() x.foobar() </code></pre> <p>is there a built-in way to loop through and execute each function in th...
5
2010-04-08T05:51:15Z
2,607,516
<p>So long as you're only interested in Python 3.x (and from the empty parentheses in your class statement I'll guess you might be), then there is actually a simple way to do this without decorators: Python 3 allows you to provide your own dictionary like object to use while the class is defined.</p> <p>The following ...
1
2010-04-09T12:53:10Z
[ "python", "reflection", "class" ]
Is there a way to loop through and execute all of the functions in a Python class?
2,597,827
<p>I have</p> <pre><code>class Foo(): function bar(): pass function foobar(): pass </code></pre> <p>Rather than executing each function one by one as follows:</p> <pre><code>x = Foo() x.bar() x.foobar() </code></pre> <p>is there a built-in way to loop through and execute each function in th...
5
2010-04-08T05:51:15Z
38,506,610
<p>There is probably one of the shortest method (the class name is <em>C</em>):</p> <pre><code>for func in filter(lambda x: callable(x), C.__dict__.values()): pass # here func is the next function, you can execute it here </code></pre> <p>The <em>filter</em> expression returns all functions of the class C.</p> <...
0
2016-07-21T14:12:21Z
[ "python", "reflection", "class" ]
Generate fixed length hash in python for url parameter
2,597,833
<p>I am working in python on appengine. </p> <p>I am trying to create what is equivalent to the "v" value in the youtube url's (http://www.youtube.com/watch?v=<strong>XhMN0wlITLk</strong>) for retrieving specific entities. The datastore auto generates a key but it is way too long (34 digits). I have experimented with ...
10
2010-04-08T05:53:24Z
2,597,938
<p>You can use the auto generated <a href="http://code.google.com/appengine/docs/python/datastore/keyclass.html#Key_id" rel="nofollow">integer id</a> of the key to generate the hash. A simple way to generate the hash would be to convert the integer id to base62 (alphanumeric). To fetch the object simply convert to deci...
8
2010-04-08T06:16:19Z
[ "python", "google-app-engine", "url", "hash" ]
Generate fixed length hash in python for url parameter
2,597,833
<p>I am working in python on appengine. </p> <p>I am trying to create what is equivalent to the "v" value in the youtube url's (http://www.youtube.com/watch?v=<strong>XhMN0wlITLk</strong>) for retrieving specific entities. The datastore auto generates a key but it is way too long (34 digits). I have experimented with ...
10
2010-04-08T05:53:24Z
2,599,654
<p>If you have a value that is unique for every entity, you can get a shorter version by hashing it and truncating. Hashes like md5 or sha1 are well-mixed, meaning that every bit in the output has a 50% chance of flipping if you change one bit in the input. If you truncate the hash, you are simply increasing the odd...
5
2010-04-08T12:11:56Z
[ "python", "google-app-engine", "url", "hash" ]
Is it an MD5 digest in this Python script?
2,597,863
<p>I am trying to understand this simple hashlib code in Python that has been given to me the other day on Stackoverflow:</p> <pre><code>import hashlib m = hashlib.md5() m.update("Nobody inspects") m.update(" the spammish repetition here") m.digest() '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' m.di...
1
2010-04-08T06:01:47Z
2,597,897
<p>The <code>hashlib.hash</code> object doesn't implement its own <code>__str__</code>, so the default to-string operation is used, which prints the class name followed by its <code>id</code> (address).</p> <p>(Use <a href="http://docs.python.org/library/hashlib.html#hashlib.hash.hexdigest" rel="nofollow"><code>.hexdi...
3
2010-04-08T06:07:29Z
[ "python", "md5", "digest", "hashlib" ]