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
How can I run an external command asynchronously from Python?
636,561
<p>I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do.</p> <p>I read this post: </p> <blockquote> <p><a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python</a> </p> </blockquote> <p>I then went off and did some testing, and it looks like <code>os.system()</code> will do the job provided that I use <code>&amp;</code> at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried <code>commands.call()</code> but it will not work for me because it blocks on the external command.</p> <p>Please let me know if using <code>os.system()</code> for this is advisable or if I should try some other route.</p>
60
2009-03-11T22:01:42Z
636,570
<p><a href="http://docs.python.org/library/subprocess.html">subprocess.Popen</a> does exactly what you want.</p> <pre><code>from subprocess import Popen p = Popen(['watch', 'ls']) # something long running # ... do other stuff while subprocess is running p.terminate() </code></pre> <p>(Edit to complete the answer from comments)</p> <p>The Popen instance can do various other things like you can <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.poll"><code>poll()</code></a> it to see if it is still running, and you can <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate"><code>communicate()</code></a> with it to send it data on stdin, and wait for it to terminate.</p>
72
2009-03-11T22:05:32Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
How can I run an external command asynchronously from Python?
636,561
<p>I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do.</p> <p>I read this post: </p> <blockquote> <p><a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python</a> </p> </blockquote> <p>I then went off and did some testing, and it looks like <code>os.system()</code> will do the job provided that I use <code>&amp;</code> at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried <code>commands.call()</code> but it will not work for me because it blocks on the external command.</p> <p>Please let me know if using <code>os.system()</code> for this is advisable or if I should try some other route.</p>
60
2009-03-11T22:01:42Z
636,601
<p>If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:</p> <pre><code>from subprocess import Popen, PIPE import time running_procs = [ Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE) for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()] while running_procs: for proc in running_procs: retcode = proc.poll() if retcode is not None: # Process finished. running_procs.remove(proc) break else: # No process is done, wait a bit and check again. time.sleep(.1) continue # Here, `proc` has finished with return code `retcode` if retcode != 0: """Error handling.""" handle_results(proc.stdout) </code></pre> <p>The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)</p> <p><strong>This has the advantage of servicing the early-finishing requests first.</strong> If you call <code>communicate</code> on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.</p>
33
2009-03-11T22:15:50Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
How can I run an external command asynchronously from Python?
636,561
<p>I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do.</p> <p>I read this post: </p> <blockquote> <p><a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python</a> </p> </blockquote> <p>I then went off and did some testing, and it looks like <code>os.system()</code> will do the job provided that I use <code>&amp;</code> at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried <code>commands.call()</code> but it will not work for me because it blocks on the external command.</p> <p>Please let me know if using <code>os.system()</code> for this is advisable or if I should try some other route.</p>
60
2009-03-11T22:01:42Z
636,620
<p><strong>What I am wondering is if this [os.system()] is the proper way to accomplish such a thing?</strong></p> <p>No. <code>os.system()</code> is not the proper way. That's why everyone says to use <code>subprocess</code>. </p> <p>For more information, read <a href="http://docs.python.org/library/os.html#os.system">http://docs.python.org/library/os.html#os.system</a></p> <blockquote> <p>The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.</p> </blockquote>
7
2009-03-11T22:24:32Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
How can I run an external command asynchronously from Python?
636,561
<p>I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do.</p> <p>I read this post: </p> <blockquote> <p><a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python</a> </p> </blockquote> <p>I then went off and did some testing, and it looks like <code>os.system()</code> will do the job provided that I use <code>&amp;</code> at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried <code>commands.call()</code> but it will not work for me because it blocks on the external command.</p> <p>Please let me know if using <code>os.system()</code> for this is advisable or if I should try some other route.</p>
60
2009-03-11T22:01:42Z
636,719
<p>I've had good success with the <a href="http://www.lysator.liu.se/~bellman/download/asyncproc.py" rel="nofollow">asyncproc</a> module, which deals nicely with the output from the processes. For example:</p> <pre><code>import os from asynproc import Process myProc = Process("myprogram.app") while True: # check to see if process has ended poll = myProc.wait(os.WNOHANG) if poll is not None: break # print any new output out = myProc.read() if out != "": print out </code></pre>
5
2009-03-11T23:04:44Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
How can I run an external command asynchronously from Python?
636,561
<p>I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do.</p> <p>I read this post: </p> <blockquote> <p><a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python</a> </p> </blockquote> <p>I then went off and did some testing, and it looks like <code>os.system()</code> will do the job provided that I use <code>&amp;</code> at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried <code>commands.call()</code> but it will not work for me because it blocks on the external command.</p> <p>Please let me know if using <code>os.system()</code> for this is advisable or if I should try some other route.</p>
60
2009-03-11T22:01:42Z
959,402
<p>I have the same problem trying to connect to an 3270 terminal using the s3270 scripting software in Python. Now I'm solving the problem with an subclass of Process that I found here:</p> <p><a href="http://code.activestate.com/recipes/440554/" rel="nofollow">http://code.activestate.com/recipes/440554/</a></p> <p>And here is the sample taken from file:</p> <pre><code>def recv_some(p, t=.1, e=1, tr=5, stderr=0): if tr &lt; 1: tr = 1 x = time.time()+t y = [] r = '' pr = p.recv if stderr: pr = p.recv_err while time.time() &lt; x or r: r = pr() if r is None: if e: raise Exception(message) else: break elif r: y.append(r) else: time.sleep(max((x-time.time())/tr, 0)) return ''.join(y) def send_all(p, data): while len(data): sent = p.send(data) if sent is None: raise Exception(message) data = buffer(data, sent) if __name__ == '__main__': if sys.platform == 'win32': shell, commands, tail = ('cmd', ('dir /w', 'echo HELLO WORLD'), '\r\n') else: shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), '\n') a = Popen(shell, stdin=PIPE, stdout=PIPE) print recv_some(a), for cmd in commands: send_all(a, cmd + tail) print recv_some(a), send_all(a, 'exit' + tail) print recv_some(a, e=0) a.wait() </code></pre>
2
2009-06-06T10:07:22Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
How can I run an external command asynchronously from Python?
636,561
<p>I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do.</p> <p>I read this post: </p> <blockquote> <p><a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python</a> </p> </blockquote> <p>I then went off and did some testing, and it looks like <code>os.system()</code> will do the job provided that I use <code>&amp;</code> at the end of the command so that I don't have to wait for it to return. What I am wondering is if this is the proper way to accomplish such a thing? I tried <code>commands.call()</code> but it will not work for me because it blocks on the external command.</p> <p>Please let me know if using <code>os.system()</code> for this is advisable or if I should try some other route.</p>
60
2009-03-11T22:01:42Z
3,187,136
<p>Using pexpect [ <a href="http://www.noah.org/wiki/Pexpect">http://www.noah.org/wiki/Pexpect</a> ] with non-blocking readlines is another way to do this. Pexpect solves the deadlock problems, allows you to easily run the processes in the background, and gives easy ways to have callbacks when your process spits out predefined strings, and generally makes interacting with the process much easier.</p>
5
2010-07-06T14:30:28Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
Python Profiling in Eclipse
636,695
<p>This questions is semi-based of this one here:</p> <p><a href="http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script">http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script</a></p> <p>I thought that this would be a great idea to run on some of my programs. Although profiling from a batch file as explained in the aforementioned answer is possible, I think it would be even better to have this option in Eclipse. At the same time, making my entire program a function and profiling it would mean I have to alter the source code?</p> <p><strong>How can I configure eclipse such that I have the ability to run the profile command on my existing programs?</strong></p> <p>Any tips or suggestions are welcomed! </p>
11
2009-03-11T22:55:47Z
636,773
<p>You can always make separate modules that do just profiling specific stuff in your other modules. You can organize modules like these in a separate package. That way you don't change your existing code.</p>
0
2009-03-11T23:31:22Z
[ "python", "eclipse", "profiling" ]
Python Profiling in Eclipse
636,695
<p>This questions is semi-based of this one here:</p> <p><a href="http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script">http://stackoverflow.com/questions/582336/how-can-you-profile-a-python-script</a></p> <p>I thought that this would be a great idea to run on some of my programs. Although profiling from a batch file as explained in the aforementioned answer is possible, I think it would be even better to have this option in Eclipse. At the same time, making my entire program a function and profiling it would mean I have to alter the source code?</p> <p><strong>How can I configure eclipse such that I have the ability to run the profile command on my existing programs?</strong></p> <p>Any tips or suggestions are welcomed! </p>
11
2009-03-11T22:55:47Z
637,561
<p>if you follow the common python idiom to make all your code, even the "existing programs", importable as modules, you could do exactly what you describe, without any additional hassle.</p> <p>here is the specific idiom I am talking about, which turns your program's flow "upside-down" since the <code>__name__ == '__main__'</code> will be placed at the bottom of the file, once all your <code>def</code>s are done:</p> <pre><code># program.py file def foo(): """ analogous to a main(). do something here """ pass # ... fill in rest of function def's here ... # here is where the code execution and control flow will # actually originate for your code, when program.py is # invoked as a program. a very common Pythonism... if __name__ == '__main__': foo() </code></pre> <p>In my experience, <strong><em>it is quite easy to retrofit any existing scripts you have</em></strong> to follow this form, probably a couple minutes at most.</p> <p>Since there are other benefits to having you program also a module, you'll find most <code>python</code> scripts out there actually do it this way. One benefit of doing it this way: anything <code>python</code> you write is potentially useable in module form, including <code>cProfile</code>-ing of your <code>foo()</code>.</p>
4
2009-03-12T06:22:20Z
[ "python", "eclipse", "profiling" ]
Unable to make each sentence to start at a new line in LaTex by AWK/Python
636,887
<p>I have a long document in LaTex, which contains paragraphs. The paragraphs contain sentences such that no subsequent sentence start at a new line.</p> <p><strong>How can you make each subsequent sentence to start at a new line in my .tex file?</strong></p> <p><em>My attempt to the problem</em></p> <p>We need to put \n to the end of Sentence B where Sentence B has Sentence A before it.</p> <p>We must not put \n to the situations where there are the mark <code>\</code>. </p> <p>I see that the problem can be solved by AWK and Python. </p>
1
2009-03-12T00:14:08Z
636,955
<p>So you want every sentence in your .tex file to start on a new line, but without introducing extra paragraphs? Is that correct?</p> <p>Possibly you could go through your file and, every time you see a '.' followed by whitespace and a capital letter, insert a newline.</p> <p>e.g. in python:</p> <pre><code>import re sentence_end = r'\.\s+([A-Z])' source = open('myfile.tex') dest = open('myfile-out.tex', 'w') for line in source: dest.write(re.sub(sentence_end, '.\n\g&lt;1&gt;', line)) </code></pre>
2
2009-03-12T00:36:40Z
[ "python", "latex", "awk" ]
Unable to make each sentence to start at a new line in LaTex by AWK/Python
636,887
<p>I have a long document in LaTex, which contains paragraphs. The paragraphs contain sentences such that no subsequent sentence start at a new line.</p> <p><strong>How can you make each subsequent sentence to start at a new line in my .tex file?</strong></p> <p><em>My attempt to the problem</em></p> <p>We need to put \n to the end of Sentence B where Sentence B has Sentence A before it.</p> <p>We must not put \n to the situations where there are the mark <code>\</code>. </p> <p>I see that the problem can be solved by AWK and Python. </p>
1
2009-03-12T00:14:08Z
636,960
<p>What's wrong with putting a newline after each period? Eg:</p> <pre><code>awk '{ gsub(/\. +/, ".\n"); print }' $ echo "abc. 123. xyz." | awk '{ gsub(/\. +/, ".\n"); print }' abc. 123. xyz. </code></pre>
2
2009-03-12T00:38:46Z
[ "python", "latex", "awk" ]
Unable to make each sentence to start at a new line in LaTex by AWK/Python
636,887
<p>I have a long document in LaTex, which contains paragraphs. The paragraphs contain sentences such that no subsequent sentence start at a new line.</p> <p><strong>How can you make each subsequent sentence to start at a new line in my .tex file?</strong></p> <p><em>My attempt to the problem</em></p> <p>We need to put \n to the end of Sentence B where Sentence B has Sentence A before it.</p> <p>We must not put \n to the situations where there are the mark <code>\</code>. </p> <p>I see that the problem can be solved by AWK and Python. </p>
1
2009-03-12T00:14:08Z
636,981
<p>If I read your question correctly, what you need is the <code>\newline</code> command. Put it after each sentence. <code>\\</code> is a shortcut for this.</p> <p>A regex to do this would be something like</p> <pre><code>s/\. ([A-Z])/.\\newline\1/ </code></pre>
2
2009-03-12T00:49:58Z
[ "python", "latex", "awk" ]
Django form - set label
636,905
<p>I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done?</p> <p>I'm trying to do it in my <code>__init__</code>, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this?</p> <p>Thanks.</p> <p>Here is my form code:</p> <pre><code>from django import forms from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationFormUniqueEmail from registration.forms import RegistrationFormTermsOfService attrs_dict = { 'class': 'required' } class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address')) def __init__(self, *args, **kwargs): self.email.label = "New Email Label" super(RegistrationFormTOS, self).__init__(*args, **kwargs) def clean_email2(self): """ Verifiy that the values entered into the two email fields match. """ if 'email' in self.cleaned_data and 'email2' in self.cleaned_data: if self.cleaned_data['email'] != self.cleaned_data['email2']: raise forms.ValidationError(_(u'You must type the same email each time')) return self.cleaned_data </code></pre>
42
2009-03-12T00:18:35Z
637,019
<p>You access fields in a form via the 'fields' dict:</p> <pre><code>self.fields['email'].label = "New Email Label" </code></pre> <p>That's so that you don't have to worry about form fields having name clashes with the form class methods. (Otherwise you couldn't have a field named 'clean' or 'is_valid') Defining the fields directly in the class body is mostly just a convenience.</p>
6
2009-03-12T01:06:37Z
[ "python", "django", "inheritance", "django-forms" ]
Django form - set label
636,905
<p>I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done?</p> <p>I'm trying to do it in my <code>__init__</code>, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this?</p> <p>Thanks.</p> <p>Here is my form code:</p> <pre><code>from django import forms from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationFormUniqueEmail from registration.forms import RegistrationFormTermsOfService attrs_dict = { 'class': 'required' } class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address')) def __init__(self, *args, **kwargs): self.email.label = "New Email Label" super(RegistrationFormTOS, self).__init__(*args, **kwargs) def clean_email2(self): """ Verifiy that the values entered into the two email fields match. """ if 'email' in self.cleaned_data and 'email2' in self.cleaned_data: if self.cleaned_data['email'] != self.cleaned_data['email2']: raise forms.ValidationError(_(u'You must type the same email each time')) return self.cleaned_data </code></pre>
42
2009-03-12T00:18:35Z
637,020
<p>You should use:</p> <pre><code>def __init__(self, *args, **kwargs): super(RegistrationFormTOS, self).__init__(*args, **kwargs) self.fields['email'].label = "New Email Label" </code></pre> <p>Note first you should use the super call.</p>
86
2009-03-12T01:06:40Z
[ "python", "django", "inheritance", "django-forms" ]
Django form - set label
636,905
<p>I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done?</p> <p>I'm trying to do it in my <code>__init__</code>, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this?</p> <p>Thanks.</p> <p>Here is my form code:</p> <pre><code>from django import forms from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationFormUniqueEmail from registration.forms import RegistrationFormTermsOfService attrs_dict = { 'class': 'required' } class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address')) def __init__(self, *args, **kwargs): self.email.label = "New Email Label" super(RegistrationFormTOS, self).__init__(*args, **kwargs) def clean_email2(self): """ Verifiy that the values entered into the two email fields match. """ if 'email' in self.cleaned_data and 'email2' in self.cleaned_data: if self.cleaned_data['email'] != self.cleaned_data['email2']: raise forms.ValidationError(_(u'You must type the same email each time')) return self.cleaned_data </code></pre>
42
2009-03-12T00:18:35Z
5,677,126
<p>It don't work for model inheritance, but you can set the label directly in the model</p> <pre><code>email = models.EmailField("E-Mail Address") email_confirmation = models.EmailField("Please repeat") </code></pre>
0
2011-04-15T13:00:13Z
[ "python", "django", "inheritance", "django-forms" ]
Django form - set label
636,905
<p>I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done?</p> <p>I'm trying to do it in my <code>__init__</code>, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this?</p> <p>Thanks.</p> <p>Here is my form code:</p> <pre><code>from django import forms from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationFormUniqueEmail from registration.forms import RegistrationFormTermsOfService attrs_dict = { 'class': 'required' } class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address')) def __init__(self, *args, **kwargs): self.email.label = "New Email Label" super(RegistrationFormTOS, self).__init__(*args, **kwargs) def clean_email2(self): """ Verifiy that the values entered into the two email fields match. """ if 'email' in self.cleaned_data and 'email2' in self.cleaned_data: if self.cleaned_data['email'] != self.cleaned_data['email2']: raise forms.ValidationError(_(u'You must type the same email each time')) return self.cleaned_data </code></pre>
42
2009-03-12T00:18:35Z
19,262,996
<p>You can set <code>label</code> as an attribute of field when you define form.</p> <pre><code>class GiftCardForm(forms.ModelForm): card_name = forms.CharField(max_length=100, label="Cardholder Name") card_number = forms.CharField(max_length=50, label="Card Number") card_code = forms.CharField(max_length=20, label="Security Code") card_expirate_time = forms.CharField(max_length=100, label="Expiration (MM/YYYY)") class Meta: model = models.GiftCard exclude = ('price', ) </code></pre>
0
2013-10-09T04:14:27Z
[ "python", "django", "inheritance", "django-forms" ]
Django form - set label
636,905
<p>I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done?</p> <p>I'm trying to do it in my <code>__init__</code>, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this?</p> <p>Thanks.</p> <p>Here is my form code:</p> <pre><code>from django import forms from django.utils.translation import ugettext_lazy as _ from registration.forms import RegistrationFormUniqueEmail from registration.forms import RegistrationFormTermsOfService attrs_dict = { 'class': 'required' } class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService): """ Subclass of ``RegistrationForm`` which adds a required checkbox for agreeing to a site's Terms of Service. """ email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address')) def __init__(self, *args, **kwargs): self.email.label = "New Email Label" super(RegistrationFormTOS, self).__init__(*args, **kwargs) def clean_email2(self): """ Verifiy that the values entered into the two email fields match. """ if 'email' in self.cleaned_data and 'email2' in self.cleaned_data: if self.cleaned_data['email'] != self.cleaned_data['email2']: raise forms.ValidationError(_(u'You must type the same email each time')) return self.cleaned_data </code></pre>
42
2009-03-12T00:18:35Z
28,162,469
<p>Here's an example taken from <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields" rel="nofollow">Overriding the default fields</a>:</p> <blockquote> <pre><code>from django.utils.translation import ugettext_lazy as _ class AuthorForm(ModelForm): class Meta: model = Author fields = ('name', 'title', 'birth_date') labels = { 'name': _('Writer'), } help_texts = { 'name': _('Some useful help text.'), } error_messages = { 'name': { 'max_length': _("This writer's name is too long."), }, } </code></pre> </blockquote>
10
2015-01-27T02:54:37Z
[ "python", "django", "inheritance", "django-forms" ]
Best way to remove duplicate characters (words) in a string?
636,977
<p>What would be the best way of removing any duplicate characters and sets of characters separated by spaces in string?</p> <p>I think this example explains it better:</p> <pre><code>foo = 'h k k h2 h' </code></pre> <p>should become: </p> <pre><code>foo = 'h k h2' # order not important </code></pre> <p>Other example:</p> <pre><code>foo = 's s k' </code></pre> <p>becomes:</p> <pre><code>foo = 's k' </code></pre>
0
2009-03-12T00:48:24Z
636,982
<p>Do you mean?</p> <pre><code>' '.join( set( someString.split() ) ) </code></pre> <p>That's the unique space-delimited words in no particular order.</p>
8
2009-03-12T00:49:59Z
[ "python", "string", "duplicates" ]
Best way to remove duplicate characters (words) in a string?
636,977
<p>What would be the best way of removing any duplicate characters and sets of characters separated by spaces in string?</p> <p>I think this example explains it better:</p> <pre><code>foo = 'h k k h2 h' </code></pre> <p>should become: </p> <pre><code>foo = 'h k h2' # order not important </code></pre> <p>Other example:</p> <pre><code>foo = 's s k' </code></pre> <p>becomes:</p> <pre><code>foo = 's k' </code></pre>
0
2009-03-12T00:48:24Z
636,996
<pre><code>out = [] for word in input.split(): if not word in out: out.append(word) output_string = " ".join(out) </code></pre> <p>Longer than using a set, but it keeps the order.</p> <p><strong>Edit:</strong> Nevermind. I missed the part in the question about order not being important. Using a set is better.</p>
5
2009-03-12T00:57:24Z
[ "python", "string", "duplicates" ]
Best way to remove duplicate characters (words) in a string?
636,977
<p>What would be the best way of removing any duplicate characters and sets of characters separated by spaces in string?</p> <p>I think this example explains it better:</p> <pre><code>foo = 'h k k h2 h' </code></pre> <p>should become: </p> <pre><code>foo = 'h k h2' # order not important </code></pre> <p>Other example:</p> <pre><code>foo = 's s k' </code></pre> <p>becomes:</p> <pre><code>foo = 's k' </code></pre>
0
2009-03-12T00:48:24Z
636,997
<pre><code>' '.join(set(foo.split())) </code></pre> <p>Note that split() by default will split on all whitespace characters. (e.g. tabs, newlines, spaces)</p> <p>So if you want to split ONLY on a space then you have to use:</p> <pre><code>' '.join(set(foo.split(' '))) </code></pre>
10
2009-03-12T00:58:06Z
[ "python", "string", "duplicates" ]
wxPython or pygame for a simple card game?
636,990
<p>I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?</p>
6
2009-03-12T00:53:27Z
637,004
<p>I'd say pygame -- I've heard it's lots of fun, easy and happy. Also, all of my experiences with wxPython have been sad an painful.</p> <p>But I'm not bias or anything.</p>
1
2009-03-12T01:00:17Z
[ "python", "wxpython", "pygame", "playing-cards" ]
wxPython or pygame for a simple card game?
636,990
<p>I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?</p>
6
2009-03-12T00:53:27Z
637,017
<p>If all you want is a GUI, wxPython should do the trick.</p> <p>If you're looking to add sound, controller input, and take it beyond a simple card game, then you may want to use pygame.</p>
6
2009-03-12T01:06:26Z
[ "python", "wxpython", "pygame", "playing-cards" ]
wxPython or pygame for a simple card game?
636,990
<p>I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?</p>
6
2009-03-12T00:53:27Z
637,864
<p>I haven't used wxPython, but Pygame by itself is rather low-level. It allows you to catch key presses, mouse events and draw stuff on the screen, but doesn't offer any pre-made GUI controls. If you use Pygame, you will either have to write your own GUI classes or use existing GUI extensions for Pygame, like <a href="http://www.imitationpickles.org/pgu/wiki/index" rel="nofollow">Phil's Pygame Utilities</a>.</p>
4
2009-03-12T09:30:17Z
[ "python", "wxpython", "pygame", "playing-cards" ]
wxPython or pygame for a simple card game?
636,990
<p>I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?</p>
6
2009-03-12T00:53:27Z
638,393
<p>The answers to this related question may be very useful for you:</p> <p><a href="http://stackoverflow.com/questions/343505/what-can-pygame-do-in-terms-of-graphics-that-wxpython-cant">What can Pygame do in terms of graphics that wxPython can't?</a></p>
2
2009-03-12T12:26:51Z
[ "python", "wxpython", "pygame", "playing-cards" ]
wxPython or pygame for a simple card game?
636,990
<p>I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?</p>
6
2009-03-12T00:53:27Z
640,064
<p>Generally, PyGame is the better option for coding games. But that's for the more common type of games - where things move on the screen and you must have a good "frame-rate" performance. </p> <p>For something like a card game, however, I'd go with wxPython (or rather, PyQt). This is because a card game hasn't much in terms of graphics (drawing 2D card shapes on the screen is no harder in wx / PyQt than in PyGame). And on the other hand, you get lots of benefits from wx - like a ready-made GUI for interaction. </p> <p>In Pygame you have to create a GUI yourself or wade through several half-baked libraries that do it for you. This actually makes sense for Pygame because when you create a game you usually want a GUI of your own, that fits the game's style. But for card games, most chances are that wx's standard GUI widgets will do the trick and will save you hours of coding.</p>
2
2009-03-12T19:09:36Z
[ "python", "wxpython", "pygame", "playing-cards" ]
wxPython or pygame for a simple card game?
636,990
<p>I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?</p>
6
2009-03-12T00:53:27Z
3,550,215
<p>pygame is the typical choice, but pyglet has been getting a lot of attention at PyCon. Here's a wiki entry on Python Game libraries: <a href="http://wiki.python.org/moin/PythonGameLibraries" rel="nofollow">http://wiki.python.org/moin/PythonGameLibraries</a></p>
1
2010-08-23T17:49:38Z
[ "python", "wxpython", "pygame", "playing-cards" ]
Django: Uploaded file locked. Can't rename
637,160
<p>I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.</p> <p>I have it working when a file is first uploaded, when a new file is uploaded, and when there are no changes to the file or file title.</p> <p>However, when the title of the file is changed, and the system tries to rename the old file to the new path I get the following error:</p> <pre><code>WindowsError at /admin/main/file/1/ (32, 'The process cannot access the file because it is being used by another process') </code></pre> <p>I don't really know how to get around this. I've tried just coping the file to the new path. This works, but I don't know I can delete the old version.</p> <p>Shortened Model:</p> <pre><code>class File(models.Model): nzb = models.FileField(upload_to='files/') name = models.CharField(max_length=256) name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False) def save(self): # Create the name slug. self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower() self.name_slug = re.sub('[-]+', '-', self.name_slug) # Need the primary key for naming the file. super(File, self).save() # Create the system paths we need. orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb} renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug} # Rename the file. if orignal_nzb not in renamed_nzb: if os.path.isfile(renamed_nzb): os.remove(renamed_nzb) # Fails when name is updated. os.rename(orignal_nzb, renamed_nzb) self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug} super(File, self).save() </code></pre> <p>I suppose the question is, does anyone know how I can rename an uploaded file when the uploaded file isn't be re-uploaded? That's the only time it appears to be locked/in-use.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>Tyler's approach is working, except when a new file is uploaded the primary key is not available and his technique below is throwing an error.</p> <pre><code>if not instance.pk: instance.save() </code></pre> <p>Error:</p> <pre><code>maximum recursion depth exceeded while calling a Python object </code></pre> <p>Is there any way to grab the primary key?</p>
3
2009-03-12T02:14:52Z
637,169
<p>I think you should look more closely at the upload_to field. This would probably be simpler than messing around with renaming during save.</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield</a></p> <blockquote> <p>This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:</p> </blockquote>
5
2009-03-12T02:21:00Z
[ "python", "django", "file-io" ]
Django: Uploaded file locked. Can't rename
637,160
<p>I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.</p> <p>I have it working when a file is first uploaded, when a new file is uploaded, and when there are no changes to the file or file title.</p> <p>However, when the title of the file is changed, and the system tries to rename the old file to the new path I get the following error:</p> <pre><code>WindowsError at /admin/main/file/1/ (32, 'The process cannot access the file because it is being used by another process') </code></pre> <p>I don't really know how to get around this. I've tried just coping the file to the new path. This works, but I don't know I can delete the old version.</p> <p>Shortened Model:</p> <pre><code>class File(models.Model): nzb = models.FileField(upload_to='files/') name = models.CharField(max_length=256) name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False) def save(self): # Create the name slug. self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower() self.name_slug = re.sub('[-]+', '-', self.name_slug) # Need the primary key for naming the file. super(File, self).save() # Create the system paths we need. orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb} renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug} # Rename the file. if orignal_nzb not in renamed_nzb: if os.path.isfile(renamed_nzb): os.remove(renamed_nzb) # Fails when name is updated. os.rename(orignal_nzb, renamed_nzb) self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug} super(File, self).save() </code></pre> <p>I suppose the question is, does anyone know how I can rename an uploaded file when the uploaded file isn't be re-uploaded? That's the only time it appears to be locked/in-use.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>Tyler's approach is working, except when a new file is uploaded the primary key is not available and his technique below is throwing an error.</p> <pre><code>if not instance.pk: instance.save() </code></pre> <p>Error:</p> <pre><code>maximum recursion depth exceeded while calling a Python object </code></pre> <p>Is there any way to grab the primary key?</p>
3
2009-03-12T02:14:52Z
643,588
<p>Once uploaded, all you have is an image object in memory, right?</p> <p>You could save this object yourself in the folder of your choice, and then edit the database entry by hand.</p> <p>You'd be bypassing the whole Django ORM, and is not something I'd do unlessI couldn't find a more Django way.</p>
0
2009-03-13T16:40:01Z
[ "python", "django", "file-io" ]
Django: Uploaded file locked. Can't rename
637,160
<p>I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.</p> <p>I have it working when a file is first uploaded, when a new file is uploaded, and when there are no changes to the file or file title.</p> <p>However, when the title of the file is changed, and the system tries to rename the old file to the new path I get the following error:</p> <pre><code>WindowsError at /admin/main/file/1/ (32, 'The process cannot access the file because it is being used by another process') </code></pre> <p>I don't really know how to get around this. I've tried just coping the file to the new path. This works, but I don't know I can delete the old version.</p> <p>Shortened Model:</p> <pre><code>class File(models.Model): nzb = models.FileField(upload_to='files/') name = models.CharField(max_length=256) name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False) def save(self): # Create the name slug. self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower() self.name_slug = re.sub('[-]+', '-', self.name_slug) # Need the primary key for naming the file. super(File, self).save() # Create the system paths we need. orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb} renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug} # Rename the file. if orignal_nzb not in renamed_nzb: if os.path.isfile(renamed_nzb): os.remove(renamed_nzb) # Fails when name is updated. os.rename(orignal_nzb, renamed_nzb) self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug} super(File, self).save() </code></pre> <p>I suppose the question is, does anyone know how I can rename an uploaded file when the uploaded file isn't be re-uploaded? That's the only time it appears to be locked/in-use.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>Tyler's approach is working, except when a new file is uploaded the primary key is not available and his technique below is throwing an error.</p> <pre><code>if not instance.pk: instance.save() </code></pre> <p>Error:</p> <pre><code>maximum recursion depth exceeded while calling a Python object </code></pre> <p>Is there any way to grab the primary key?</p>
3
2009-03-12T02:14:52Z
643,789
<p>My other answer is deprecated, use this instead:</p> <pre><code>class File(models.Model): nzb = models.FileField(upload_to=get_filename) ... def get_filename(instance, filename): if not instance.pk: instance.save() # Create the name slug. name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower() name_slug = re.sub('[-]+', '-', name_slug) filename = u'filess/%(2)s_%(3)s.nzb' % {'2': instance.pk, '3': name_slug} return filename </code></pre> <p>As of 1.0, <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload%5Fto" rel="nofollow"><code>upload_to</code> can be callable</a>, in which case it is expected to return the filename, including path (relative to MEDIA_ROOT).</p>
3
2009-03-13T17:32:37Z
[ "python", "django", "file-io" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,309
<p>It can be confusing in some editors where one line is indented with spaces and the next is indented with a tab. This is confusing as the indentation looks the same but causes an error.</p> <p>Also when your copying code, if your editor doesn't have a function to indent entire blocks, it could be annoying fixing all the indentation.</p> <p>But with a good editor and a bit of practice, this shouldn't be a problem. I personally really like the way Python uses white space.</p>
11
2009-03-12T03:59:08Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,310
<p>The problem is that in Python, if you use spaces to indent basic blocks in one area of a file, and tabs to indent in another, you get a run-time error. This is quite different from semicolons in C.</p> <p>This isn't really a programming question, though, is it?</p>
0
2009-03-12T03:59:39Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,331
<p>That actually kept me away from Python for a while. Coming from a strong C background, I felt like I was driving without a seat belt.</p> <p>It was aggravating when I was trying to fill up a snippet library in my editor with boilerplate, frequently used classes. I learn best by example, so I was grabbing as many interesting snippets as I could with the aim of writing a useful program while learning.</p> <p>After I got in the habit of re-formatting everything that I borrowed, it wasn't so bad. But it still felt really awkward. I had to get used to a dynamically typed language PLUS indentation controlling my code.</p> <p>It was quite a leap for me :)</p>
2
2009-03-12T04:11:21Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,341
<p>Whitespace block delimiters force a certain amount of code formatting, which seems to irritate some programmers. Some in our shop seem to be of the attitude that they are too busy, or can't be bothered to pay attention to formatting standards, and a language that forces it rubs them raw. Sometimes the same folks gripe when others do not follow the same patterns of putting curly braces on a new line ;)</p> <p>I find that Python code from the web is more commonly "readable", since this minor formatting requirement is in place. IMO, this requirement is a very useful feature.</p> <p>IIRC, does not Haskell, OCaml (#light), and F# also use whitespace in the same fashion? For some reason, I have not seen any complaints about these languages.</p>
1
2009-03-12T04:18:40Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,342
<p>Long ago, in and environment far, far away, there were languages (such as RPG) that depended on the column structure of punch cards. This was a tedious and annoying system, and led to many errors, and newer languages such as BASIC, pascal, and so forth were designed without this dependency.</p> <p>A generation of programmers were trained on these languages and told repeatedly that the freedom to put anything anywhere was a wonderful feature of the newer languages, and they should be grateful. The freedom was used, abused, and calibrated (cf the <a href="http://www.ioccc.org/" rel="nofollow">IOCC</a>) for many years.</p> <p>Now the pendulum has begun to swing back, but many people still remember that forced layout is bad in some way vague, and resist it.</p> <p>IMHO, the thing to do is to work with languages on their own terms, and not get hung up on tastes-great-less-filling battles.</p>
1
2009-03-12T04:18:46Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,344
<p>Some people say that they don't like python indentation, because it can cause errors, which would be immensely hard to detect in case if tabs and spaces are mixed. For example: </p> <pre><code>1 if needFrobnicating: 2 frobnicate() 3 update() </code></pre> <p>Depending on the tab width, line 3 may appear to be in the same block as line 2, or in the enclosing block. This won't cause runtime or compile error, but the program would do unexpected thing.</p> <p>Though I program in python for 10 years and never seen an error caused by mixing tabs and spaces</p>
1
2009-03-12T04:20:47Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,361
<p>The only trouble I've ever had is minor annoyances when I'm using code I wrote before I settled on whether I liked tabs or spaces, or cutting and posting code from a website.</p> <p>I think most decent editors these days have a convert tabs-to-spaces and back option. Textmate certainly does.</p> <p>Beyond that, the indentation has never caused me any trouble.</p>
0
2009-03-12T04:27:56Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,375
<p>When python programmers don't follow the common convention of "Use 4 spaces per indentation level" defined in <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow"><strong>PEP 8</strong></a>. (<em>If your a python programmer and haven't read it please do so</em>)</p> <p>Then you run into copy paste issues.</p>
1
2009-03-12T04:33:26Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,388
<p>Pick a good editor. You'd want features such as:</p> <ol> <li>Automatic indentation that mimics the last indented line</li> <li>Automatic indentation that you can control (tabs vs. spaces)</li> <li>Show whitespace characters</li> <li>Detection and mimicking of whitespace convention when loading a file</li> </ol> <p>For example, Vim lets me highlight tabs with these settings:</p> <pre><code>set list set listchars=tab:\|_ highlight SpecialKey ctermbg=Red guibg=Red highlight SpecialKey ctermfg=White guifg=White </code></pre> <p>Which can be turned off at any time using:</p> <pre><code>set nolist </code></pre> <p>IMO, I dislike editor settings that convert tabs to spaces or vice versa, because you end up with a mix of tabs and spaces, which can be nasty.</p>
1
2009-03-12T04:37:09Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,404
<p>I used to think that the white space issues was just a question of getting used to it.</p> <p>Someone pointed out some serious flaws with Python indentation and I think they are quite valid and some subconcious understanding of these is what makes experienced programs nervious about the whole thing:-</p> <ul> <li>Cut and paste just doesnt work anymore! You cannot cut boiler plate code from one app and drop it into another app.</li> <li>Your editor becomes powerless to help you. With C/Jave etc. there are two things going on the "official" curly brackets indentation, and, the "unnofficial" white space indentation. Most editors are able reformat hte white space indentation to match the curly brackets nesting -- which gives you a string visual clue that something is wrong if the indentation is not what you expected. With pythons "space is syntax" paradigm your editor cannot help you.</li> <li>The sheer pain of introducing another condition into already complex logic. Adding another if then else into an existing condition involves lots of silly error prone inserting of spaces on many lines line by hand.</li> <li>Refactoring is a nightmare. Moving blocks of code around your classes is so painful its easier to put up with a "wrong" class structure than refactor it into a better one. </li> </ul>
0
2009-03-12T04:48:18Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
637,423
<p>yeah there are some pitfalls, but most of the time, in practice, they turn out to be enemy <a href="http://en.wikipedia.org/wiki/Tilting%5Fat%5Fwindmills">windmills of the Quixotic style</a>, i.e. imaginary, and nothing to worry about in reality. </p> <p>I would estimate that the pitfalls one is <em>most likely to encounter</em> are (including mitigating steps identified):</p> <ol> <li><p><strong>working with others a.k.a. collaboration</strong> </p> <p>a. if you have others which for whatever reason refuse to adhere to <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>, then it could become a pain to maintain code. I've never seen this in practice once I point out to them the almost universal convention for python is <strong>indent level == four spaces</strong> </p> <p>b. get anyone/everyone you work with to accept the convention and have them figure out how to have their editor automatically do it (or better yet, if you use the same editor, show them how to configure it) such that copy-and-paste and stuff <em>just works</em>. </p></li> <li><p><strong>having to invest in a "decent" editor other than your current preferred one, if your current preferred editor is not python friendly</strong> -- not really a pitfall, more an investment requirement to avoid the other pitfalls mentioned associated with copy-and-paste, re-factoring, etc. stop using Notepad and you'll thank yourself in the morning.</p> <p>a. your efficiency in editing the code will be much higher under an editor which understands <code>python</code></p> <p>b. most <em>modern</em> code editors handle python decently. I myself prefer GNU Emacs, and recent versions come with excellent <code>python-mode</code> support out-of-the-box. The are plenty of <a href="http://wiki.python.org/moin/PythonEditors">other editors to explore</a>, including many free alternatives and <a href="http://wiki.python.org/moin/IntegratedDevelopmentEnvironments">IDEs</a>.</p> <p>c. python itself comes out of the box with a "smart" python editor, <code>idle</code>. Check it out if you are not familiar, as it is probably already available with your python install, and may even support <code>python</code> better than your current editor. <a href="http://wxpython.org/py.php">PyCrust</a> is another option for a python editor implemented in python, and comes as part of wxPython.</p></li> <li><p><strong>some code generation or templating environments that incorporate python (think HTML generation or python CGI/WSGI apps) can have quirks</strong></p> <p>a. most of them, if they touch python, have taken steps to minimize the nature of python as an issue, but it still pops up once in a while.</p> <p>b. if you encounter this, familiarize yourself with the steps that the framework authors have already taken to minimize the impact, and read their suggestions (<em>and yes they will have some if it has ever been encountered in their project</em>), and it will be simple to avoid the pitfalls related to python on this.</p></li> </ol>
10
2009-03-12T04:56:58Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
638,131
<p>When I look at C and Java code, it's always nicely indented.</p> <p>Always. Nicely. Indented. </p> <p>Clearly, C and Java folks spend a lot of time getting their whitespace right.</p> <p>So do Python programmers.</p>
2
2009-03-12T11:02:21Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
638,534
<p>If you use Eclipse as your IDE, you should take a look at PyDev; it handles indentation and spacing automatically. You can copy-paste from mixed-spacing sources, and it will convert them for you. Since I started learning the language, I've never once had to think about spacing.</p> <p>And it's really a non-issue; sane programmers indent anyway. With Python, you just do what you've always done, minus having to type and match braces.</p>
1
2009-03-12T13:05:08Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
639,229
<p>If your using emacs, set a hard tab length of 8 and a soft tab length of 4. This way you will be alterted to any extraneous tab characters. You should always uses 4 spaces instead of tabs.</p>
0
2009-03-12T15:40:53Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
639,262
<p>One drawback I experienced as a beginner whith python was forgetting to set softtabs in my editors gave me lots of trouble.</p> <p>But after a year of serious use of the language I'm not able to write poorly indented code anymore in any other language.</p>
0
2009-03-12T15:51:21Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
639,671
<p>Pitfalls</p> <ul> <li><p>It can be annoying posting code snippets on web sites that ignore your indentation.</p></li> <li><p>Its hard to see how multi-line anonymous functions (lambdas) can fit in with the syntax of the language.</p></li> <li><p>It makes it hard to embed Python in HTML files to make templates in the way that PHP or C# can be embedded in PHP or ASP.NET pages. But that's not necessarily the best way to design templates anyway.</p></li> <li><p>If your editor does not have sensible commands for block indent and outdent it will be tedious to realign code.</p></li> </ul> <p>Advantages</p> <ul> <li><p>Forces even lazy programmers to produce legible code. I've seen examples of brace-language code that I had to spend hours reformatting to be able to read it...</p></li> <li><p>Python programmers do not need to spend hours discussing whether braces should go at the ends of lines K&amp;R style or on lines on their own in the Microsoft style.</p></li> <li><p>Frees the brace characters for use for dictionary and set expressions.</p></li> <li><p>Is automatically pretty legible</p></li> </ul>
1
2009-03-12T17:33:41Z
[ "python", "whitespace" ]
Are there any pitfalls with using whitespace in Python?
637,295
<p>At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language? </p>
3
2009-03-12T03:50:34Z
639,767
<p>No, I would say that is one thing to which I can find no downfalls. Yes, it is no doubt irritating to some, but that is just because they have a different habit about their style of formatting. Learn it early, and it's gonna stick. Just look how many discussions we have over a style matter in languages like C, Cpp, Java and such. You don't see those (useless, no doubt) discussions about languages like Python, F77, and some others mentioned here which have a "fixed" formatting style.</p> <p>The only thing which is variable is spaces vs. tabs (can be changed with a little trouble with any good editor), and amount of spaces tab accounts for (can be changed with no trouble with any good editor). Voila ! Style discussion complete.</p> <p>Now I can do something useful :)</p>
0
2009-03-12T17:55:43Z
[ "python", "whitespace" ]
Default encoding for python for stderr?
637,396
<p>I've got a noisy python script that I want to silence by directing its stderr output to /dev/null (using bash BTW).</p> <p>Like so:</p> <pre><code>python -u parse.py 1&gt; /tmp/output3.txt 2&gt; /dev/null </code></pre> <p>but it quickly exits prematurely. Hmm. I can't see the traceback because of course that goes out with stderr. It runs noisily and normally if I don't direct stderr somewhere.</p> <p>So let's try redirecting it to a file somewhere rather than /dev/null, and take a look at what it's outputting:</p> <pre><code>python -u parse.py 1&gt; /tmp/output3.txt 2&gt; /tmp/foo || tail /tmp/foo Traceback (most recent call last): File "parse.py", line 79, in &lt;module&gt; parseit('pages-articles.xml') File "parse.py", line 33, in parseit print &gt;&gt;sys.stderr, "bad page title", page_title UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) </code></pre> <p>So, the stderr that's being generated contains utf8, and for some reason python refuses to print non-ascii when it's being redirected, even though it's being directed to /dev/null (though of course python doesn't know that).</p> <p>How can I silence the stderr of a python script even though it contains utf8? Is there any way to do it without re-writing every print to stderr in this script?</p>
7
2009-03-12T04:45:51Z
637,411
<p>When stderr is not redirected, it takes on the encoding of your terminal. This all goes out the door when you redirect it though. You'll need to use sys.stderr.isatty() in order to detect if it's redirected and encode appropriately.</p>
4
2009-03-12T04:52:13Z
[ "python", "bash", "shell", "unicode" ]
Default encoding for python for stderr?
637,396
<p>I've got a noisy python script that I want to silence by directing its stderr output to /dev/null (using bash BTW).</p> <p>Like so:</p> <pre><code>python -u parse.py 1&gt; /tmp/output3.txt 2&gt; /dev/null </code></pre> <p>but it quickly exits prematurely. Hmm. I can't see the traceback because of course that goes out with stderr. It runs noisily and normally if I don't direct stderr somewhere.</p> <p>So let's try redirecting it to a file somewhere rather than /dev/null, and take a look at what it's outputting:</p> <pre><code>python -u parse.py 1&gt; /tmp/output3.txt 2&gt; /tmp/foo || tail /tmp/foo Traceback (most recent call last): File "parse.py", line 79, in &lt;module&gt; parseit('pages-articles.xml') File "parse.py", line 33, in parseit print &gt;&gt;sys.stderr, "bad page title", page_title UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) </code></pre> <p>So, the stderr that's being generated contains utf8, and for some reason python refuses to print non-ascii when it's being redirected, even though it's being directed to /dev/null (though of course python doesn't know that).</p> <p>How can I silence the stderr of a python script even though it contains utf8? Is there any way to do it without re-writing every print to stderr in this script?</p>
7
2009-03-12T04:45:51Z
638,331
<p>You could also just encode the string as ASCII, replacing unicode characters that don't map. Then you don't have to worry about what kind of terminal you have.</p> <pre><code>asciiTitle = page_title.encode("ascii", "backslashreplace") print &gt;&gt;sys.stderr, "bad page title", asciiTitle </code></pre> <p>That replaces the characters that can't be encoded with backslash-escapes, i.e. <code>\xfc</code>. There are some other replace options too, described here:</p> <p><a href="http://docs.python.org/library/stdtypes.html#str.encode" rel="nofollow">http://docs.python.org/library/stdtypes.html#str.encode</a></p>
2
2009-03-12T12:06:07Z
[ "python", "bash", "shell", "unicode" ]
Default encoding for python for stderr?
637,396
<p>I've got a noisy python script that I want to silence by directing its stderr output to /dev/null (using bash BTW).</p> <p>Like so:</p> <pre><code>python -u parse.py 1&gt; /tmp/output3.txt 2&gt; /dev/null </code></pre> <p>but it quickly exits prematurely. Hmm. I can't see the traceback because of course that goes out with stderr. It runs noisily and normally if I don't direct stderr somewhere.</p> <p>So let's try redirecting it to a file somewhere rather than /dev/null, and take a look at what it's outputting:</p> <pre><code>python -u parse.py 1&gt; /tmp/output3.txt 2&gt; /tmp/foo || tail /tmp/foo Traceback (most recent call last): File "parse.py", line 79, in &lt;module&gt; parseit('pages-articles.xml') File "parse.py", line 33, in parseit print &gt;&gt;sys.stderr, "bad page title", page_title UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) </code></pre> <p>So, the stderr that's being generated contains utf8, and for some reason python refuses to print non-ascii when it's being redirected, even though it's being directed to /dev/null (though of course python doesn't know that).</p> <p>How can I silence the stderr of a python script even though it contains utf8? Is there any way to do it without re-writing every print to stderr in this script?</p>
7
2009-03-12T04:45:51Z
638,823
<p>You can silence stderr by binding it to a custom writer:</p> <pre><code>#!/usr/bin/env python import codecs, sys class NullWriter: def write(self, *args, **kwargs): pass if len(sys.argv) == 2: if sys.argv[1] == '1': sys.stderr = NullWriter() elif sys.argv[1] == '2': #NOTE: sys.stderr.encoding is *read-only* # therefore the whole stderr should be replaced # encode all output using 'utf8' sys.stderr = codecs.getwriter('utf8')(sys.stderr) print &gt;&gt;sys.stderr, u"\u20AC" # euro sign print "ok" </code></pre> <p>Example:</p> <pre><code>$ python silence_stderr.py Traceback (most recent call last): File "silence_stderr.py", line 11, in &lt;module&gt; print &gt;&gt;sys.stderr, u"\u20AC" UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128) </code></pre> <p>Silenced stderr:</p> <pre><code>$ python silence_stderr.py 1 ok </code></pre> <p>Encoded stderr:</p> <pre><code>$ python silence_stderr.py 2 € ok </code></pre> <p><strong>NOTE</strong>: I've got the above outputs inside emacs therefore to emulate it in a terminal you could do:</p> <pre><code>$ python ... 2&gt;out.txt $ cat out.txt </code></pre> <p><strong>NOTE</strong>: Inside Windows console (after <code>chcp 65001</code> that switch to 'utf-8' and with truetype font (<code>Lucida Console</code>)) I've got strange results:</p> <pre><code>C:\&gt; python silence_stderr.py 2 Traceback (most recent call last): File "silence_stderr.py", line 14, in &lt;module&gt; print &gt;&gt;sys.stderr, u"\u20AC" # euro sign File "C:\pythonxy\python\lib\codecs.py", line 304, in write self.stream.write(data) IOError: [Errno 13] Permission denied </code></pre> <p>If the font is not truetype then the exception doesn't raise but the output is wrong.</p> <p>Perl works for the truetype font:</p> <pre><code>C:\&gt; perl -E"say qq(\x{20ac})" Wide character in print at -e line 1. € </code></pre> <p>Redirection works though:</p> <pre><code>C:\&gt;python silence_stderr.py 2 2&gt;tmp.log ok C:\&gt;cat tmp.log € cat: write error: Permission denied </code></pre> <h3>re comment</h3> <p>From <a href="http://docs.python.org/library/codecs.html#codecs.getwriter"><code>codecs.getwriter</code></a> documentation:</p> <blockquote> <p>Look up the codec for the given encoding and return its StreamWriter class or factory function. Raises a <code>LookupError</code> in case the encoding cannot be found.</p> </blockquote> <p>An oversimplified view:</p> <pre><code>class UTF8StreamWriter: def __init__(self, writer): self.writer = writer def write(self, s): self.writer.write(s.encode('utf-8')) sys.stderr = UTF8StreamWriter(sys.stderr) </code></pre>
5
2009-03-12T14:22:25Z
[ "python", "bash", "shell", "unicode" ]
On interface up, possible to scan for a specific MAC address?
637,399
<p>I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.</p> <p>So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.</p> <p>This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.</p> <p>I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <a href="http://www.secdev.org/projects/scapy/index.html" rel="nofollow">http://www.secdev.org/projects/scapy/index.html</a> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause.</p>
0
2009-03-12T04:47:34Z
637,419
<p>Just make sure Avahi / Bonjour's running, then type <em>hostname</em>.local (or also try <em>hostname</em>.localdomain) - it resolves using mDNS, so you don't have to care what your IP is or rigging /etc/hosts.</p>
1
2009-03-12T04:54:23Z
[ "python", "linux", "networking", "sysadmin" ]
On interface up, possible to scan for a specific MAC address?
637,399
<p>I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.</p> <p>So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.</p> <p>This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.</p> <p>I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <a href="http://www.secdev.org/projects/scapy/index.html" rel="nofollow">http://www.secdev.org/projects/scapy/index.html</a> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause.</p>
0
2009-03-12T04:47:34Z
637,939
<p>You could also use <strong>arp-scan</strong> (a Debian package of the name exists, not sure about other distributions) to scan your whole network. Have a script parse its output and you'll be all set.</p>
0
2009-03-12T09:58:39Z
[ "python", "linux", "networking", "sysadmin" ]
On interface up, possible to scan for a specific MAC address?
637,399
<p>I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.</p> <p>So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.</p> <p>This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.</p> <p>I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <a href="http://www.secdev.org/projects/scapy/index.html" rel="nofollow">http://www.secdev.org/projects/scapy/index.html</a> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause.</p>
0
2009-03-12T04:47:34Z
637,992
<p>Sorry, it looks like an attempt to create a problem where no problem exists, and subsequently solve it using a bit crazy methods. :)</p> <p>You can configure your dhcp server (router) to always issue a fixed ip for your workstation. If you don't have dhcp server, then why do you use dhcp for configuring the interface? Change the configuration (<code>/etc/network/interfaces</code> in Ubuntu and Debian) to assign static ip address to the interface.</p>
1
2009-03-12T10:15:28Z
[ "python", "linux", "networking", "sysadmin" ]
On interface up, possible to scan for a specific MAC address?
637,399
<p>I admit the linux network system is somewhat foreign to me, I know enough of it to configure routes manually and assign a static IP if necessary.</p> <p>So quick question, in the ifconfig configuration files, is it possible to add a post connect hook to a python script then use a python script to reassign a hostname in /etc/hosts and spawn off a new process to do other things once the hostname has been updated.</p> <p>This is a "fun" project for me to solve an annoyance in my daily routine. When I boot up my workstation in the morning, the DHCP service assigns it a IP at random. So I usually stop what I'm doing, lookup my new IP, type that IP into my laptop and get synergy running so I can share the two machines. I figure I lose 10-15 minutes a day doing this everyday of the week and I've never really messed with linux's networking system so it would ultimately pan out.</p> <p>I already figured my python script would have to run as root, therefore I'd store it in /root or somewhere else that's safe. I found a similar question on stack overflow that pointed me in the direction of <a href="http://www.secdev.org/projects/scapy/index.html" rel="nofollow">http://www.secdev.org/projects/scapy/index.html</a> a raw packet toolset to work with ARP. Editing the host file is a snap... just wondering what possible side effects of trying to put this hook into a core service might cause.</p>
0
2009-03-12T04:47:34Z
672,780
<p>Cleanest solution would be to have a DHCP server that exchanges its assignments with a local DNS server. So regardless which IP address your workstation is being assigned to, it is accessible under the same hostname. </p> <p>This concept is used in every full-blown windows network as well as in any other well configured network.</p>
1
2009-03-23T09:59:38Z
[ "python", "linux", "networking", "sysadmin" ]
Django with Passenger
637,565
<p>I'm trying to get a trivial Django project working with Passenger on Dreamhost, following the instructions <a href="http://www.soasi.com/2008/09/django-10-on-dreamhost-with-passenger-mod_rails/"> here </a></p> <p>I've set up the directories exactly as in that tutorial, and ensured that django is on my PYTHONPATH (I can run python and type 'import django' without any errors). However, when I try to access the url in a browser, I get the following message: "An error occurred importing your passenger_wsgi.py". Here is the contents of my passenger_wsgi.py file:</p> <pre><code>import sys, os sys.path.append("/path/to/web/root/") # I used the actual path in my file os.environ['DJANGO_SETTINGS_MODULE'] = ‘myproject.settings’ import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre> <p>However, when I put the following simple "Hello World" application in passenger_wsgi.py, it works as intended, suggesting Passenger is set up correctly:</p> <pre><code>def application(environ, start_response): write = start_response('200 OK', [('Content-type', 'text/plain')]) return ["Hello, world!"] </code></pre> <p>What am I missing? Seems like some config issue.</p>
8
2009-03-12T06:26:51Z
637,747
<p>Are those fancy quotation marks also in your code?</p> <pre><code>os.environ['DJANGO_SETTINGS_MODULE'] = ‘myproject.settings’ ^ ^ </code></pre> <p>If so, start by fixing them, as they cause a syntax error.</p>
24
2009-03-12T08:36:12Z
[ "python", "django", "passenger", "dreamhost" ]
Function Parser with RegEx in Python
637,773
<p>I have a source code in Fortran (almost irrelevant) and I want to parse the function names and arguments.</p> <p>eg using </p> <pre><code>(\w+)\([^\(\)]+\) </code></pre> <p>with</p> <pre><code>a(b(1 + 2 * 2), c(3,4)) </code></pre> <p>I get the following: (as expected)</p> <pre><code>b, 1 + 2 * 2 c, 3,4 </code></pre> <p>where I would need</p> <pre><code>a, b(1 + 2 * 2), c(3,4) b, 1 + 2 * 2 c, 3,4 </code></pre> <p>Any suggestions?</p> <p>Thanks for your time...</p>
2
2009-03-12T08:52:44Z
637,781
<p>I don't think this is a job for regular expressions... they can't really handle nested patterns.</p> <p>This is because regexes are compiled into FSMs (Finite State Machines). In order to parse arbitrarily nested expressions, you can't use a FSM, because you need infinitely many states to keep track of the arbitrary nesting. Also see this <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">SO thread</a>.</p>
2
2009-03-12T08:55:01Z
[ "python", "regex" ]
Function Parser with RegEx in Python
637,773
<p>I have a source code in Fortran (almost irrelevant) and I want to parse the function names and arguments.</p> <p>eg using </p> <pre><code>(\w+)\([^\(\)]+\) </code></pre> <p>with</p> <pre><code>a(b(1 + 2 * 2), c(3,4)) </code></pre> <p>I get the following: (as expected)</p> <pre><code>b, 1 + 2 * 2 c, 3,4 </code></pre> <p>where I would need</p> <pre><code>a, b(1 + 2 * 2), c(3,4) b, 1 + 2 * 2 c, 3,4 </code></pre> <p>Any suggestions?</p> <p>Thanks for your time...</p>
2
2009-03-12T08:52:44Z
637,807
<p>This is a nonlinear grammar -- you need to be able to recurse on a set of allowed rules. Look at <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> to do simple CFG (Context Free Grammar) parsing via readable specifications.</p> <p>It's been a while since I've written out CFGs, and I'm probably rusty, so I'll refer you to the <a href="http://www.python.org/doc/2.4.3/ref/grammar.txt" rel="nofollow">Python EBNF</a> to get an idea of how you can construct one for a subset of a language syntax.</p> <p><strong>Edit:</strong> If the example will always be simple, you can code a small state machine class/function that iterates over the tokenized input string, as <a href="http://stackoverflow.com/questions/637773/function-parser-with-regex-in-python/637823#637823">@Devin Jeanpierre</a> suggests.</p>
2
2009-03-12T09:07:20Z
[ "python", "regex" ]
Function Parser with RegEx in Python
637,773
<p>I have a source code in Fortran (almost irrelevant) and I want to parse the function names and arguments.</p> <p>eg using </p> <pre><code>(\w+)\([^\(\)]+\) </code></pre> <p>with</p> <pre><code>a(b(1 + 2 * 2), c(3,4)) </code></pre> <p>I get the following: (as expected)</p> <pre><code>b, 1 + 2 * 2 c, 3,4 </code></pre> <p>where I would need</p> <pre><code>a, b(1 + 2 * 2), c(3,4) b, 1 + 2 * 2 c, 3,4 </code></pre> <p>Any suggestions?</p> <p>Thanks for your time...</p>
2
2009-03-12T08:52:44Z
637,823
<p>It can be done with regular expressions-- use them to tokenize the string, and work with the tokens. i.e. see <code>re.Scanner</code>. Alternatively, just use pyparsing.</p>
2
2009-03-12T09:12:20Z
[ "python", "regex" ]
Function Parser with RegEx in Python
637,773
<p>I have a source code in Fortran (almost irrelevant) and I want to parse the function names and arguments.</p> <p>eg using </p> <pre><code>(\w+)\([^\(\)]+\) </code></pre> <p>with</p> <pre><code>a(b(1 + 2 * 2), c(3,4)) </code></pre> <p>I get the following: (as expected)</p> <pre><code>b, 1 + 2 * 2 c, 3,4 </code></pre> <p>where I would need</p> <pre><code>a, b(1 + 2 * 2), c(3,4) b, 1 + 2 * 2 c, 3,4 </code></pre> <p>Any suggestions?</p> <p>Thanks for your time...</p>
2
2009-03-12T08:52:44Z
637,974
<p>You can't do this with regular expression only. It's sort of recursive. You should match first the most external function and its arguments, print the name of the function, then do the same (match the function name, then its arguments) with all its arguments. Regex alone are not enough.</p>
1
2009-03-12T10:10:35Z
[ "python", "regex" ]
Function Parser with RegEx in Python
637,773
<p>I have a source code in Fortran (almost irrelevant) and I want to parse the function names and arguments.</p> <p>eg using </p> <pre><code>(\w+)\([^\(\)]+\) </code></pre> <p>with</p> <pre><code>a(b(1 + 2 * 2), c(3,4)) </code></pre> <p>I get the following: (as expected)</p> <pre><code>b, 1 + 2 * 2 c, 3,4 </code></pre> <p>where I would need</p> <pre><code>a, b(1 + 2 * 2), c(3,4) b, 1 + 2 * 2 c, 3,4 </code></pre> <p>Any suggestions?</p> <p>Thanks for your time...</p>
2
2009-03-12T08:52:44Z
641,844
<p>You can take a look at <a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY (Python Lex-Yacc)</a>, it's (in my opinion) very simple to use and well documented, and it comes with a <a href="http://www.dabeaz.com/ply/example.html" rel="nofollow">calculator example</a> which could be a good starting point. </p>
2
2009-03-13T08:42:19Z
[ "python", "regex" ]
Showing page count with ReportLab
637,800
<p><br /> I'm trying to add a simple "page x of y" to a report made with ReportLab.. I found <a href="http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html">this old post</a> about it, but maybe six years later something more straightforward has emerged? ^^;<br /> I found <a href="http://code.activestate.com/recipes/546511/">this recipe</a> too, but when I use it, the resulting PDF is missing the images..</p>
12
2009-03-12T09:05:34Z
638,218
<p>Just digging up some code for you, we use this:</p> <pre><code>SimpleDocTemplate(...).build(self.story, onFirstPage=self._on_page, onLaterPages=self._on_page) </code></pre> <p>Now <code>self._on_page</code> is a method that gets called for each page like:</p> <pre><code>def _on_page(self, canvas, doc): # ... do any additional page formatting here for each page print doc.page </code></pre>
1
2009-03-12T11:29:03Z
[ "python", "reportlab" ]
Showing page count with ReportLab
637,800
<p><br /> I'm trying to add a simple "page x of y" to a report made with ReportLab.. I found <a href="http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html">this old post</a> about it, but maybe six years later something more straightforward has emerged? ^^;<br /> I found <a href="http://code.activestate.com/recipes/546511/">this recipe</a> too, but when I use it, the resulting PDF is missing the images..</p>
12
2009-03-12T09:05:34Z
639,993
<p>I was able to implement the NumberedCanvas approach from ActiveState. It was very easy to do and did not change much of my existing code. All I had to do was add that NumberedCanvas class and add the canvasmaker attribute when building my doc. I also changed the measurements of where the "x of y" was displayed:</p> <pre><code>self.doc.build(pdf) </code></pre> <p>became </p> <pre><code>self.doc.build(pdf, canvasmaker=NumberedCanvas) </code></pre> <p><strong>doc</strong> is a BaseDocTemplate and <strong>pdf</strong> is my list of flowable elements.</p>
11
2009-03-12T18:54:30Z
[ "python", "reportlab" ]
Showing page count with ReportLab
637,800
<p><br /> I'm trying to add a simple "page x of y" to a report made with ReportLab.. I found <a href="http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html">this old post</a> about it, but maybe six years later something more straightforward has emerged? ^^;<br /> I found <a href="http://code.activestate.com/recipes/546511/">this recipe</a> too, but when I use it, the resulting PDF is missing the images..</p>
12
2009-03-12T09:05:34Z
7,758,773
<p>use doc.multiBuild</p> <p>and in the page header method (defined by "onLaterPages="):</p> <pre><code>global TOTALPAGES if doc.page &gt; TOTALPAGES: TOTALPAGES = doc.page else: canvas.drawString(270 * mm, 5 * mm, "Seite %d/%d" % (doc.page,TOTALPAGES)) </code></pre>
4
2011-10-13T18:32:55Z
[ "python", "reportlab" ]
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
<p>I have a list of tuples (always pairs) like this:</p> <pre><code>[(0, 1), (2, 3), (5, 7), (2, 1)] </code></pre> <p>I'd like to find the sum of the first items in each pair, i.e.:</p> <pre><code>0 + 2 + 5 + 2 </code></pre> <p>How can I do this in Python? At the moment I'm iterating through the list: </p> <pre><code>sum = 0 for pair in list_of_pairs: sum += pair[0] </code></pre> <p>I have a feeling there must be a more Pythonic way.</p>
17
2009-03-12T10:37:27Z
638,055
<p>A version compatible with Python 2.3 is</p> <pre><code>sum([pair[0] for pair in list_of_pairs]) </code></pre> <p>or in recent versions of Python, see <a href="https://stackoverflow.com/a/638069/56541">this answer</a> or <a href="https://stackoverflow.com/a/10255912/56541">this one</a>.</p>
44
2009-03-12T10:39:31Z
[ "python", "list", "tuples" ]
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
<p>I have a list of tuples (always pairs) like this:</p> <pre><code>[(0, 1), (2, 3), (5, 7), (2, 1)] </code></pre> <p>I'd like to find the sum of the first items in each pair, i.e.:</p> <pre><code>0 + 2 + 5 + 2 </code></pre> <p>How can I do this in Python? At the moment I'm iterating through the list: </p> <pre><code>sum = 0 for pair in list_of_pairs: sum += pair[0] </code></pre> <p>I have a feeling there must be a more Pythonic way.</p>
17
2009-03-12T10:37:27Z
638,069
<pre><code>sum(i for i, j in list_of_pairs) </code></pre> <p>will do too.</p>
30
2009-03-12T10:43:45Z
[ "python", "list", "tuples" ]
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
<p>I have a list of tuples (always pairs) like this:</p> <pre><code>[(0, 1), (2, 3), (5, 7), (2, 1)] </code></pre> <p>I'd like to find the sum of the first items in each pair, i.e.:</p> <pre><code>0 + 2 + 5 + 2 </code></pre> <p>How can I do this in Python? At the moment I'm iterating through the list: </p> <pre><code>sum = 0 for pair in list_of_pairs: sum += pair[0] </code></pre> <p>I have a feeling there must be a more Pythonic way.</p>
17
2009-03-12T10:37:27Z
638,098
<p>If you have a very large list or a generator that produces a large number of pairs you might want to use a generator based approach. For fun I use <code>itemgetter()</code> and <code>imap()</code>, too. A simple generator based approach might be enough, though.</p> <pre><code>import operator import itertools idx0 = operator.itemgetter(0) list_of_pairs = [(0, 1), (2, 3), (5, 7), (2, 1)] sum(itertools.imap(idx0, list_of_pairs) </code></pre> <p>Edit: itertools.imap() is available in Python 2.3. So you can use a generator based approach there, too.</p>
4
2009-03-12T10:52:48Z
[ "python", "list", "tuples" ]
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
<p>I have a list of tuples (always pairs) like this:</p> <pre><code>[(0, 1), (2, 3), (5, 7), (2, 1)] </code></pre> <p>I'd like to find the sum of the first items in each pair, i.e.:</p> <pre><code>0 + 2 + 5 + 2 </code></pre> <p>How can I do this in Python? At the moment I'm iterating through the list: </p> <pre><code>sum = 0 for pair in list_of_pairs: sum += pair[0] </code></pre> <p>I have a feeling there must be a more Pythonic way.</p>
17
2009-03-12T10:37:27Z
638,193
<p>Obscure (but fun) answer:</p> <pre><code>&gt;&gt;&gt; sum(zip(*list_of_pairs)[0]) 9 </code></pre> <p>Or when zip's are iterables only this should work:</p> <pre><code>&gt;&gt;&gt; sum(zip(*list_of_pairs).__next__()) 9 </code></pre>
4
2009-03-12T11:19:19Z
[ "python", "list", "tuples" ]
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
<p>I have a list of tuples (always pairs) like this:</p> <pre><code>[(0, 1), (2, 3), (5, 7), (2, 1)] </code></pre> <p>I'd like to find the sum of the first items in each pair, i.e.:</p> <pre><code>0 + 2 + 5 + 2 </code></pre> <p>How can I do this in Python? At the moment I'm iterating through the list: </p> <pre><code>sum = 0 for pair in list_of_pairs: sum += pair[0] </code></pre> <p>I have a feeling there must be a more Pythonic way.</p>
17
2009-03-12T10:37:27Z
10,255,912
<p>I recommend:</p> <pre><code>sum(i for i, _ in list_of_pairs) </code></pre> <p><em>Note</em>: </p> <p>Using the variable <code>_</code>(or <code>__</code> to avoid confliction with the alias of <code>gettext</code>) instead of <code>j</code> has at least two benefits:</p> <ol> <li><code>_</code>(which stands for placeholder) has better readability</li> <li><code>pylint</code> won't complain: "Unused variable 'j'"</li> </ol>
10
2012-04-21T03:24:43Z
[ "python", "list", "tuples" ]
Problem Inserting data into MS Access database using ADO via Python
638,095
<p>[Edit 2: More information and debugging in answer below...]</p> <p>I'm writing a python script to export MS Access databases into a series of text files to allow for more meaningful version control (I know - why Access? Why aren't I using existing solutions? Let's just say the restrictions aren't of a technical nature).</p> <p>I've successfully exported the full contents and structure of the database using ADO and ADOX via the comtypes library, but I'm getting a problem re-importing the data.</p> <p>I'm exporting the contents of each table into a text file with a list on each line, like so:</p> <pre><code>[-9, u'No reply'] [1, u'My home is as clean and comfortable as I want'] [2, u'My home could be more clean or comfortable than it is'] [3, u'My home is not at all clean or comfortable'] </code></pre> <p>And the following function to import the said file:</p> <pre><code>import os import sys import datetime import comtypes.client as client from ADOconsts import * from access_consts import * class Db: def create_table_contents(self, verbosity = 0): conn = client.CreateObject("ADODB.Connection") rs = client.CreateObject("ADODB.Recordset") conn.ConnectionString = self.new_con_string conn.Open() for fname in os.listdir(self.file_path): if fname.startswith("Table_"): tname = fname[6:-4] if verbosity &gt; 0: print "Filling table %s." % tname conn.Execute("DELETE * FROM [%s];" % tname) rs.Open("SELECT * FROM [%s];" % tname, conn, adOpenDynamic, adLockOptimistic) f = open(self.file_path + os.path.sep + fname, "r") data = f.readline() print repr(data) while data != '': data = eval(data.strip()) print data[0] print rs.Fields.Count rs.AddNew() for i in range(rs.Fields.Count): if verbosity &gt; 1: print "Into field %s (type %s) insert value %s." % ( rs.Fields[i].Name, str(rs.Fields[i].Type), data[i]) rs.Fields[i].Value = data[i] data = f.readline() print repr(data) rs.Update() rs.Close() conn.Close() </code></pre> <p>Everything works fine except that numerical values (double and int) are being inserted as zeros. Any ideas on whether the problem is with my code, eval, comtypes, or ADO?</p> <p>Edit: I've fixed the problem with inserting numbers - casting them as strings(!) seems to solve the problem for both double and integer fields.</p> <p>However, I now have a different issue that had previously been obscured by the above: the first field in every row is being set to 0 regardless of data type... Any ideas?</p>
6
2009-03-12T10:52:29Z
638,763
<p>Is <code>data[i]</code> being treated as a string? What happens if you specifically cast it as a int/double when you set <code>rs.Fields[i].Value</code>?</p> <p>Also, what happens when you print out the contents of <code>rs.Fields[i].Value</code> after it is set?</p>
0
2009-03-12T14:08:47Z
[ "python", "ms-access", "ado", "comtypes" ]
Problem Inserting data into MS Access database using ADO via Python
638,095
<p>[Edit 2: More information and debugging in answer below...]</p> <p>I'm writing a python script to export MS Access databases into a series of text files to allow for more meaningful version control (I know - why Access? Why aren't I using existing solutions? Let's just say the restrictions aren't of a technical nature).</p> <p>I've successfully exported the full contents and structure of the database using ADO and ADOX via the comtypes library, but I'm getting a problem re-importing the data.</p> <p>I'm exporting the contents of each table into a text file with a list on each line, like so:</p> <pre><code>[-9, u'No reply'] [1, u'My home is as clean and comfortable as I want'] [2, u'My home could be more clean or comfortable than it is'] [3, u'My home is not at all clean or comfortable'] </code></pre> <p>And the following function to import the said file:</p> <pre><code>import os import sys import datetime import comtypes.client as client from ADOconsts import * from access_consts import * class Db: def create_table_contents(self, verbosity = 0): conn = client.CreateObject("ADODB.Connection") rs = client.CreateObject("ADODB.Recordset") conn.ConnectionString = self.new_con_string conn.Open() for fname in os.listdir(self.file_path): if fname.startswith("Table_"): tname = fname[6:-4] if verbosity &gt; 0: print "Filling table %s." % tname conn.Execute("DELETE * FROM [%s];" % tname) rs.Open("SELECT * FROM [%s];" % tname, conn, adOpenDynamic, adLockOptimistic) f = open(self.file_path + os.path.sep + fname, "r") data = f.readline() print repr(data) while data != '': data = eval(data.strip()) print data[0] print rs.Fields.Count rs.AddNew() for i in range(rs.Fields.Count): if verbosity &gt; 1: print "Into field %s (type %s) insert value %s." % ( rs.Fields[i].Name, str(rs.Fields[i].Type), data[i]) rs.Fields[i].Value = data[i] data = f.readline() print repr(data) rs.Update() rs.Close() conn.Close() </code></pre> <p>Everything works fine except that numerical values (double and int) are being inserted as zeros. Any ideas on whether the problem is with my code, eval, comtypes, or ADO?</p> <p>Edit: I've fixed the problem with inserting numbers - casting them as strings(!) seems to solve the problem for both double and integer fields.</p> <p>However, I now have a different issue that had previously been obscured by the above: the first field in every row is being set to 0 regardless of data type... Any ideas?</p>
6
2009-03-12T10:52:29Z
639,031
<p>Not a complete answer yet, but it appears to be a problem during the update. I've added some further debugging code in the insertion process which generates the following (example of a single row being updated):</p> <pre><code>Inserted into field ID (type 3) insert value 1, field value now 1. Inserted into field TextField (type 202) insert value u'Blah', field value now Blah. Inserted into field Numbers (type 5) insert value 55.0, field value now 55.0. After update: [0, u'Blah', 55.0] </code></pre> <p>The last value in each "Inserted..." line is the result of calling rs.Fields[i].Value before calling rs.Update(). The "After..." line shows the results of calling rs.Fields[i].Value after calling rs.Update().</p> <p>What's even more annoying is that it's not reliably failing. Rerunning the exact same code on the same records a few minutes later generated:</p> <pre><code>Inserted into field ID (type 3) insert value 1, field value now 1. Inserted into field TextField (type 202) insert value u'Blah', field value now Blah. Inserted into field Numbers (type 5) insert value 55.0, field value now 55.0. After update: [1, u'Blah', 2.0] </code></pre> <p>As you can see, results are reliable until you commit them, then... not.</p>
0
2009-03-12T14:58:14Z
[ "python", "ms-access", "ado", "comtypes" ]
Problem Inserting data into MS Access database using ADO via Python
638,095
<p>[Edit 2: More information and debugging in answer below...]</p> <p>I'm writing a python script to export MS Access databases into a series of text files to allow for more meaningful version control (I know - why Access? Why aren't I using existing solutions? Let's just say the restrictions aren't of a technical nature).</p> <p>I've successfully exported the full contents and structure of the database using ADO and ADOX via the comtypes library, but I'm getting a problem re-importing the data.</p> <p>I'm exporting the contents of each table into a text file with a list on each line, like so:</p> <pre><code>[-9, u'No reply'] [1, u'My home is as clean and comfortable as I want'] [2, u'My home could be more clean or comfortable than it is'] [3, u'My home is not at all clean or comfortable'] </code></pre> <p>And the following function to import the said file:</p> <pre><code>import os import sys import datetime import comtypes.client as client from ADOconsts import * from access_consts import * class Db: def create_table_contents(self, verbosity = 0): conn = client.CreateObject("ADODB.Connection") rs = client.CreateObject("ADODB.Recordset") conn.ConnectionString = self.new_con_string conn.Open() for fname in os.listdir(self.file_path): if fname.startswith("Table_"): tname = fname[6:-4] if verbosity &gt; 0: print "Filling table %s." % tname conn.Execute("DELETE * FROM [%s];" % tname) rs.Open("SELECT * FROM [%s];" % tname, conn, adOpenDynamic, adLockOptimistic) f = open(self.file_path + os.path.sep + fname, "r") data = f.readline() print repr(data) while data != '': data = eval(data.strip()) print data[0] print rs.Fields.Count rs.AddNew() for i in range(rs.Fields.Count): if verbosity &gt; 1: print "Into field %s (type %s) insert value %s." % ( rs.Fields[i].Name, str(rs.Fields[i].Type), data[i]) rs.Fields[i].Value = data[i] data = f.readline() print repr(data) rs.Update() rs.Close() conn.Close() </code></pre> <p>Everything works fine except that numerical values (double and int) are being inserted as zeros. Any ideas on whether the problem is with my code, eval, comtypes, or ADO?</p> <p>Edit: I've fixed the problem with inserting numbers - casting them as strings(!) seems to solve the problem for both double and integer fields.</p> <p>However, I now have a different issue that had previously been obscured by the above: the first field in every row is being set to 0 regardless of data type... Any ideas?</p>
6
2009-03-12T10:52:29Z
639,223
<p>And found an answer.</p> <pre><code> rs = client.CreateObject("ADODB.Recordset") </code></pre> <p>Needs to be:</p> <pre><code> rs = client.CreateObject("ADODB.Recordset", dynamic=True) </code></pre> <p>Now I just need to look into why. Just hope this question saves someone else a few hours...</p>
3
2009-03-12T15:39:32Z
[ "python", "ms-access", "ado", "comtypes" ]
Ruby on Rails versus Python
638,150
<p>I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic.</p> <p>But when I start googling for web development I start inclining towards Ruby on Rails my question is why is the web world obsessed with ruby on rails and active records so much?</p> <p>There seem to be so many screencasts to learn Ruby on Rails and plethora of good books too why is Python not able to pull the crowd when it comes to creating screencasts or ORM's like active record.</p>
13
2009-03-12T11:06:40Z
638,160
<p>Ruby and Python are languages.</p> <p>Rails is a framework.</p> <p>So it is not really sensible to compare Ruby on Rails vs Python.</p> <p>There are Python Frameworks out there you should take a look at for a more direct comparison - <a href="http://wiki.python.org/moin/WebFrameworks">http://wiki.python.org/moin/WebFrameworks</a> (e.g. I know <a href="http://www.djangoproject.com/">Django</a> gets a lot of love, but there are others)</p> <p>Edit: I've just had a google, there seem to be loads of <a href="http://www.google.co.uk/search?rlz=1C1GGLS%5FenGB291GB304&amp;aq=f&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=django%2Bscreencast">Django Screencasts</a>.</p>
25
2009-03-12T11:09:40Z
[ "python", "ruby" ]
Ruby on Rails versus Python
638,150
<p>I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic.</p> <p>But when I start googling for web development I start inclining towards Ruby on Rails my question is why is the web world obsessed with ruby on rails and active records so much?</p> <p>There seem to be so many screencasts to learn Ruby on Rails and plethora of good books too why is Python not able to pull the crowd when it comes to creating screencasts or ORM's like active record.</p>
13
2009-03-12T11:06:40Z
638,800
<p>If you want Python screencasts, see ShowMeDo.com. I'm a co-founder, it is 3.5 yrs old and has over 400 Python screencasts (most are free) along with 600+ other free open-source topics: <a href="http://showmedo.com/videos/python">http://showmedo.com/videos/python</a></p> <p>In the Python section (linked) you'll see videos for Django, the entire TurboGears v1 DVD (provided freely courtesy Kevin Dangoor, the project founder), Python CGI (old-skool), web-scraping and plenty more.</p> <p>About 1/10th of the content is subscriber-only, the other 90% is created by 100 open-src authors with 100,000 users/month.</p> <p>Note that both Kyran and myself (co-founders) are A.I./math researchers in the UK with strong academic connections. Many of the Python videos have some links with starting out in data processing, I'll be creating new series over the coming months focused on math/stats/graphing/science purely for Python to accompany those that are already present.</p> <p>HTH, Ian.</p>
9
2009-03-12T14:16:09Z
[ "python", "ruby" ]
Ruby on Rails versus Python
638,150
<p>I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic.</p> <p>But when I start googling for web development I start inclining towards Ruby on Rails my question is why is the web world obsessed with ruby on rails and active records so much?</p> <p>There seem to be so many screencasts to learn Ruby on Rails and plethora of good books too why is Python not able to pull the crowd when it comes to creating screencasts or ORM's like active record.</p>
13
2009-03-12T11:06:40Z
639,045
<p>Ruby and Python have more similarities than differences; the same is true for Rails and Django, which are the leading web frameworks in the respective languages.</p> <p>Both languages and both frameworks are likely to be rewarding to work with - in personal, "fun" terms at least - I don't know what the job markets are like in the specific areas.</p> <p>There are some similar questions in StackOverflow: you could do worse than clicking around the "Related" list in the right-hand sidebar to get more feel.</p> <p>Best thing is to get and try both: pick a small project and build it both ways. Decide which you like better and go for it!</p>
3
2009-03-12T15:03:33Z
[ "python", "ruby" ]
Ruby on Rails versus Python
638,150
<p>I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic.</p> <p>But when I start googling for web development I start inclining towards Ruby on Rails my question is why is the web world obsessed with ruby on rails and active records so much?</p> <p>There seem to be so many screencasts to learn Ruby on Rails and plethora of good books too why is Python not able to pull the crowd when it comes to creating screencasts or ORM's like active record.</p>
13
2009-03-12T11:06:40Z
639,650
<p>Ruby gets more attention than Python simply because Ruby has one clear favourite when it comes to web apps while Python has traditionally had a very splintered approach (Zope, Plone, Django, Pylons, Turbogears). The critical mass of having almost all developers using one system as opposed to a variety of individual ones does a lot for improving documentation, finding and removing bugs, building hype and buzz, and so on.</p> <p>In actual language terms the two are very similar in all but syntax, and Python is more popular generally. Python's perhaps been hindered by being popular in its own right before web frameworks became a big deal, making it harder for the community to agree to concentrate on any single approach.</p>
15
2009-03-12T17:28:55Z
[ "python", "ruby" ]
Python - How to calculate equal parts of two dictionaries?
638,360
<p>I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists: </p> <pre><code>d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']} </code></pre> <p>I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:</p> <pre><code>d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']} </code></pre> <p>Can anyone help me with this?</p> <p>My fault I forgot to be more specific. I'm looking for a solution in Python.</p>
4
2009-03-12T12:15:14Z
638,392
<p>in pseudocode:</p> <pre><code>Dictionary d3 = new Dictionary() for (i = 0 to min(d1.size(), d2.size())) { element shared = getSharedElements(d1[i], d2[i]); d3.store(i, shared); } function getsharedElements(array e1, array e2) { element e3 = new element(); for (int i = 0 to e1.length) { if (e2.contains(e1[i])) { e3.add[e1[i]]; } } return e3; } </code></pre>
-1
2009-03-12T12:26:47Z
[ "python", "list", "dictionary", "merge" ]
Python - How to calculate equal parts of two dictionaries?
638,360
<p>I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists: </p> <pre><code>d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']} </code></pre> <p>I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:</p> <pre><code>d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']} </code></pre> <p>Can anyone help me with this?</p> <p>My fault I forgot to be more specific. I'm looking for a solution in Python.</p>
4
2009-03-12T12:15:14Z
638,409
<p>Assuming this is Python, you want:</p> <pre><code>dict((x, set(y) &amp; set(d1.get(x, ()))) for (x, y) in d2.iteritems()) </code></pre> <p>to generate the resulting dictionary "d3".</p> <h3>Python 3.0+ version</h3> <pre><code>&gt;&gt;&gt; d3 = {k: list(set(d1.get(k,[])).intersection(v)) for k, v in d2.items()} {0: ['11', '25', '38'], 1: ['38'], 2: ['11', '18'], 3: ['11', '25']} </code></pre> <p>The above version (as well as Python 2.x version) allows empty intersections therefore additional filtering is required in general case:</p> <pre><code>&gt;&gt;&gt; d3 = {k: v for k, v in d3.items() if v} </code></pre> <p>Combining the above in one pass:</p> <pre><code>d3 = {} for k, v in d2.items(): # find common elements for d1 &amp; d2 v3 = set(d1.get(k,[])).intersection(v) if v3: # whether there are common elements d3[k] = list(v3) </code></pre> <p><hr /></p> <p>[Edit: I made this post community wiki so that people can improve it if desired. I concede it might be a little hard to read if you're not used to reading this sort of thing in Python.]</p>
7
2009-03-12T12:30:54Z
[ "python", "list", "dictionary", "merge" ]
Python - How to calculate equal parts of two dictionaries?
638,360
<p>I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists: </p> <pre><code>d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']} </code></pre> <p>I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:</p> <pre><code>d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']} </code></pre> <p>Can anyone help me with this?</p> <p>My fault I forgot to be more specific. I'm looking for a solution in Python.</p>
4
2009-03-12T12:15:14Z
638,439
<p>The problem boils down to determining the common elements between the two entries. (To obtain the result for all entries, just enclose the code in a loop over all of them.) Furthermore, it looks like each entry is a set (i.e. it has not duplicate elements). Therefore, all you need to do is find the set intersection between these elements. Many languages offer a method or function for doing this; for instance in C++ use the set container and the set_intersection function. This is a lot more efficient than comparing each element in one set against the other, as others have proposed.</p>
1
2009-03-12T12:39:48Z
[ "python", "list", "dictionary", "merge" ]
Python - How to calculate equal parts of two dictionaries?
638,360
<p>I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists: </p> <pre><code>d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']} </code></pre> <p>I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:</p> <pre><code>d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']} </code></pre> <p>Can anyone help me with this?</p> <p>My fault I forgot to be more specific. I'm looking for a solution in Python.</p>
4
2009-03-12T12:15:14Z
638,762
<p>If we can assume d1 and d2 have the same keys:</p> <pre><code>d3 = {} for k in d1.keys(): intersection = set(d1[k]) &amp; set(d2[k]) d3[k] = [x for x in intersection] </code></pre> <p>Otherwise, if we can't assume that, then it is a little messier:</p> <pre><code>d3 = {} for k in set(d1.keys() + d2.keys()): intersection = set(d1.get(k, [])) &amp; set(d2.get(k, [])) d3[k] = [x for x in intersection] </code></pre> <p><strong>Edit:</strong> New version taking the comments into account. This one only checks for keys that d1 and d2 have in common, which is what the poster seems to be asking.</p> <pre><code>d3 = {} for k in set(d1.keys()) &amp; set(d2.keys()): intersection = set(d1[k]) &amp; set(d2[k]) d3[k] = list(intersection) </code></pre>
1
2009-03-12T14:08:18Z
[ "python", "list", "dictionary", "merge" ]
Python - How to calculate equal parts of two dictionaries?
638,360
<p>I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists: </p> <pre><code>d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '43'], 1:['05', '08', '09','13','15','20','32','36','38', '40','41'], 2:['02', '08', '11', '13', '18', '20', '22','33','36','39'], 3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']} </code></pre> <p>I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:</p> <pre><code>d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']} </code></pre> <p>Can anyone help me with this?</p> <p>My fault I forgot to be more specific. I'm looking for a solution in Python.</p>
4
2009-03-12T12:15:14Z
641,134
<p>Offering a more readable solution:</p> <pre><code>d3= {} for common_key in set(d1) &amp; set(d2): common_values= set(d1[common_key]) &amp; set(d2[common_key]) d3[common_key]= list(common_values) </code></pre> <h3>EDIT after suggestion:</h3> <p>If you want only keys having at least one common value item:</p> <pre><code>d3= {} for common_key in set(d1) &amp; set(d2): common_values= set(d1[common_key]) &amp; set(d2[common_key]) if common_values: d3[common_key]= list(common_values) </code></pre> <p>You could keep the d1 and d2 values as sets instead of lists, if order and duplicates are not important.</p>
4
2009-03-13T01:15:00Z
[ "python", "list", "dictionary", "merge" ]
In stackless Python, can you send a channel over a channel?
638,464
<p>I do not have <em>stackless</em> currently running, so I can not try this myself.</p> <pre><code>import stackless ch1 = stackless.channel() ch2 = stackless.channel() ch1.send(ch2) ch3 = ch1.receive() </code></pre> <p>Are <em>ch2</em> and <em>ch3</em> then the same channel? Say:</p> <pre><code>text = "Hallo" ch2.send(text) assert text == ch3.receive() </code></pre> <p>This feature reminded me of a <a href="https://www.youtube.com/watch?v=hB05UFqOtFA" rel="nofollow">talk about Newsqueak</a> that Robert Pike (of <a href="http://en.wikipedia.org/wiki/Plan_9_from_Bell_Labs" rel="nofollow">Plan9</a> fame) gave at Google. In Newsqueak you could send channels over channels.</p>
4
2009-03-12T12:46:57Z
638,843
<p>Yes. Just tested.</p> <pre><code>&gt;&gt;&gt; import stackless &gt;&gt;&gt; ch1 = stackless.channel() &gt;&gt;&gt; def a(): ... ch2 = stackless.channel() ... ch1.send(ch2) ... ch2.send("Hello") ... &gt;&gt;&gt; def b(): ... ch3 = ch1.receive() ... print ch3.receive() ... &gt;&gt;&gt; stackless.tasklet(a)() &lt;stackless.tasklet object at 0x01C6FCB0&gt; &gt;&gt;&gt; stackless.tasklet(b)() &lt;stackless.tasklet object at 0x01C6FAB0&gt; &gt;&gt;&gt; stackless.run() Hello </code></pre>
4
2009-03-12T14:26:27Z
[ "python", "stackless", "python-stackless" ]
In stackless Python, can you send a channel over a channel?
638,464
<p>I do not have <em>stackless</em> currently running, so I can not try this myself.</p> <pre><code>import stackless ch1 = stackless.channel() ch2 = stackless.channel() ch1.send(ch2) ch3 = ch1.receive() </code></pre> <p>Are <em>ch2</em> and <em>ch3</em> then the same channel? Say:</p> <pre><code>text = "Hallo" ch2.send(text) assert text == ch3.receive() </code></pre> <p>This feature reminded me of a <a href="https://www.youtube.com/watch?v=hB05UFqOtFA" rel="nofollow">talk about Newsqueak</a> that Robert Pike (of <a href="http://en.wikipedia.org/wiki/Plan_9_from_Bell_Labs" rel="nofollow">Plan9</a> fame) gave at Google. In Newsqueak you could send channels over channels.</p>
4
2009-03-12T12:46:57Z
639,563
<p>Channels send normal Python references so the data you send (channel, string, whatever) is exactly what is received.</p> <p>One example of sending a channel over a channel is when you use a tasklet as a service, that is, a tasklet listens on a channel for requests, does work, and returns the result. The request needs to include the data for the work and the return channel for the result, so that the result goes to the requestor.</p> <p>Here's an extreme example I developed for my <a href="http://dalkescientific.com/StacklessPyCon2007-Dalke.pdf" rel="nofollow">Stackless talk at PyCon</a> a few years ago. This creates a new tasklet for each function call so I can use a recursive implementation of factorial which doesn't need to worry about Python's stack limit. I allocate a tasklet for each call and it gets the return channel for the result. </p> <pre><code>import stackless def call_wrapper(f, args, kwargs, result_ch): result_ch.send(f(*args, **kwargs)) # ... should also catch and forward exceptions ... def call(f, *args, **kwargs): result_ch = stackless.channel() stackless.tasklet(call_wrapper)(f, args, kwargs, result_ch) return result_ch.receive() def factorial(n): if n &lt;= 1: return 1 return n * call(factorial, n-1) print "5! =", factorial(5) print "1000! / 998! =", factorial(1000)/factorial(998) </code></pre> <p>The output is:</p> <pre><code>5! = 120 1000! / 998! = 999000 </code></pre> <p>I have a few other examples of sending channels over channels in my presentation. It's a common thing in Stackless.</p>
3
2009-03-12T17:05:14Z
[ "python", "stackless", "python-stackless" ]
Paging depending on grouping of items in Django
638,647
<p>For a website implemented in Django/Python we have the following requirement:</p> <p>On a view page there are 15 messages per web paging shown. When there are more two or more messages from the same source, that follow each other on the view, they should be grouped together. </p> <p>Maybe not clear, but with the following exemple it might be:</p> <p>An example is (with 5 messages on a page this time):</p> <pre><code> Message1 Source1 Message2 Source2 Message3 Source2 Message4 Source1 Message5 Source3 ... </code></pre> <p>This should be shown as:</p> <pre><code>Message1 Source1 Message2 Source2 (click here to 1 more message from Source2) Message4 Source1 Message5 Source3 Message6 Source2 </code></pre> <p>So on each page a fixed number of items is shown on page, where some have been regrouped.</p> <p>We are wondering how we can create a Django or MySQL query to query this data in a optimal and in an easy way. Note that paging is used and that the messages are sorted by time.</p> <p>PS: I don't think there is a simple solution for this due to the nature of SQL, but sometimes complex problems can be easily solved</p>
5
2009-03-12T13:36:19Z
638,752
<p>I have a simple, though not perfect, template-only solution for this. In the template you can regroup the records using the <code>regroup</code> template tag. After regrouping you can hide successive records from the same source:</p> <pre><code>{% regroup records by source as grouped_records %} {% for group in grouped_records %} {% for item in group.list %} &lt;li{% if not forloop.first %} style="display:none"{% endif %}&gt; {{ item.message }} {{ iterm.source }} {% if forloop.first %} {% ifnotequal group.list|length 1 %} &lt;a href="#" onclick="..."&gt;Show more from the same source...&lt;/a&gt; {% endifnotequal %} {% endif %} &lt;/li&gt; {% endfor %} {% endfor %} </code></pre> <p>This would be perfect if it wasn't for one thing: Pagination. If you mean to display 15 items per page, and on one page the first five are fromone source, next five from another, and the last five yet another, there would be only three visible items on the page.</p>
1
2009-03-12T14:05:47Z
[ "python", "sql", "mysql", "django", "django-models" ]
Paging depending on grouping of items in Django
638,647
<p>For a website implemented in Django/Python we have the following requirement:</p> <p>On a view page there are 15 messages per web paging shown. When there are more two or more messages from the same source, that follow each other on the view, they should be grouped together. </p> <p>Maybe not clear, but with the following exemple it might be:</p> <p>An example is (with 5 messages on a page this time):</p> <pre><code> Message1 Source1 Message2 Source2 Message3 Source2 Message4 Source1 Message5 Source3 ... </code></pre> <p>This should be shown as:</p> <pre><code>Message1 Source1 Message2 Source2 (click here to 1 more message from Source2) Message4 Source1 Message5 Source3 Message6 Source2 </code></pre> <p>So on each page a fixed number of items is shown on page, where some have been regrouped.</p> <p>We are wondering how we can create a Django or MySQL query to query this data in a optimal and in an easy way. Note that paging is used and that the messages are sorted by time.</p> <p>PS: I don't think there is a simple solution for this due to the nature of SQL, but sometimes complex problems can be easily solved</p>
5
2009-03-12T13:36:19Z
638,816
<p>I don't see any great way to do what you're trying to do directly. If you're willing to accept a little de-normalization, I would recommend a pre-save signal to mark messages as being at the head.</p> <pre><code>#In your model head = models.BooleanField(default=True) #As a signal plugin: def check_head(sender, **kwargs): message = kwargs['instance'] if hasattr(message,'no_check_head') and message.no_check_head: return previous_message = Message.objects.filter(time__lt=message.time).order_by('-time')[0] if message.source == previous_message.source: message.head = False next_message = Message.objects.filter(time__gt=message.time).order_by('time')[0] if message.source == next_message.source: next_message.head = False next_message.no_check_head next_message.save() </code></pre> <p>Then your query becomes magically simple:</p> <pre><code>messages = Message.objects.filter(head=True).order_by('time')[0:15] </code></pre> <p>To be quite honest...the signal listener would have to be a bit more complicated than the one I wrote. There are a host of lost synchronization/lost update problems inherent in my approach, the solutions to which will vary depending on your server (if it is single-processed, multi-threaded, then a python <code>Lock</code> object should get you by, but if it is multi-processed, then you will really need to implement locking based on files or database objects). Also, you will certainly also have to write a corresponding delete signal listener.</p> <p>Obviously this solution involves adding some database hits, but they are on edit as opposed to on view, which might be worthwhile for you. Otherwise, perhaps consider a cruder approach: grab 30 stories, loop through the in the view, knock out the ones you won't display, and if you have 15 left, display them, otherwise repeat. Definitely an awful worst-case scenario, but perhaps not terrible average case?</p> <p>If you had a server configuration that used a single process that's multi-threaded, a Lock or RLock should do the trick. Here's a possible implementation with non-reentrant lock:</p> <pre><code>import thread lock = thread.allocate_lock() def check_head(sender, **kwargs): # This check must come outside the safe zone # Otherwise, your code will screech to a hault message = kwargs['instance'] if hasattr(message,'no_check_head') and message.no_check_head: return # define safe zone lock.acquire() # see code above .... lock.release() </code></pre> <p>Again, a corresponding delete signal is critical as well.</p> <p>EDIT: Many or most server configurations (such as Apache) will prefork, meaning there are several processes going on. The above code will be useless in that case. See <a href="http://stackoverflow.com/questions/698950/what-is-the-simplest-way-to-lock-an-object-in-django/699222#699222">this page</a> for ideas on how to get started synchronizing with forked processes.</p>
3
2009-03-12T14:20:47Z
[ "python", "sql", "mysql", "django", "django-models" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
638,917
<p>I would:</p> <ul> <li>lowercase the string</li> <li>replace all <code>[^a-z]</code> with <code>""</code></li> </ul> <p>Like that:</p> <pre><code>def strip_string_to_lowercase(): nonascii = re.compile('[^a-z]') return lambda s: nonascii.sub('', s.lower().strip()) </code></pre> <p>EDIT: It turns out that the original version (below) is really slow, though some performance can be gained by converting it into a closure (above).</p> <pre><code>def strip_string_to_lowercase(s): return re.sub('[^a-z]', '', s.lower().strip()) </code></pre> <p><hr /></p> <p>My performance measurements with 100,000 iterations against the string </p> <pre><code>"A235th@#$&amp;( er Ra{}|?&gt;ndom" </code></pre> <p>revealed that:</p> <ul> <li><code>f_re_0 took 2672.000 ms</code> (this is the original version of this answer)</li> <li><code>f_re_1 took 2109.000 ms</code> (this is the closure version shown above)</li> <li><code>f_re_2 took 2031.000 ms</code> (the closure version, without the redundant <code>strip()</code>)</li> <li><code>f_fl_1 took 1953.000 ms</code> (<a href="http://stackoverflow.com/questions/638893/what-is-the-most-efficient-way-in-python-to-convert-a-string-to-all-lowercase-str/638946#638946">unwind's <code>filter</code>/<code>lambda</code> version</a>)</li> <li><code>f_fl_2 took 1485.000 ms</code> (<a href="http://stackoverflow.com/questions/638893/what-is-the-most-efficient-way-in-python-to-convert-a-string-to-all-lowercase-str/639272#639272">Coady's <code>filter</code> version</a>)</li> <li><code>f_jn_1 took 1860.000 ms</code> (<a href="http://stackoverflow.com/questions/638893/what-is-the-most-efficient-way-in-python-to-convert-a-string-to-all-lowercase-str/638920#638920">Dana's <code>join</code> version</a>)</li> </ul> <p>For the sake of the test, I did not <code>print</code> the results.</p>
8
2009-03-12T14:39:28Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
638,920
<p>Not especially runtime efficient, but certainly nicer on poor, tired coder eyes:</p> <pre><code>def strip_string_and_lowercase(s): return ''.join(c for c in s.lower() if c in string.ascii_lowercase) </code></pre>
10
2009-03-12T14:39:48Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
638,937
<pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; a = "O235th@#$&amp;( er Ra{}|?&amp;lt;ndom" &gt;&gt;&gt; ''.join(i for i in a.lower() if i in string.ascii_lowercase) 'otheraltndom' </code></pre> <p>doing essentially the same as you.</p>
2
2009-03-12T14:42:47Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
638,944
<p>This is a typical application of list compehension:</p> <pre><code>import string s = "O235th@#$&amp;( er Ra{}|?&lt;ndom" print ''.join(c for c in s.lower() if c in string.ascii_lowercase) </code></pre> <p>It won't filter out "&lt;" (html entity), as in your example, but I assume that was accidental cut and past problem.</p>
2
2009-03-12T14:43:57Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
638,945
<p>Personally I would use a regular expression and then convert the final string to lower case. I have no idea how to write it in Python, but the basic idea is to:</p> <ol> <li>Remove characters in string that don't match case-insensitive regex "<code>\w</code>"</li> <li>Convert string to lower-case</li> </ol> <p>or vice versa.</p>
0
2009-03-12T14:44:04Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
638,946
<p>Similar to @Dana's, but I think this sounds like a filtering job, and that should be visible in the code. Also without the need to explicitly call <code>join()</code>:</p> <pre><code>def strip_string_to_lowercase(s): return filter(lambda x: x in string.ascii_lowercase, s.lower()) </code></pre>
4
2009-03-12T14:44:10Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
639,272
<pre><code>&gt;&gt;&gt; filter(str.isalpha, "This is a Test").lower() 'thisisatest' &gt;&gt;&gt; filter(str.isalpha, "A235th@#$&amp;( er Ra{}|?&gt;ndom").lower() 'atherrandom' </code></pre>
17
2009-03-12T15:55:32Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
639,325
<p>Another solution (not that pythonic, but very fast) is to use string.translate - though note that this will not work for unicode. It's also worth noting that you can speed up <a href="http://stackoverflow.com/questions/638893/what-is-the-most-efficient-way-in-python-to-convert-a-string-to-all-lowercase-str/638920#638920">Dana's code</a> by moving the characters into a set (which looks up by hash, rather than performing a linear search each time). Here are the timings I get for various of the solutions given:</p> <pre><code>import string, re, timeit # Precomputed values (for str_join_set and translate) letter_set = frozenset(string.ascii_lowercase + string.ascii_uppercase) tab = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase * 2) deletions = ''.join(ch for ch in map(chr,range(256)) if ch not in letter_set) s="A235th@#$&amp;( er Ra{}|?&gt;ndom" # From unwind's filter approach def test_filter(s): return filter(lambda x: x in string.ascii_lowercase, s.lower()) # using set instead (and contains) def test_filter_set(s): return filter(letter_set.__contains__, s).lower() # Tomalak's solution def test_regex(s): return re.sub('[^a-z]', '', s.lower()) # Dana's def test_str_join(s): return ''.join(c for c in s.lower() if c in string.ascii_lowercase) # Modified to use a set. def test_str_join_set(s): return ''.join(c for c in s.lower() if c in letter_set) # Translate approach. def test_translate(s): return string.translate(s, tab, deletions) for test in sorted(globals()): if test.startswith("test_"): assert globals()[test](s)=='atherrandom' print "%30s : %s" % (test, timeit.Timer("f(s)", "from __main__ import %s as f, s" % test).timeit(200000)) </code></pre> <p>This gives me:</p> <pre><code> test_filter : 2.57138351271 test_filter_set : 0.981806765698 test_regex : 3.10069885233 test_str_join : 2.87172979743 test_str_join_set : 2.43197956381 test_translate : 0.335367566218 </code></pre> <p>[Edit] Updated with filter solutions as well. (Note that using <code>set.__contains__</code> makes a big difference here, as it avoids making an extra function call for the lambda.</p>
22
2009-03-12T16:06:22Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
639,404
<p>I added the filter solutions to Brian's code:</p> <pre><code>import string, re, timeit # Precomputed values (for str_join_set and translate) letter_set = frozenset(string.ascii_lowercase + string.ascii_uppercase) tab = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase * 2) deletions = ''.join(ch for ch in map(chr,range(256)) if ch not in letter_set) s="A235th@#$&amp;( er Ra{}|?&gt;ndom" def test_original(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) def test_regex(s): return re.sub('[^a-z]', '', s.lower()) def test_regex_closure(s): nonascii = re.compile('[^a-z]') def replacer(s): return nonascii.sub('', s.lower().strip()) return replacer(s) def test_str_join(s): return ''.join(c for c in s.lower() if c in string.ascii_lowercase) def test_str_join_set(s): return ''.join(c for c in s.lower() if c in letter_set) def test_filter_set(s): return filter(letter_set.__contains__, s.lower()) def test_filter_isalpha(s): return filter(str.isalpha, s).lower() def test_filter_lambda(s): return filter(lambda x: x in string.ascii_lowercase, s.lower()) def test_translate(s): return string.translate(s, tab, deletions) for test in sorted(globals()): if test.startswith("test_"): print "%30s : %s" % (test, timeit.Timer("f(s)", "from __main__ import %s as f, s" % test).timeit(200000)) </code></pre> <p>This gives me:</p> <pre><code> test_filter_isalpha : 1.31981746283 test_filter_lambda : 2.23935583992 test_filter_set : 0.76511679557 test_original : 2.13079176264 test_regex : 2.44295629752 test_regex_closure : 2.65205913042 test_str_join : 2.25571266739 test_str_join_set : 1.75565888961 test_translate : 0.269259640541 </code></pre> <p>It appears that isalpha is using a similar algorithm, at least in terms of O(), to the set algorithm.</p> <p><hr /></p> <p><strong>Edit:</strong> Added the filter set, and renamed the filter functions to be a little more clear.</p>
2
2009-03-12T16:20:46Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
639,773
<h3>Python 2.x <code>translate</code> method</h3> <p>Convert to lowercase and filter non-ascii non-alpha characters:</p> <pre><code>from string import ascii_letters, ascii_lowercase, maketrans table = maketrans(ascii_letters, ascii_lowercase*2) deletechars = ''.join(set(maketrans('','')) - set(ascii_letters)) print "A235th@#$&amp;( er Ra{}|?&gt;ndom".translate(table, deletechars) # -&gt; 'atherrandom' </code></pre> <h3>Python 3 <code>translate</code> method</h3> <p>Filter non-ascii:</p> <pre><code>ascii_bytes = "A235th@#$&amp;(٠٫٢٥ er Ra{}|?&gt;ndom".encode('ascii', 'ignore') </code></pre> <p>Use <a href="http://docs.python.org/py3k/library/stdtypes.html#bytes.translate" rel="nofollow"><code>bytes.translate()</code></a> to convert to lowercase and delete non-alpha bytes:</p> <pre><code>from string import ascii_letters, ascii_lowercase alpha, lower = [s.encode('ascii') for s in [ascii_letters, ascii_lowercase]] table = bytes.maketrans(alpha, lower*2) # convert to lowercase deletebytes = bytes(set(range(256)) - set(alpha)) # delete nonalpha print(ascii_bytes.translate(table, deletebytes)) # -&gt; b'atherrandom' </code></pre>
5
2009-03-12T17:56:26Z
[ "python", "string" ]
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
<p>I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. </p> <p>For example:</p> <pre><code>"This is a Test" -&gt; "thisisatest" "A235th@#$&amp;( er Ra{}|?&gt;ndom" -&gt; "atherrandom" </code></pre> <p>I have a simple function to do this:</p> <pre><code>import string import sys def strip_string_to_lowercase(s): tmpStr = s.lower().strip() retStrList = [] for x in tmpStr: if x in string.ascii_lowercase: retStrList.append(x) return ''.join(retStrList) </code></pre> <p>But I cannot help thinking there is a more efficient, or more elegant, way.</p> <p>Thanks!</p> <p><hr /></p> <p><strong>Edit:</strong></p> <p>Thanks to all those that answered. I learned, and in some cases re-learned, a good deal of python.</p>
25
2009-03-12T14:35:42Z
7,861,632
<h3>Python 2.x:</h3> <pre><code>import string valid_chars= string.ascii_lowercase + string.ascii_uppercase def only_lower_ascii_alpha(text): return filter(valid_chars.__contains__, text).lower() </code></pre> <p>Works with either <code>str</code> or <code>unicode</code> arguments.</p> <pre><code>&gt;&gt;&gt; only_lower_ascii_alpha("Hello there 123456!") 'hellothere' &gt;&gt;&gt; only_lower_ascii_alpha(u"435 café") u'caf' </code></pre>
0
2011-10-22T18:15:51Z
[ "python", "string" ]
Unable search names which contain three 7s in random order by AWK/Python/Bash
639,078
<p>I need to find names which contain three number 7 in the random order.</p> <p><strong>My attempt</strong></p> <p>We need to find first names which do not contain seven</p> <pre><code>ls | grep [^7] </code></pre> <p>Then, we could remove these matches from the whole space</p> <pre><code>ls [remove] ls | grep [^7] </code></pre> <p>The problem in my pseudo-code starts to repeat itself quickly.</p> <p><strong>How can you find the names which contain three 7s in the random order by AWK/Python/Bash?</strong></p> <p><strong>[edit]</strong> The name can contain any number of letters and it contains words of three 7s. </p>
0
2009-03-12T15:11:45Z
639,096
<p>I don't understand the part about "random order". How do you differentiate between the "order" when it's the same token that repeats? Is "a7b7" different from "c7d7" in the order of the 7s?</p> <p>Anyway, this ought to work:</p> <pre><code> ls *7*7*7* </code></pre> <p>It just let's the shell solve the problem, but maybe I didn't understand properly.</p> <p>EDIT: The above is wrong, it includes cases with more than four 7s which is not wanted. Assuming this is bash, and extended globbing is enabled, this works:</p> <pre><code>ls *([^7])7*([^7])7*([^7])7*([^7]) </code></pre> <p>This reads as "zero or more characters which are not sevens, followed by a seven, followed by zero or more characters that are not sevens", and so on. It's important to understand that the asterisk is a <em>prefix</em> operator here, operating on the expression <code>([^7])</code> which means "any character except 7".</p>
7
2009-03-12T15:15:27Z
[ "python", "regex", "bash", "awk" ]
Unable search names which contain three 7s in random order by AWK/Python/Bash
639,078
<p>I need to find names which contain three number 7 in the random order.</p> <p><strong>My attempt</strong></p> <p>We need to find first names which do not contain seven</p> <pre><code>ls | grep [^7] </code></pre> <p>Then, we could remove these matches from the whole space</p> <pre><code>ls [remove] ls | grep [^7] </code></pre> <p>The problem in my pseudo-code starts to repeat itself quickly.</p> <p><strong>How can you find the names which contain three 7s in the random order by AWK/Python/Bash?</strong></p> <p><strong>[edit]</strong> The name can contain any number of letters and it contains words of three 7s. </p>
0
2009-03-12T15:11:45Z
639,212
<p>I'm guessing you want to find files that contain exactly three 7's, but no more. Using gnu grep with the extends regexp switch (<code>-E</code>):</p> <pre><code> ls | grep -E '^([^7]*7){3}[^7]*$' </code></pre> <p>Should do the trick.</p> <p>Basically that matches 3 occurrences of "not 7 followed by a 7", then a bunch of "not 7" across the whole string (the ^ and $ at the beginning and end of the pattern respectively).</p>
5
2009-03-12T15:35:32Z
[ "python", "regex", "bash", "awk" ]
Unable search names which contain three 7s in random order by AWK/Python/Bash
639,078
<p>I need to find names which contain three number 7 in the random order.</p> <p><strong>My attempt</strong></p> <p>We need to find first names which do not contain seven</p> <pre><code>ls | grep [^7] </code></pre> <p>Then, we could remove these matches from the whole space</p> <pre><code>ls [remove] ls | grep [^7] </code></pre> <p>The problem in my pseudo-code starts to repeat itself quickly.</p> <p><strong>How can you find the names which contain three 7s in the random order by AWK/Python/Bash?</strong></p> <p><strong>[edit]</strong> The name can contain any number of letters and it contains words of three 7s. </p>
0
2009-03-12T15:11:45Z
639,446
<p>Something like this:</p> <pre><code>printf '%s\n' *|awk -F7 NF==4 </code></pre>
2
2009-03-12T16:31:29Z
[ "python", "regex", "bash", "awk" ]
Unable search names which contain three 7s in random order by AWK/Python/Bash
639,078
<p>I need to find names which contain three number 7 in the random order.</p> <p><strong>My attempt</strong></p> <p>We need to find first names which do not contain seven</p> <pre><code>ls | grep [^7] </code></pre> <p>Then, we could remove these matches from the whole space</p> <pre><code>ls [remove] ls | grep [^7] </code></pre> <p>The problem in my pseudo-code starts to repeat itself quickly.</p> <p><strong>How can you find the names which contain three 7s in the random order by AWK/Python/Bash?</strong></p> <p><strong>[edit]</strong> The name can contain any number of letters and it contains words of three 7s. </p>
0
2009-03-12T15:11:45Z
639,473
<p>Or instead of doing it in a single grep, use one grep to find files with 3-or-more 7s and another to filter out 4-or-more 7s.</p> <pre><code>ls -f | egrep '7.*7.*7' | grep -v '7.*7.*7.*7' </code></pre> <p>You could move some of the work into the shell glob with the shorter</p> <pre><code>ls -f *7*7*7* | grep -v '7.*7.*7.*7' </code></pre> <p>though if there are a large number of files which match that pattern then the latter won't work because of built-in limits to the glob size.</p> <p>The '-f' in the 'ls' is to prevent 'ls' from sorting the results. If there is a huge number of files in the directory then the sort time can be quite noticeable.</p> <p>This two-step filter process is, I think, more understandable than using the [^7] patterns.</p> <p>Also, here's the solution as a Python script, since you asked for that as an option.</p> <pre><code>import os for filename in os.listdir("."): if filename.count("7") == 4: print filename </code></pre> <p>This will handle a few cases that the shell commands won't, like (evil) filenames which contain a newline character. Though even here the output in that case would likely still be wrong, or at least unprepared for by downstream programs.</p>
1
2009-03-12T16:39:21Z
[ "python", "regex", "bash", "awk" ]
Unable search names which contain three 7s in random order by AWK/Python/Bash
639,078
<p>I need to find names which contain three number 7 in the random order.</p> <p><strong>My attempt</strong></p> <p>We need to find first names which do not contain seven</p> <pre><code>ls | grep [^7] </code></pre> <p>Then, we could remove these matches from the whole space</p> <pre><code>ls [remove] ls | grep [^7] </code></pre> <p>The problem in my pseudo-code starts to repeat itself quickly.</p> <p><strong>How can you find the names which contain three 7s in the random order by AWK/Python/Bash?</strong></p> <p><strong>[edit]</strong> The name can contain any number of letters and it contains words of three 7s. </p>
0
2009-03-12T15:11:45Z
639,517
<p>A Perl solution:</p> <pre><code>$ ls | perl -ne 'print if (tr/7/7/ == 3)' 3777 4777 5777 6777 7077 7177 7277 7377 7477 7577 7677 ... </code></pre> <p>(I happen to have a directory with 4-digit numbers. 1777 and 2777 don't exist. :-)</p>
2
2009-03-12T16:53:43Z
[ "python", "regex", "bash", "awk" ]
python: determine if a class is nested
639,162
<p>Suppose you have a python method that gets a type as parameter; is it possible to determine if the given type is a nested class?<br /> E.g. in this example:</p> <pre><code>def show_type_info(t): print t.__name__ # print outer class name (if any) ... class SomeClass: pass class OuterClass: class InnerClass: pass show_type_info(SomeClass) show_type_info(OuterClass.InnerClass) </code></pre> <p>I would like the call to <code>show_type_info(OuterClass.InnerClass)</code> to show also that InnerClass is defined inside OuterClass.</p>
5
2009-03-12T15:26:53Z
639,209
<p>AFAIK, given a class and no other information, you can't tell whether or not it's a nested class. However, <a href="http://mail.python.org/pipermail/python-list/2005-July/330874.html">see here</a> for how you might use a decorator to determine this.</p> <p>The problem is that a nested class is simply a normal class that's an attribute of its outer class. Other solutions that you might expect to work probably won't -- <code>inspect.getmro</code>, for example, only gives you base classes, not outer classes. </p> <p>Also, nested classes are rarely needed. I would strongly reconsider whether that's a good approach in each particular case where you feel tempted to use one.</p>
12
2009-03-12T15:34:51Z
[ "python", "introspection", "inner-classes" ]
python: determine if a class is nested
639,162
<p>Suppose you have a python method that gets a type as parameter; is it possible to determine if the given type is a nested class?<br /> E.g. in this example:</p> <pre><code>def show_type_info(t): print t.__name__ # print outer class name (if any) ... class SomeClass: pass class OuterClass: class InnerClass: pass show_type_info(SomeClass) show_type_info(OuterClass.InnerClass) </code></pre> <p>I would like the call to <code>show_type_info(OuterClass.InnerClass)</code> to show also that InnerClass is defined inside OuterClass.</p>
5
2009-03-12T15:26:53Z
639,412
<p>An inner class offers no particular special features in Python. It's only a property of the class object, no different from an integer or string property. Your OuterClass/InnerClass example can be rewritten exactly as:</p> <pre><code>class OuterClass(): pass class InnerClass(): pass OuterClass.InnerClass= InnerClass </code></pre> <p>InnerClass can't know whether it was declared inside another class, because that's just a plain variable binding. The magic that makes bound methods know about their owner ‘self’ doesn't apply here.</p> <p>The innerclass decorator magic in the link John posted is an interesting approach but I would not use it as-is. It doesn't cache the classes it creates for each outer object, so you get a new InnerClass every time you call outerinstance.InnerClass:</p> <pre><code>&gt;&gt;&gt; o= OuterClass() &gt;&gt;&gt; i= o.InnerClass() &gt;&gt;&gt; isinstance(i, o.InnerClass) False # huh? &gt;&gt;&gt; o.InnerClass is o.InnerClass False # oh, whoops... </code></pre> <p>Also the way it tries to replicate the Java behaviour of making outer class variables available on the inner class with getattr/setattr is very dodgy, and unnecessary really (since the more Pythonic way would be to call i.__outer__.attr explicitly).</p>
5
2009-03-12T16:23:04Z
[ "python", "introspection", "inner-classes" ]