title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
11,768,336
<p>As other answers said, using the string method count() is probably the simplest, but if you're doing this frequently, check out collections.Counter:</p> <pre><code>from collections import Counter str = "Mary had a little lamb" counter = Counter(str) print counter['a'] </code></pre>
51
2012-08-01T22:12:08Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
27,321,071
<p>Regular expressions are very useful if you want case-insensitivity (and of course all the power of regex).</p> <pre><code>my_string = "Mary had a little lamb" # simplest solution, using count, is case-sensitive my_string.count("m") # yields 1 import re # case-sensitive with regex len(re.findall("m", my_string)) # three ways to get case insensitivity - all yield 2 len(re.findall("(?i)m", my_string)) len(re.findall("m|M", my_string)) len(re.findall(re.compile("m",re.IGNORECASE), my_string)) </code></pre> <p>Be aware that the regex version takes on the order of ten times as long to run, which will likely be an issue only if my_string is tremendously long, or the code is inside a deep loop.</p>
6
2014-12-05T17:04:28Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
27,889,928
<h1>"Without using count to find you want character in string" method.</h1> <pre><code>import re def count(s, ch): pass def main(): s = raw_input ("Enter strings what you like, for example, 'welcome': ") ch = raw_input ("Enter you want count characters, but best result to find one character: " ) print ( len (re.findall ( ch, s ) ) ) main() </code></pre>
3
2015-01-11T17:24:27Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
33,324,089
<pre><code>a = 'have a nice day' symbol = 'abcdefghijklmnopqrstuvwxyz' for key in symbol: print key, a.count(key) </code></pre>
2
2015-10-24T22:36:58Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
33,723,716
<pre><code>spam = 'have a nice day' var = 'd' def count(spam, var): found = 0 for key in spam: if key == var: found += 1 return found count(spam, var) print 'count %s is: %s ' %(var, count(spam, var)) </code></pre>
0
2015-11-15T19:05:09Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
35,586,210
<p>No more than this IMHO - you can add the upper or lower methods</p> <pre><code>def count_letter_in_str(string,letter): return string.count(letter) </code></pre>
0
2016-02-23T19:16:31Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
36,346,557
<pre><code>str = "count a character occurance" List = list(str) print (List) Uniq = set(List) print (Uniq) for key in Uniq: print (key, str.count(key)) </code></pre>
0
2016-04-01T01:29:24Z
[ "python", "string", "count" ]
Count occurrence of a character in a string
1,155,617
<p>What's the simplest way to count the number of occurrences of a character in a string?</p> <p>e.g. count the number of times <code>'a'</code> appears in <code>'Mary had a little lamb'</code></p>
433
2009-07-20T20:00:36Z
39,813,320
<p><code>str.count(a)</code> is the best solution to count a single character in a string. But if you need to count more characters than one you would have to read the string as many times as characters you want to count.</p> <p>A better approach for this job would be:</p> <pre><code>from collections import defaultdict string = 'Mary had a little lamb' chars = defaultdict(int) for char in string: chars[char] += 1 </code></pre> <p>So you'll have a dict that returns the number of ocurrences of every letter in the string and <code>0</code> if it isn't present.</p> <pre><code>&gt;&gt;&gt;chars['a'] 4 &gt;&gt;&gt;chars['x'] 0 </code></pre>
0
2016-10-02T02:33:10Z
[ "python", "string", "count" ]
Python: Importing pydoc and then using it natively?
1,155,853
<p>I know how to use pydoc from the command line. However, because of complicated environmental setup, it would be preferable to run it within a python script as a native API call. That is, my python runner looks a bit like this:</p> <p>import pydoc pydoc.generate_html_docs_for(someFile)</p> <p>However, it's not clear to me from the pydoc documentation which function calls I need to use to make this behavior work. Any ideas?</p>
2
2009-07-20T20:41:24Z
1,155,885
<p>Do you mean something like this?</p> <pre><code>&gt;&gt;&gt; import pydoc &gt;&gt;&gt; pydoc.writedoc('sys') wrote sys.html &gt;&gt;&gt; </code></pre>
4
2009-07-20T20:48:28Z
[ "python" ]
Latin-1 and the unicode factory in Python
1,155,903
<p>I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the <code>unicode</code> factory, and I don't know how to make Python use a codec other than <code>ascii</code>.</p> <p>The script is a simple tool to return lookup data from a database without having to execute the SQL directly in a SQL editor. I use the <a href="http://code.google.com/p/prettytable/" rel="nofollow">PrettyTable</a> 0.5 library to display the results.</p> <p>The core of the script is this bit of code. The tuples I get from the cursor contain integer and string data, and no Unicode data. (I'd use <code>adodbapi</code> instead of <code>pyodbc</code>, which would get me Unicode, but <code>adodbapi</code> gives me other problems.)</p> <pre><code>x = pyodbc.connect(cxnstring) r = x.cursor() r.execute(sql) t = PrettyTable(columns) for rec in r: t.add_row(rec) r.close() x.close() t.set_field_align("ID", 'r') t.set_field_align("Name", 'l') print t </code></pre> <p>But the <code>Name</code> column can contain characters that fall outside the ASCII range. I'll sometimes get an error message like this, in line 222 of <code>prettytable.pyc</code>, when it gets to the <code>t.add_row</code> call:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 12: ordinal not in range(128) </code></pre> <p>This is line 222 in <code>prettytable.py</code>. It uses <code>unicode</code>, which is the source of my problems, and not just in this script, but in other Python scripts that I have written.</p> <pre><code>for i in range(0,len(row)): if len(unicode(row[i])) &gt; self.widths[i]: # This is line 222 self.widths[i] = len(unicode(row[i])) </code></pre> <p>Please tell me what I'm doing wrong here. How can I make <code>unicode</code> work without hacking <code>prettytable.py</code> or any of the other libraries that I use? Is there even a way to do this?</p> <p>EDIT: The error occurs not at the <code>print</code> statement, but at the <code>t.add_row</code> call.</p> <p>EDIT: With Bastien Léonard's help, I came up with the following solution. It's not a panacea, but it works.</p> <pre><code>x = pyodbc.connect(cxnstring) r = x.cursor() r.execute(sql) t = PrettyTable(columns) for rec in r: urec = [s.decode('latin-1') if isinstance(s, str) else s for s in rec] t.add_row(urec) r.close() x.close() t.set_field_align("ID", 'r') t.set_field_align("Name", 'l') print t.get_string().encode('latin-1') </code></pre> <p>I ended up having to decode on the way in and encode on the way out. All of this makes me hopeful that everybody ports their libraries to Python 3.x sooner than later!</p>
4
2009-07-20T20:52:20Z
1,155,923
<p>Add this at the beginning of the module:</p> <pre><code># coding: latin1 </code></pre> <p>Or decode the string to Unicode yourself.</p> <p>[Edit]</p> <p>It's been a while since I played with Unicode, but hopefully this example will show how to convert from Latin1 to Unicode:</p> <pre><code>&gt;&gt;&gt; s = u'ééé'.encode('latin1') # a string you may get from the database &gt;&gt;&gt; s.decode('latin1') u'\xe9\xe9\xe9' </code></pre> <p>[Edit]</p> <p>Documentation:<br /> <a href="http://docs.python.org/howto/unicode.html" rel="nofollow">http://docs.python.org/howto/unicode.html</a><br /> <a href="http://docs.python.org/library/codecs.html" rel="nofollow">http://docs.python.org/library/codecs.html</a></p>
4
2009-07-20T20:59:20Z
[ "python", "unicode" ]
Latin-1 and the unicode factory in Python
1,155,903
<p>I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the <code>unicode</code> factory, and I don't know how to make Python use a codec other than <code>ascii</code>.</p> <p>The script is a simple tool to return lookup data from a database without having to execute the SQL directly in a SQL editor. I use the <a href="http://code.google.com/p/prettytable/" rel="nofollow">PrettyTable</a> 0.5 library to display the results.</p> <p>The core of the script is this bit of code. The tuples I get from the cursor contain integer and string data, and no Unicode data. (I'd use <code>adodbapi</code> instead of <code>pyodbc</code>, which would get me Unicode, but <code>adodbapi</code> gives me other problems.)</p> <pre><code>x = pyodbc.connect(cxnstring) r = x.cursor() r.execute(sql) t = PrettyTable(columns) for rec in r: t.add_row(rec) r.close() x.close() t.set_field_align("ID", 'r') t.set_field_align("Name", 'l') print t </code></pre> <p>But the <code>Name</code> column can contain characters that fall outside the ASCII range. I'll sometimes get an error message like this, in line 222 of <code>prettytable.pyc</code>, when it gets to the <code>t.add_row</code> call:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 12: ordinal not in range(128) </code></pre> <p>This is line 222 in <code>prettytable.py</code>. It uses <code>unicode</code>, which is the source of my problems, and not just in this script, but in other Python scripts that I have written.</p> <pre><code>for i in range(0,len(row)): if len(unicode(row[i])) &gt; self.widths[i]: # This is line 222 self.widths[i] = len(unicode(row[i])) </code></pre> <p>Please tell me what I'm doing wrong here. How can I make <code>unicode</code> work without hacking <code>prettytable.py</code> or any of the other libraries that I use? Is there even a way to do this?</p> <p>EDIT: The error occurs not at the <code>print</code> statement, but at the <code>t.add_row</code> call.</p> <p>EDIT: With Bastien Léonard's help, I came up with the following solution. It's not a panacea, but it works.</p> <pre><code>x = pyodbc.connect(cxnstring) r = x.cursor() r.execute(sql) t = PrettyTable(columns) for rec in r: urec = [s.decode('latin-1') if isinstance(s, str) else s for s in rec] t.add_row(urec) r.close() x.close() t.set_field_align("ID", 'r') t.set_field_align("Name", 'l') print t.get_string().encode('latin-1') </code></pre> <p>I ended up having to decode on the way in and encode on the way out. All of this makes me hopeful that everybody ports their libraries to Python 3.x sooner than later!</p>
4
2009-07-20T20:52:20Z
1,155,968
<p>Maybe try to decode the latin1-encoded strings into unicode?</p> <pre><code>t.add_row((value.decode('latin1') for value in rec)) </code></pre>
1
2009-07-20T21:09:36Z
[ "python", "unicode" ]
Latin-1 and the unicode factory in Python
1,155,903
<p>I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the <code>unicode</code> factory, and I don't know how to make Python use a codec other than <code>ascii</code>.</p> <p>The script is a simple tool to return lookup data from a database without having to execute the SQL directly in a SQL editor. I use the <a href="http://code.google.com/p/prettytable/" rel="nofollow">PrettyTable</a> 0.5 library to display the results.</p> <p>The core of the script is this bit of code. The tuples I get from the cursor contain integer and string data, and no Unicode data. (I'd use <code>adodbapi</code> instead of <code>pyodbc</code>, which would get me Unicode, but <code>adodbapi</code> gives me other problems.)</p> <pre><code>x = pyodbc.connect(cxnstring) r = x.cursor() r.execute(sql) t = PrettyTable(columns) for rec in r: t.add_row(rec) r.close() x.close() t.set_field_align("ID", 'r') t.set_field_align("Name", 'l') print t </code></pre> <p>But the <code>Name</code> column can contain characters that fall outside the ASCII range. I'll sometimes get an error message like this, in line 222 of <code>prettytable.pyc</code>, when it gets to the <code>t.add_row</code> call:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 12: ordinal not in range(128) </code></pre> <p>This is line 222 in <code>prettytable.py</code>. It uses <code>unicode</code>, which is the source of my problems, and not just in this script, but in other Python scripts that I have written.</p> <pre><code>for i in range(0,len(row)): if len(unicode(row[i])) &gt; self.widths[i]: # This is line 222 self.widths[i] = len(unicode(row[i])) </code></pre> <p>Please tell me what I'm doing wrong here. How can I make <code>unicode</code> work without hacking <code>prettytable.py</code> or any of the other libraries that I use? Is there even a way to do this?</p> <p>EDIT: The error occurs not at the <code>print</code> statement, but at the <code>t.add_row</code> call.</p> <p>EDIT: With Bastien Léonard's help, I came up with the following solution. It's not a panacea, but it works.</p> <pre><code>x = pyodbc.connect(cxnstring) r = x.cursor() r.execute(sql) t = PrettyTable(columns) for rec in r: urec = [s.decode('latin-1') if isinstance(s, str) else s for s in rec] t.add_row(urec) r.close() x.close() t.set_field_align("ID", 'r') t.set_field_align("Name", 'l') print t.get_string().encode('latin-1') </code></pre> <p>I ended up having to decode on the way in and encode on the way out. All of this makes me hopeful that everybody ports their libraries to Python 3.x sooner than later!</p>
4
2009-07-20T20:52:20Z
1,156,570
<p>After a quick peek at the source for PrettyTable, it appears that it works on unicode objects internally (see <code>_stringify_row</code>, <code>add_row</code> and <code>add_column</code>, for example). Since it doesn't know what encoding your input strings are using, it uses the default encoding, <a href="http://diveintopython.net/xml_processing/unicode.html" rel="nofollow">usually ascii</a>.</p> <p>Now ascii is a <em>subset</em> of latin-1, which means if you're converting from ascii to latin-1, you shouldn't have any problems. The reverse however, isn't true; not all latin-1 characters map to ascii characters. To demonstrate this:</p> <pre><code>&gt;&gt;&gt; s = u'\xed\x31\x32\x33' &gt;&gt;&gt; print s # FAILS: Python calls "s.decode('ascii')", but ascii codec can't decode '\xed' &gt;&gt;&gt; print s.decode('ascii') # FAILS: Same as above &gt;&gt;&gt; print s.decode('latin-1') í123 </code></pre> <p>Explicitly converting the strings to unicode (like you eventually did) fixes things, and makes more sense, IMO -- you're more likely to know what charset your data is using, than the author of PrettyTable :). <s>BTW, you can omit the check for strings in your list comprehension by replacing <code>s.decode('latin-1')</code> with <code>unicode(s, 'latin-1')</code> since all objects can be coerced to strings</s>.</p> <p>One last thing: don't forget to check the character set of your database and tables -- you don't want to assume 'latin-1' in code, when the data is actually being stored as something else ('utf-8'?) in the database. In MySQL, you can use the <code>SHOW CREATE TABLE &lt;table_name&gt;</code> command to find out what character set a table is using, and <code>SHOW CREATE DATABASE &lt;db_name&gt;</code> to do the same for a database.</p>
0
2009-07-20T23:45:32Z
[ "python", "unicode" ]
Print current call stack from a method in Python code
1,156,023
<p>In Python, how can I print the current call stack from within a method (for debugging purposes).</p>
141
2009-07-20T21:24:05Z
1,156,048
<p>Here's an example of getting the stack via the <a href="http://docs.python.org/library/traceback.html">traceback</a> module, and printing it:</p> <pre><code>import traceback def f(): g() def g(): for line in traceback.format_stack(): print(line.strip()) f() # Prints: # File "so-stack.py", line 10, in &lt;module&gt; # f() # File "so-stack.py", line 4, in f # g() # File "so-stack.py", line 7, in g # for line in traceback.format_stack(): </code></pre> <p>If you really only want to print the stack to stderr, you can use:</p> <pre><code>traceback.print_stack() </code></pre> <p>Or to print to stdout (useful if want to keep redirected output together), use:</p> <pre><code>traceback.print_stack(file=sys.stdout) </code></pre> <p>But getting it via <code>traceback.format_stack()</code> lets you do whatever you like with it.</p>
161
2009-07-20T21:27:43Z
[ "python", "debugging", "stack-trace" ]
Print current call stack from a method in Python code
1,156,023
<p>In Python, how can I print the current call stack from within a method (for debugging purposes).</p>
141
2009-07-20T21:24:05Z
1,156,055
<pre><code>import traceback traceback.print_stack() </code></pre>
46
2009-07-20T21:28:14Z
[ "python", "debugging", "stack-trace" ]
Print current call stack from a method in Python code
1,156,023
<p>In Python, how can I print the current call stack from within a method (for debugging purposes).</p>
141
2009-07-20T21:24:05Z
16,200,714
<p><code>inspect.stack()</code> returns the current stack rather than the exception traceback:</p> <pre><code>import inspect print inspect.stack() </code></pre> <p>See <a href="https://gist.github.com/FredLoney/5454553">https://gist.github.com/FredLoney/5454553</a> for a log_stack utility function.</p>
11
2013-04-24T19:37:20Z
[ "python", "debugging", "stack-trace" ]
Composable Regexp in Python
1,156,030
<p>Often, I would like to build up complex regexps from simpler ones. The only way I'm currently aware of of doing this is through string operations, e.g.:</p> <pre><code>Year = r'[12]\d{3}' Month = r'Jan|Feb|Mar' Day = r'\d{2}' HourMins = r'\d{2}:\d{2}' Date = r'%s %s, %s, %s' % (Month, Day, Year, HourMins) DateR = re.compile(Date) </code></pre> <p>Is anybody aware of a different method or a more systematic approach (maybe a module) in Python to have composable regexps? I'd rather compile each regexp individually (e.g. for using individual compile options), but then there doesn't seem to be a way of composing them anymore!?</p>
5
2009-07-20T21:24:58Z
1,156,208
<p>You can use Python's formatting syntax for this:</p> <pre><code>types = { "year": r'[12]\d{3}', "month": r'(Jan|Feb|Mar)', "day": r'\d{2}', "hourmins": r'\d{2}:\d{2}', } import re Date = r'%(month)s %(day)s, %(year)s, %(hourmins)s' % types DateR = re.compile(Date) </code></pre> <p>(Note the added grouping around Jan|Feb|Mar.)</p>
4
2009-07-20T22:02:17Z
[ "python", "regex" ]
Composable Regexp in Python
1,156,030
<p>Often, I would like to build up complex regexps from simpler ones. The only way I'm currently aware of of doing this is through string operations, e.g.:</p> <pre><code>Year = r'[12]\d{3}' Month = r'Jan|Feb|Mar' Day = r'\d{2}' HourMins = r'\d{2}:\d{2}' Date = r'%s %s, %s, %s' % (Month, Day, Year, HourMins) DateR = re.compile(Date) </code></pre> <p>Is anybody aware of a different method or a more systematic approach (maybe a module) in Python to have composable regexps? I'd rather compile each regexp individually (e.g. for using individual compile options), but then there doesn't seem to be a way of composing them anymore!?</p>
5
2009-07-20T21:24:58Z
1,156,507
<p>You could use Ping's <a href="http://zesty.ca/python/rxb.py" rel="nofollow">rxb</a>:</p> <pre><code>year = member("1", "2") + digit*3 month = either("Jan", "Feb", "Mar") day = digit*2 hour_mins = digit*2 + ":" + digit*2 date = month + " " + day + ", " + year + ", " + hour_mins </code></pre> <p>You can then match on the resulting date directly, or use</p> <pre><code>DateR = date.compile() </code></pre>
1
2009-07-20T23:25:04Z
[ "python", "regex" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,156,114
<p>You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to <code>map()</code> or similar, but it's always going to be there.</p> <p>My preference would always be to have clean and simple code, unless performance is a major factor.</p> <p>Here's perhaps a more Pythonic version of your code:</p> <pre><code>data = [['a','b'], ['a','c'], ['b','d']] search = 'c' for sublist in data: if sublist[1] == search: print "Found it!", sublist break # Prints: Found it! ['a', 'c'] </code></pre> <p>It breaks out of the loop as soon as it finds a match.</p> <p>(You have a typo, by the way, in <code>['b''d']</code>.)</p>
20
2009-07-20T21:39:56Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,156,128
<pre><code>&gt;&gt;&gt; my_list =[ ['a', 'b'], ['a', 'c'], ['b', 'd'] ] &gt;&gt;&gt; 'd' in (x[1] for x in my_list) True </code></pre> <p>Editing to add:</p> <p>Both David's answer using <strong>any</strong> and mine using <strong>in</strong> will end when they find a match since we're using generator expressions. Here is a test using an infinite generator to show that:</p> <pre><code>def mygen(): ''' Infinite generator ''' while True: yield 'xxx' # Just to include a non-match in the generator yield 'd' print 'd' in (x for x in mygen()) # True print any('d' == x for x in mygen()) # True # print 'q' in (x for x in mygen()) # Never ends if uncommented # print any('q' == x for x in mygen()) # Never ends if uncommented </code></pre> <p>I just like simply using <strong>in</strong> instead of both <strong>==</strong> and <strong>any</strong>.</p>
7
2009-07-20T21:43:54Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,156,143
<p>Nothing against RichieHindle's and Anon's answers, but here's how I'd write it:</p> <pre><code>data = [['a','b'], ['a','c'], ['b','d']] search = 'c' any(e[1] == search for e in data) </code></pre> <p>Like RichieHindle said, there is a hidden loop in the implementation of <code>any</code> (although I think it breaks out of the loop as soon as it finds a match).</p>
34
2009-07-20T21:47:27Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,156,145
<pre><code>&gt;&gt;&gt; the_list =[ ['a','b'], ['a','c'], ['b''d'] ] &gt;&gt;&gt; any('c' == x[1] for x in the_list) True </code></pre>
13
2009-07-20T21:47:41Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,156,582
<pre><code>&gt;&gt;&gt; the_list =[ ['a','b'], ['a','c'], ['b','d'] ] &gt;&gt;&gt; "b" in zip(*the_list)[1] True </code></pre> <p><code>zip()</code> takes a bunch of lists and groups elements together by index, effectively transposing the list-of-lists matrix. The asterisk takes the contents of <code>the_list</code> and sends it to <code>zip</code> as arguments, so you're effectively passing the three lists separately, which is what <code>zip</code> wants. All that remains is to check if <code>"b"</code> (or whatever) is in the list made up of elements with the index you're interested in.</p>
1
2009-07-20T23:48:55Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,156,628
<p>Markus has one way to avoid using the word <code>for</code> -- here's another, which should have much better performance for long <code>the_list</code>s...:</p> <pre><code>import itertools found = any(itertools.ifilter(lambda x:x[1]=='b', the_list) </code></pre>
4
2009-07-21T00:01:46Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,157,153
<p>Nothing wrong with using a gen exp, but if the goal is to inline the loop...</p> <pre><code>&gt;&gt;&gt; import itertools, operator &gt;&gt;&gt; 'b' in itertools.imap(operator.itemgetter(1), the_list) True </code></pre> <p>Should be the fastest as well.</p>
2
2009-07-21T03:25:56Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
1,158,136
<p>the above all look good</p> <p>but do you want to keep the result?</p> <p>if so...</p> <p>you can use the following</p> <pre><code>result = [element for element in data if element[1] == search] </code></pre> <p>then a simple</p> <pre><code>len(result) </code></pre> <p>lets you know if anything was found (and now you can do stuff with the results)</p> <p><strong>of course</strong> this does not handle elements which are length less than one (which you should be checking unless you know they always are greater than length 1, and in that case should you be using a tuple? (tuples are immutable))</p> <p>if you know all items are a set length you can also do:</p> <pre><code>any(second == search for _, second in data) </code></pre> <p>or for len(data[0]) == 4:</p> <pre><code>any(second == search for _, second, _, _ in data) </code></pre> <p>...and I would recommend using</p> <pre><code>for element in data: ... </code></pre> <p>instead of</p> <pre><code>for i in range(len(data)): ... </code></pre> <p>(for future uses, <em>unless you want to save or use 'i'</em>, and just so you know the '0' is not required, you only need use the full syntax if you are starting at a non zero value)</p>
9
2009-07-21T09:25:00Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
10,907,447
<p>This Python demonstrates locating an element in your list of lists:</p> <pre><code>def finder(element): L=[ ['a', 'b'], ['a', 'c'], ['b', 'd'] ] for x in L: if element in x: print "find in ", x else: print "not find" finder('d') </code></pre>
0
2012-06-06T02:27:37Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
13,588,121
<p>What about:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] search = 'b' filter(lambda x:x[1]==search,list) </code></pre> <p>This will return each list in the list of lists with the second element being equal to search. </p>
4
2012-11-27T16:00:37Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
16,757,108
<p>Given below is a simple way to find exactly where in the list the item is.</p> <pre><code>for i in range (0,len(a)): sublist=a[i] for i in range(0,len(sublist)): if search==sublist[i]: print "found in sublist "+ "a"+str(i) </code></pre>
-1
2013-05-26T07:33:42Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
18,412,156
<p>k old post but no one use list expression to answer :P</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] Search = 'c' # return if it find in either item 0 or item 1 print [x for x,y in list if x == Search or y == Search] # return if it find in item 1 print [x for x,y in list if y == Search] </code></pre>
2
2013-08-23T21:28:45Z
[ "python", "list" ]
Python search in lists of lists
1,156,087
<p>I have a list of two-item lists and need to search for things in it.</p> <p>If the list is:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] </code></pre> <p>I can search for a pair easily by doing</p> <pre><code>['a','b'] in list </code></pre> <p>Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:</p> <pre><code>for i in range (0, len(list)): if list[i][1]==search: found=1 </code></pre> <p>But is there a (better) way without the <code>for</code> loop? I don't need to know <code>i</code> or keep the loop going after it's found.</p>
28
2009-07-20T21:34:26Z
30,449,870
<p>I think using nested list comprehensions is the most elegant way to solve this, because the intermediate result is the position where the element is. An implementation would be:</p> <pre><code>list =[ ['a','b'], ['a','c'], ['b','d'] ] search = 'c' any([ (list.index(x),x.index(y)) for x in list for y in x if y == search ] ) </code></pre>
0
2015-05-26T05:06:08Z
[ "python", "list" ]
Algorithm for BFS traveral of an acylic directed graph
1,156,175
<p>I'm looking for an elegant Python program that does a BFS traveral of a DAG:</p> <p>Node A is connected to B (<code>A-&gt;B</code>) if A "depends on" B (think of python package Foo "depending upon" Bar: Foo->Bar). </p> <p>In a graph of about 7000 such nodes, I want to sort all nodes such that for all possible <code>(i, j)</code> where <code>1&gt;=i&lt;j&lt;=7000</code> .. <code>depends(Ni, Nj)</code> is False. depends(A, B) = True if and only if <code>A-&gt;B</code> or A "depends on" B .. and <code>Nx</code> is the node occuring in <code>x</code>th position in the sorted list.</p> <p>Note: A node can have multiple parents. Eg: A->C and B->C. Therefore, according to the above sorting rule, A and B must come before C. </p>
1
2009-07-20T21:54:22Z
1,156,213
<p>If I am reading the question correctly, it looks like you want a <a href="http://en.wikipedia.org/wiki/Topological%5Fsorting" rel="nofollow">topological sort</a>. The most efficient algorithm (O(V+E)) for doing this was proposed by <a href="http://en.wikipedia.org/wiki/Robert%5FTarjan" rel="nofollow">Tarjan</a>, and a Python implementation can be found <a href="http://www.bitformation.com/art/python%5Ftoposort.html" rel="nofollow">here</a>.</p> <p>Off-topic, but it seems as though your package dependency analogy is reversed; I would think that "A depends on B" would imply "B->A", but of course this will not change the structure of the tree, merely reverse it.</p>
5
2009-07-20T22:03:17Z
[ "python", "algorithm", "graph", "dependencies", "traversal" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
1,156,490
<p>A "download" is simply an HTTP header change.</p> <p>See <a href="http://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment">http://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment</a> for how to respond with a download.</p> <p>You only need one URL definition for <code>"/download"</code>.</p> <p>The request's <code>GET</code> or <code>POST</code> dictionary will have the <code>"f=somefile.txt"</code> information.</p> <p>Your view function will simply merge the base path with the "<code>f</code>" value, open the file, create and return a response object. It should be less than 12 lines of code.</p>
62
2009-07-20T23:20:15Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
1,158,244
<p>Django recommend that you use another server to serve static media (another server running on the same machine is fine.) They recommend the use of such servers as <a href="http://www.lighttpd.net/" rel="nofollow">lighttp</a>. </p> <p>This is very simple to set up. However. if 'somefile.txt' is generated on request (content is dynamic) then you may want django to serve it.</p> <p><a href="http://docs.djangoproject.com/en/dev/howto/static-files/" rel="nofollow">Django Docs - Static Files</a></p>
1
2009-07-21T09:49:56Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
1,158,750
<p>For the "best of both worlds" you could combine S.Lott's solution with the <a href="http://www.google.com.ng/search?q=mod_xsendfile&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a">xsendfile module</a>: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you've set up mod_xsendfile, integrating with your view takes a few lines of code:</p> <pre><code>from django.utils.encoding import smart_str response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7 response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(path_to_file) # It's usually a good idea to set the 'Content-Length' header too. # You can also set any other required headers: Cache-Control, etc. return response </code></pre> <p>Of course, this will only work if you have control over your server, or your hosting company has mod_xsendfile already set up.</p>
126
2009-07-21T11:57:59Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
4,565,501
<p>S.Lott has the "good"/simple solution, and elo80ka has the "best"/efficient solution. Here is a middle "better"/middle solution - no server setup, but more efficient for large files than the naive fix.</p> <p><a href="http://djangosnippets.org/snippets/365/">http://djangosnippets.org/snippets/365/</a></p> <p>Basically django still handles serving the file, but does not load the whole thing into memory at once. This allows your server to (slowly) server a big file without ramping up the memory usage.</p> <p>Again, S.Lott's X-SendFile is still better for larger files. But if you can't or don't want to bother with that, then this middle solution will gain you better efficiency without the hassle.</p>
24
2010-12-30T19:17:20Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
5,301,921
<p>It was mentioned above that the mod_xsendfile method does not allow for non-ASCII characters in filenames.</p> <p>For this reason, I have a patch available for mod_xsendfile that will allow any file to be sent, as long as the name is url encoded, and the additional header:</p> <pre><code>X-SendFile-Encoding: url </code></pre> <p>Is sent as well.</p> <p><a href="http://ben.timby.com/?p=149">http://ben.timby.com/?p=149</a></p>
11
2011-03-14T17:10:18Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
5,659,486
<p>Try: <a href="https://pypi.python.org/pypi/django-sendfile/" rel="nofollow">https://pypi.python.org/pypi/django-sendfile/</a></p> <p>"Abstraction to offload file uploads to web-server (e.g. Apache with mod_xsendfile) once Django has checked permissions etc."</p>
5
2011-04-14T06:37:37Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
8,846,697
<p>Another project to have a look at: <a href="http://readthedocs.org/docs/django-private-files/en/latest/usage.html" rel="nofollow">http://readthedocs.org/docs/django-private-files/en/latest/usage.html</a> Looks promissing, haven't tested it myself yet tho.</p> <p>Basically the project abstracts the mod_xsendfile configuration and allows you to do things like:</p> <pre><code>from django.db import models from django.contrib.auth.models import User from private_files import PrivateFileField def is_owner(request, instance): return (not request.user.is_anonymous()) and request.user.is_authenticated and instance.owner.pk = request.user.pk class FileSubmission(models.Model): description = models.CharField("description", max_length = 200) owner = models.ForeignKey(User) uploaded_file = PrivateFileField("file", upload_to = 'uploads', condition = is_owner) </code></pre>
0
2012-01-13T06:18:31Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
10,405,065
<p>I have faced the same problem more then once and so implemented using xsendfile module and auth view decorators the <a href="https://github.com/danielsokolowski/django-filelibrary" rel="nofollow">django-filelibrary</a>. Feel free to use it as inspiration for your own solution. </p> <p><a href="https://github.com/danielsokolowski/django-filelibrary" rel="nofollow">https://github.com/danielsokolowski/django-filelibrary</a></p>
0
2012-05-01T22:07:51Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
18,985,653
<p>Tried @Rocketmonkeys solution but downloaded files were being stored as *.bin and given random names. That's not fine of course. Adding another line from @elo80ka solved the problem.<br> Here is the code I'm using now:</p> <pre><code>filename = "/home/stackoverflow-addict/private-folder(not-porn)/image.jpg" wrapper = FileWrapper(file(filename)) response = HttpResponse(wrapper, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename) response['Content-Length'] = os.path.getsize(filename) return response </code></pre> <p>You can now store files in a private directory (not inside /media nor /public_html) and expose them via django to certain users or under certain circumstances.<br> Hope it helps. <br><br> <em>Thanks to @elo80ka, @S.Lott and @Rocketmonkeys for the answers, got the perfect solution combining all of them =)</em></p>
8
2013-09-24T15:22:06Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
20,609,767
<pre><code>def qrcodesave(request): import urllib2; url ="http://chart.apis.google.com/chart?cht=qr&amp;chs=300x300&amp;chl=s&amp;chld=H|0"; opener = urllib2.urlopen(url); content_type = "application/octet-stream" response = HttpResponse(opener.read(), content_type=content_type) response["Content-Disposition"]= "attachment; filename=aktel.png" return response </code></pre>
1
2013-12-16T11:26:06Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
21,210,929
<p>For a very simple <strong>but not efficient or scalable</strong> solution, you can just use the built in django <code>serve</code> view. This is excellent for quick prototypes or one-off work, but as has been mentioned throughout this question, you should use something like apache or nginx in production.</p> <pre><code>from django.views.static import serve filepath = '/some/path/to/local/file.txt' return serve(request, os.path.basename(filepath), os.path.dirname(filepath)) </code></pre>
14
2014-01-18T22:54:28Z
[ "python", "django", "download" ]
Having Django serve downloadable files
1,156,246
<p>I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.</p> <p>For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt</p> <p>And on the server, I know that all downloadable files reside in a folder "/home/user/files/".</p> <p>Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?</p>
155
2009-07-20T22:10:30Z
22,776,886
<p>Providing protected access to static html folder using <a href="https://github.com/johnsensible/django-sendfile" rel="nofollow">https://github.com/johnsensible/django-sendfile</a>: <a href="https://gist.github.com/iutinvg/9907731" rel="nofollow">https://gist.github.com/iutinvg/9907731</a></p>
0
2014-04-01T04:35:39Z
[ "python", "django", "download" ]
Import Dynamically Created Python Files
1,156,356
<p>I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way.</p> <p>Originally I was calling the <code>execFile(&lt;script_path&gt;)</code> function and then calling the function defined by executing the file. This has a side effect of always entering the if <code>__name__ == "__main__"</code> condition, which with my current setup I can't have happen. </p> <p>I can't change the generated files, because I've already created 100's of them and don't want to have to revise them all. I can only change the file that calls the generated files.</p> <p>Basically what I have now...</p> <pre><code>#&lt;c:\File.py&gt; def func(word): print word if __name__ == "__main__": print "must only be called from command line" #results in an error when called from CallingFunction.py input = sys.argv[1] #&lt;CallingFunction.py&gt; #results in Main Condition being called execFile("c:\\File.py") func("hello world") </code></pre>
2
2009-07-20T22:37:22Z
1,156,382
<p>Use</p> <pre><code>m = __import__("File") </code></pre> <p>This is essentially the same as doing</p> <pre><code>import File m = File </code></pre>
5
2009-07-20T22:43:55Z
[ "python", "import" ]
Import Dynamically Created Python Files
1,156,356
<p>I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way.</p> <p>Originally I was calling the <code>execFile(&lt;script_path&gt;)</code> function and then calling the function defined by executing the file. This has a side effect of always entering the if <code>__name__ == "__main__"</code> condition, which with my current setup I can't have happen. </p> <p>I can't change the generated files, because I've already created 100's of them and don't want to have to revise them all. I can only change the file that calls the generated files.</p> <p>Basically what I have now...</p> <pre><code>#&lt;c:\File.py&gt; def func(word): print word if __name__ == "__main__": print "must only be called from command line" #results in an error when called from CallingFunction.py input = sys.argv[1] #&lt;CallingFunction.py&gt; #results in Main Condition being called execFile("c:\\File.py") func("hello world") </code></pre>
2
2009-07-20T22:37:22Z
1,156,594
<p>If I understand correctly your remarks to man that the file isn't in <code>sys.path</code> and you'd rather keep it that way, this would still work:</p> <pre><code>import imp fileobj, pathname, description = imp.find_module('thefile', 'c:/') moduleobj = imp.load_module('thefile', fileobj, pathname, description) fileobj.close() </code></pre> <p>(Of course, given 'c:/thefile.py', you can extract the parts 'c:/' and 'thefile.py' with <code>os.path.spliy</code>, and from 'thefile.py' get 'thefile' with <code>os.path.splitext</code>.)</p>
3
2009-07-20T23:51:44Z
[ "python", "import" ]
Seeding random in django
1,156,511
<p>In a view in django I use <code>random.random()</code>. How often do I have to call <code>random.seed()</code>? One time for every request? One time for every season? One time while the webserver is running?</p>
3
2009-07-20T23:26:16Z
1,156,536
<p>It really depends on what you need the random number for. Use some experimentation to find out if it makes any difference. You should also consider that there is actually a pattern to pseudo-random numbers. Does it make a difference to you if someone can possible guess the next random number? If not, seed it once at the start of a session or when the server first starts up.</p> <p>Seeding once at the start of the session would probably make the most sense, IMO. This way the user will get a set of pseudo-random numbers throughout their session. If you seed every time a page is served, they aren't guaranteed this.</p>
0
2009-07-20T23:33:25Z
[ "python", "django", "random", "django-views" ]
Seeding random in django
1,156,511
<p>In a view in django I use <code>random.random()</code>. How often do I have to call <code>random.seed()</code>? One time for every request? One time for every season? One time while the webserver is running?</p>
3
2009-07-20T23:26:16Z
1,156,541
<p>Call <code>random.seed()</code> rarely if at all.</p> <p>To be random, you must allow the random number generator to run without touching the seed. The sequence of numbers is what's random. If you change the seed, you start a new sequence. The seed values may not be very random, leading to problems. </p> <p>Depending on how many numbers you need, you can consider resetting the seed from <code>/dev/random</code> periodically.</p> <p>You should try to reset the seed just before you've used up the previous seed. You don't get the full 32 bits of randomness, so you might want to reset the seed after generating 2**28 numbers.</p>
2
2009-07-20T23:34:30Z
[ "python", "django", "random", "django-views" ]
Seeding random in django
1,156,511
<p>In a view in django I use <code>random.random()</code>. How often do I have to call <code>random.seed()</code>? One time for every request? One time for every season? One time while the webserver is running?</p>
3
2009-07-20T23:26:16Z
1,157,735
<p>Don't set the seed.</p> <p>The only time you want to set the seed is if you want to make sure that the same events keep happening. For example, if you don't want to let players cheat in your game you can save the seed, and then set it when they load their game. Then no matter how many times they save + reload, it still gives the same outcomes.</p>
3
2009-07-21T07:32:08Z
[ "python", "django", "random", "django-views" ]
Forced to use inconsistent file import paths in Python (/Django)
1,156,515
<p>I've recently been having some problems with my imports in Django (Python)... It's better to explain using a file diagram:</p> <pre><code>- project/ - application/ - file.py - application2/ - file2.py </code></pre> <p>In <code>project/application/file.py</code> I have the following:</p> <pre><code>def test_method(): return "Working" </code></pre> <p>The problem occurs in <code>project/application2/file2.py</code>, when I try to import the method from above:</p> <pre><code>from application.file import test_method </code></pre> <p>Usually works, but sometimes not.</p> <pre><code>from project.application.file import test_method </code></pre> <p>Does work, but it goes against Django's portability guidelines as the project folder must always be called the same.</p> <p>I wouldn't mind, but it's the fact that this issue is occurring inconsistently, most of the time omitting <code>project</code> is fine, but occasionally not (and as far as I can see, with no reason).</p> <p>I can pretty much guarantee I'm doing something stupid, but has anyone experienced this? Would I be better just putting the <code>project</code> in front of all relevant imports to keep things consistent? Honestly, it's unlikely the <code>project</code> folder name will ever change, I just want things to stick with guidelines where possible.</p>
4
2009-07-20T23:26:43Z
1,156,579
<p>For import to find a module, it needs to either be in sys.path. Usually, this includes "", so it searches the current directory. If you load "application" from project, it'll find it, since it's in the current directory.</p> <p>Okay, that's the obvious stuff. A confusing bit is that Python remembers which modules are loaded. If you load application, then you load application2 which imports application, the module "application" is already loaded. It doesn't need to find it on disk; it just uses the one that's already loaded. On the other hand, if you didn't happen to load application yet, it'll search for it--and not find it, since it's not in the same directory as what's loading it ("."), or anywhere else in the path.</p> <p>That can lead to the weird case where importing sometimes works and sometimes doesn't; it only works if it's already loaded.</p> <p>If you want to be able to load these modules as just "application", then you need to arrange for project/ to be appended to sys.path.</p> <p>(Relative imports sound related, but it seems like application and application2 are separate packages--relative imports are used for importing within the same package.)</p> <p>Finally, be sure to consistently treat the whole thing as a package, or to consistently treat each application as their own package. Do not mix and match. If package/ is in the path (eg. sys.path includes package/..), then you can indeed do "from package.application import foo", but if you then also do "from application import foo", it's possible for Python to not realize these are the same thing--their names are different, and they're in different paths--and end up loading two distinct copies of it, which you definitely don't want.</p>
4
2009-07-20T23:48:06Z
[ "python", "django", "import", "path" ]
Forced to use inconsistent file import paths in Python (/Django)
1,156,515
<p>I've recently been having some problems with my imports in Django (Python)... It's better to explain using a file diagram:</p> <pre><code>- project/ - application/ - file.py - application2/ - file2.py </code></pre> <p>In <code>project/application/file.py</code> I have the following:</p> <pre><code>def test_method(): return "Working" </code></pre> <p>The problem occurs in <code>project/application2/file2.py</code>, when I try to import the method from above:</p> <pre><code>from application.file import test_method </code></pre> <p>Usually works, but sometimes not.</p> <pre><code>from project.application.file import test_method </code></pre> <p>Does work, but it goes against Django's portability guidelines as the project folder must always be called the same.</p> <p>I wouldn't mind, but it's the fact that this issue is occurring inconsistently, most of the time omitting <code>project</code> is fine, but occasionally not (and as far as I can see, with no reason).</p> <p>I can pretty much guarantee I'm doing something stupid, but has anyone experienced this? Would I be better just putting the <code>project</code> in front of all relevant imports to keep things consistent? Honestly, it's unlikely the <code>project</code> folder name will ever change, I just want things to stick with guidelines where possible.</p>
4
2009-07-20T23:26:43Z
1,157,719
<p>It is better to always import using the same way - say, using <code>project.app.models</code> - because otherwise, you may find your module is imported twice, which sometimes leads to obscure errors as discussed in <a href="http://stackoverflow.com/questions/1149317/signals-registered-more-than-once-in-django1-1-testserver/1149336#1149336">this question</a>.</p>
0
2009-07-21T07:28:29Z
[ "python", "django", "import", "path" ]
Forced to use inconsistent file import paths in Python (/Django)
1,156,515
<p>I've recently been having some problems with my imports in Django (Python)... It's better to explain using a file diagram:</p> <pre><code>- project/ - application/ - file.py - application2/ - file2.py </code></pre> <p>In <code>project/application/file.py</code> I have the following:</p> <pre><code>def test_method(): return "Working" </code></pre> <p>The problem occurs in <code>project/application2/file2.py</code>, when I try to import the method from above:</p> <pre><code>from application.file import test_method </code></pre> <p>Usually works, but sometimes not.</p> <pre><code>from project.application.file import test_method </code></pre> <p>Does work, but it goes against Django's portability guidelines as the project folder must always be called the same.</p> <p>I wouldn't mind, but it's the fact that this issue is occurring inconsistently, most of the time omitting <code>project</code> is fine, but occasionally not (and as far as I can see, with no reason).</p> <p>I can pretty much guarantee I'm doing something stupid, but has anyone experienced this? Would I be better just putting the <code>project</code> in front of all relevant imports to keep things consistent? Honestly, it's unlikely the <code>project</code> folder name will ever change, I just want things to stick with guidelines where possible.</p>
4
2009-07-20T23:26:43Z
1,157,777
<p>If you dig into the django philosophy, you will find, that a project is a collection of apps. Some of these apps could depend on other apps, which is just fine. However, what you always want is to make your apps plug-able so you can move them to a different project and use them there as well. To do this, you need to strip all things in your code that's related to your project, so when doing imports you would do.</p> <pre><code>from aplication.file import test_method </code></pre> <p>This would be the django way of doing this. Glenn answered why you are getting your errors so I wont go into that part. When you run the command to start a new project: <pre>django-admin.py startproject myproject</pre> This will create a folder with a bunch of files that django needs, manage.py settings,py ect, but it will do another thing for you. It will place the folder "myproject" on your python path. In short this means that what ever application you put in that folder, you would be able to import like shown above. You don't need to use django-admin.py to start a project as nothing magical happens, it's just a shortcut. So you can place you application folders anywhere really, you just need to have them on a python path, so you can import from them directly and make your code project independent so it easily can be used in any future project, abiding to the DRY principle that django is built upon.</p>
2
2009-07-21T07:44:19Z
[ "python", "django", "import", "path" ]
How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?
1,156,962
<p>Suppose that I have a table like:</p> <pre><code>class Ticker(Entity): ticker = Field(String(7)) tsdata = OneToMany('TimeSeriesData') staticdata = OneToMany('StaticData') </code></pre> <p>How would I query it so that it returns a set of <code>Ticker.ticker</code>?</p> <p>I dig into the doc and seems like <code>select()</code> is the way to go. However I am not too familiar with the sqlalchemy syntax. Any help is appreciated.</p> <p>ADDED: My ultimate goal is to have a set of current ticker such that, when new ticker is not in the set, it will be inserted into the database. I am just learning how to create a database and sql in general. Any thought is appreciated. </p> <p>Thanks. :)</p>
0
2009-07-21T02:04:40Z
1,157,012
<p>Not sure what you're after exactly but to get an array with all 'Ticker.ticker' values you would do this:</p> <pre><code>[instance.ticker for instance in Ticker.query.all()] </code></pre> <p>What you really want is probably the <a href="http://elixir.ematia.de/trac/wiki/TutorialDivingIn" rel="nofollow">Elixir getting started tutorial</a> - it's good so take a look!</p> <p>UPDATE 1: Since you have a database, the best way to find out if a new potential ticker needs to be inserted or not is to query the database. This will be much faster than reading all tickers into memory and checking. To see if a value is there or not, try this:</p> <pre><code>Ticker.query.filter_by(ticker=new_ticker_value).first() </code></pre> <p>If the result is None you don't have it yet. So all together,</p> <pre><code>if Ticker.query.filter_by(ticker=new_ticker_value).first() is None: Ticker(ticker=new_ticker_value) session.commit() </code></pre>
0
2009-07-21T02:27:32Z
[ "python", "sql", "sqlalchemy" ]
Fast, searchable dict storage for Python
1,156,993
<p>Current I use <a href="http://www.sqlite.org/" rel="nofollow">SQLite</a> (w/ <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>) to store about 5000 dict objects. Each dict object corresponds to an entry in PyPI with keys - (name, version, summary .. sometimes 'description' can be as big as the project documentation).</p> <p>Writing these entries (from JSON) back to the disk (SQLite format) takes several seconds, and it feels slow.</p> <p>Writing is done as frequent as once a day, but reading/searching for a particular entry based on a key (usually name or description) is done very often. </p> <p>Just like apt-get.</p> <p>Is there a storage library for use with Python that will suit my needs better than SQLite?</p>
2
2009-07-21T02:16:49Z
1,157,019
<p>Did you put indices on name and description? Searching on 5000 indexed entries should be essentially instantaneous (of course ORMs will make your life much harder, as they usually do [even relatively good ones such as SQLAlchemy, but try "raw sqlite" and it absolutely should fly).</p> <p>Writing just the updated entries (again with real SQL) should also be basically instantaneous -- ideally a single update statement should do it, but even a thousand should be no real problem, just make sure to turn off autocommit at the start of the loop (and if you want turn it back again later).</p>
2
2009-07-21T02:29:57Z
[ "python", "sqlite", "data-storage" ]
Fast, searchable dict storage for Python
1,156,993
<p>Current I use <a href="http://www.sqlite.org/" rel="nofollow">SQLite</a> (w/ <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>) to store about 5000 dict objects. Each dict object corresponds to an entry in PyPI with keys - (name, version, summary .. sometimes 'description' can be as big as the project documentation).</p> <p>Writing these entries (from JSON) back to the disk (SQLite format) takes several seconds, and it feels slow.</p> <p>Writing is done as frequent as once a day, but reading/searching for a particular entry based on a key (usually name or description) is done very often. </p> <p>Just like apt-get.</p> <p>Is there a storage library for use with Python that will suit my needs better than SQLite?</p>
2
2009-07-21T02:16:49Z
1,157,087
<p>It might be overkill for your application, but you ought to check out schema-free/document-oriented databases. Personally I'm a fan of <a href="http://couchdb.apache.org/" rel="nofollow">couchdb</a>. Basically, rather than store records as rows in a table, something like couchdb stores key-value pairs, and then (in the case of couchdb) you write views in javascript to cull the data you need. These databases are usually easier to scale than relational databases, and in your case may be much faster, since you dont have to hammer your data into a shape that will fit into a relational database. On the other hand, it means that there is another service running.</p>
1
2009-07-21T03:06:08Z
[ "python", "sqlite", "data-storage" ]
Fast, searchable dict storage for Python
1,156,993
<p>Current I use <a href="http://www.sqlite.org/" rel="nofollow">SQLite</a> (w/ <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>) to store about 5000 dict objects. Each dict object corresponds to an entry in PyPI with keys - (name, version, summary .. sometimes 'description' can be as big as the project documentation).</p> <p>Writing these entries (from JSON) back to the disk (SQLite format) takes several seconds, and it feels slow.</p> <p>Writing is done as frequent as once a day, but reading/searching for a particular entry based on a key (usually name or description) is done very often. </p> <p>Just like apt-get.</p> <p>Is there a storage library for use with Python that will suit my needs better than SQLite?</p>
2
2009-07-21T02:16:49Z
2,373,002
<p>Given the approximate number of objects stated (around 5,000), SQLite is probably not the problem behind speed. It's the intermediary measures; for example JSON or possibly non-optimal use of SQLAlChemy.</p> <p>Try this out (fairly fast even for million objects): y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p> <p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p> <p>The yserial search on your keys is done using the regular expression ("regex") code on the SQLite side, not Python, so there's another substantial speed improvement. </p> <p>Let us know how it works out. </p>
0
2010-03-03T16:27:50Z
[ "python", "sqlite", "data-storage" ]
Fast, searchable dict storage for Python
1,156,993
<p>Current I use <a href="http://www.sqlite.org/" rel="nofollow">SQLite</a> (w/ <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>) to store about 5000 dict objects. Each dict object corresponds to an entry in PyPI with keys - (name, version, summary .. sometimes 'description' can be as big as the project documentation).</p> <p>Writing these entries (from JSON) back to the disk (SQLite format) takes several seconds, and it feels slow.</p> <p>Writing is done as frequent as once a day, but reading/searching for a particular entry based on a key (usually name or description) is done very often. </p> <p>Just like apt-get.</p> <p>Is there a storage library for use with Python that will suit my needs better than SQLite?</p>
2
2009-07-21T02:16:49Z
4,468,860
<p>I'm solving a very similar problem for myself right now, using <a href="http://nucular.sourceforge.net/index.html" rel="nofollow">Nucular</a>, which might suit your needs. It's a file-system based storage and seems very fast indeed. (It comes with an example app that <a href="http://aaron.oirt.rutgers.edu/cgi-bin/nucularRepo.cgi/file/7675e470b95b/test/pythonIndexTest.py" rel="nofollow">indexes the whole python source tree</a>) It's concurrent-safe, requires no external libraries and is pure python. It searches rapidly and has powerful fulltext search, indexing and so on - kind of a specialised, in-process, native python-dict store after the manner of the trendy Couchdb and mongodb, but much lighter.</p> <p>It does have limitations, though - it can't store or query on nested dictionaries, so not every JSON type can be stored in it. Moreover, although its text searching is powerful, its numerical queries are weak and unindexed. Nonetheless, it may be precisely what you are after.</p>
0
2010-12-17T08:41:18Z
[ "python", "sqlite", "data-storage" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
1,157,132
<p>You can use a list comprehension:</p> <pre><code>def remove_values_from_list(the_list, val): return [value for value in the_list if value != val] x = [1, 2, 3, 4, 2, 2, 3] x = remove_values_from_list(x, 2) print x # [1, 3, 4, 3] </code></pre>
114
2009-07-21T03:17:58Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
1,157,160
<p>Functional approach:</p> <p><strong>2.x</strong></p> <pre><code>&gt;&gt;&gt; x = [1,2,3,2,2,2,3,4] &gt;&gt;&gt; filter(lambda a: a != 2, x) [1, 3, 3, 4] </code></pre> <p><strong>3.x</strong></p> <pre><code>&gt;&gt;&gt; list(filter((2).__ne__, x)) [1, 3, 3, 4] </code></pre>
223
2009-07-21T03:28:39Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
1,157,174
<p>You can use slice assignment if the original list must be modified, while still using an efficient list comprehension (or generator expression).</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; x[:] = (value for value in x if value != 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
64
2009-07-21T03:33:13Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
4,618,920
<p>I believe this is probably faster than any other way if you don't care about the lists order, if you do take care about the final order store the indexes from the original and resort by that.</p> <pre><code>category_ids.sort() ones_last_index = category_ids.count('1') del category_ids[0:ones_last_index] </code></pre>
1
2011-01-06T19:27:17Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
10,978,459
<p>At the cost of readability, I think this version is slightly faster as it doesn't force the while to reexamine the list, thus doing exactly the same work remove has to do anyway:</p> <pre><code>x = [1, 2, 3, 4, 2, 2, 3] def remove_values_from_list(the_list, val): for i in range(the_list.count(val)): the_list.remove(val) remove_values_from_list(x, 2) print(x) </code></pre>
3
2012-06-11T10:32:47Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
14,658,399
<p>To remove all duplicate occurrences and leave one in the list:</p> <pre><code>test = [1, 1, 2, 3] newlist = list(set(test)) print newlist [1, 2, 3] </code></pre> <p>Here is the function I've used for Project Euler:</p> <pre><code>def removeOccurrences(e): return list(set(e)) </code></pre>
3
2013-02-02T03:52:04Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
24,577,941
<p>All of the answers above (apart from Martin Andersson's) create a new list without the desired items, rather than removing the items from the original list. </p> <pre><code>&gt;&gt;&gt; import random, timeit &gt;&gt;&gt; a = list(range(5)) * 1000 &gt;&gt;&gt; random.shuffle(a) &gt;&gt;&gt; b = a &gt;&gt;&gt; print(b is a) True &gt;&gt;&gt; b = [x for x in b if x != 0] &gt;&gt;&gt; print(b is a) False &gt;&gt;&gt; b.count(0) 0 &gt;&gt;&gt; a.count(0) 1000 &gt;&gt;&gt; b = a &gt;&gt;&gt; b = filter(lambda a: a != 2, x) &gt;&gt;&gt; print(b is a) False </code></pre> <p>This can be important if you have other references to the list hanging around.</p> <p>To modify the list in place, use a method like this</p> <pre><code>&gt;&gt;&gt; def removeall_inplace(x, l): ... for _ in xrange(l.count(x)): ... l.remove(x) ... &gt;&gt;&gt; removeall_inplace(0, b) &gt;&gt;&gt; b is a True &gt;&gt;&gt; a.count(0) 0 </code></pre> <p>As far as speed is concerned, results on my laptop are (all on a 5000 entry list with 1000 entries removed)</p> <ul> <li>List comprehension - ~400us</li> <li>Filter - ~900us</li> <li>.remove() loop - 50ms</li> </ul> <p>So the .remove loop is about 100x slower........ Hmmm, maybe a different approach is needed. The fastest I've found is using the list comprehension, but then replace the contents of the original list.</p> <pre><code>&gt;&gt;&gt; def removeall_replace(x, l): .... t = [y for y in l if y != x] .... del l[:] .... l.extend(t) </code></pre> <ul> <li>removeall_replace() - 450us</li> </ul>
4
2014-07-04T16:04:21Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
26,419,313
<p>Repeating the solution of the first post in a more abstract way:</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; while 2 in x: x.remove(2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
9
2014-10-17T06:42:03Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
31,132,147
<pre><code>p=[2,3,4,4,4] p.clear() print(p) [] </code></pre> <p>Only with Python 3</p>
-3
2015-06-30T07:29:32Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
36,342,652
<h1>Remove all occurrences of a value from a Python list</h1> <pre><code>lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7] def remove_values_from_list(): for list in lists: if(list!=7): print(list) remove_values_from_list() </code></pre> <p>""" Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11 """</p> <h1>Alternatively,</h1> <pre><code>lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7] def remove_values_from_list(remove): for list in lists: if(list!=remove): print(list) remove_values_from_list(7) </code></pre> <p>""" Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11 """</p>
0
2016-03-31T20:01:01Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
37,628,392
<p>Numpy approach and timings against a list/array with 1.000.000 elements:</p> <p>Timings:</p> <pre><code>In [10]: a.shape Out[10]: (1000000,) In [13]: len(lst) Out[13]: 1000000 In [18]: %timeit a[a != 2] 100 loops, best of 3: 2.94 ms per loop In [19]: %timeit [x for x in lst if x != 2] 10 loops, best of 3: 79.7 ms per loop </code></pre> <p><strong>Conclusion:</strong> numpy is 27 times faster (on my notebook) compared to list comprehension approach</p> <p>PS if you want to convert your regular Python list <code>lst</code> to numpy array:</p> <pre><code>arr = np.array(lst) </code></pre> <p>Setup:</p> <pre><code>import numpy as np a = np.random.randint(0, 1000, 10**6) In [10]: a.shape Out[10]: (1000000,) In [12]: lst = a.tolist() In [13]: len(lst) Out[13]: 1000000 </code></pre> <p>Check:</p> <pre><code>In [14]: a[a != 2].shape Out[14]: (998949,) In [15]: len([x for x in lst if x != 2]) Out[15]: 998949 </code></pre>
1
2016-06-04T09:01:52Z
[ "python", "list" ]
Remove all occurrences of a value from a Python list
1,157,106
<p>In Python <code>remove()</code> will remove the first occurrence of value in a list.</p> <p>How to remove all occurrences of a value from a list, without sorting the list?</p> <p>This is what I have in mind.</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 2, 2, 3] &gt;&gt;&gt; def remove_values_from_list(the_list, val): while val in the_list: the_list.remove(val) &gt;&gt;&gt; remove_values_from_list(x, 2) &gt;&gt;&gt; x [1, 3, 4, 3] </code></pre>
167
2009-07-21T03:12:10Z
38,259,872
<p>you can do this</p> <pre><code>while 2 in x: x.remove(2) </code></pre>
-1
2016-07-08T06:02:21Z
[ "python", "list" ]
How to update an older C extension for Python 2.x to Python 3.x
1,157,134
<p>I'm wanting to use an extension for Python that I found <a href="http://effbot.org/zone/console-index.htm" rel="nofollow">here</a>, but I'm using Python 3.1 and when I attempt to compile the C extension included in the package (_wincon), it does not compile due to all the syntax errors. Unfortunately, it was written for 2.x versions of Python and as such includes methods such as <code>PyMember_Get</code> and <code>PyMember_Set</code>, which are no longer part of Python. My problem is that I have not gotten around to learning C and as such have not been able to figure out how to modify the code to use syntax that is still valid in Python 3.1. (There were also a couple macros such as <code>staticforward</code> that need fixing, but I'm assuming those just need to be changed to <code>static</code>.) Therefore: how do I go about fixing this?</p> <p>(Note that I have indeed looked into various other Windows console interfaces for Python such as the win32con extension in PyWin32), but none of them fit my needs as much as this one appears to.)</p>
2
2009-07-21T03:18:46Z
1,157,170
<p>I don't believe there is any magic bullet to make the C sources for a Python extension coded for some old-ish version of Python 2, into valid C sources for one coded for Python 3 -- it takes understanding of C and of how the C API has changed, and of what exactly the extension is doing in each part of its code. Believe me, if we had known of some magic bullet way to do it susbtantially without such human knowledge and understanding, we'd have included a "code generator" (like 2to3 for Python sources -- and even that has substantial limitations!) for such C code translation.</p> <p>In practice, even though Python 3.1 is <strong>per se</strong> a mature and production-ready language, you should not yet migrate your code (or write a totally new app) in Python 3.1 if you need some Python 2.* extension that you're unable to port -- stick with 2.6 until the extensions you require are available (or you have learned enough C to port them yourself -- or rewrite them in Cython, which DOES smoothly support Python 2.* <em>and</em> 3.*, with, I believe, just a modicum of care on the programmer's part).</p>
7
2009-07-21T03:31:25Z
[ "python", "c", "windows", "console" ]
Creating a board game simulator (Python?) (Pygame?)
1,157,245
<p>I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python.</p> <p>The game is the old Avalon Hill game <a href="http://www.boardgamegeek.com/boardgame/2808" rel="nofollow">Russian Campaign</a></p> <p>I've been playing with PyGame a little bit and was wondering if there were reasons not to try to do this with PyGame and go after some other engine/language.</p> <p>What would be the disadvantages of using Pygame to build this?</p> <p>I'm not worried about AI, primarily I'd just love to get a minimal two player version of the game up and running. Bonuses would be the ability to save the state of the game and also to play over a network.</p> <p>Do's and Dont's for starting this project would be greatly appreciated.</p>
14
2009-07-21T04:03:33Z
1,157,289
<p>Separate the "back-end" engine (which keeps track of board state, receives move orders from front-ends, generates random numbers to resolve battles, sends updates to front-ends, deals with saving and restoring specific games, ...) from "front-end" ones, which basically supply user interfaces for all of this.</p> <p>PyGame is one suitable technology for a client-side front-end, but you could implement multiple front-ends (maybe a PyGame one, a browser-based one, a text-based one for debugging, etc, etc). The back-end of course could care less about PyGame or other UI technologies. Python is fine for most front-ends (except ones that need to be in Javascript, Actionscript, etc, if you write front-ends for browsers, Flash, etc;-) and definitely fine for thre back-end.</p> <p>Run back-end and front-ends as separate processes and communicate as simply as you possibly can -- for a turn-based game (as I believe this one is), XML-RPC or some even simpler variant (JSON payloads going back and forth over HTTP POST and replies to them, say) would seem best.</p> <p>I'd start with the back-end (probably using JSON for payloads, as I mentioned), as a dirt-simple WSGI server (maybe with a touch of werkzeug or the like to help out with mdidleware), and a simple-as-dirt debugging command-line client. At each step I would then be enriching either the server side (back-end) or the client side (front-end) carefully avoiding doing too-big OR any simultaneous "steps". I wouldn't use "heavy" technologies nor any big frameworks doing magical things behind my back (no ORMs, Django, SOAP, ...).</p> <p>Make sure you use a good source code repository (say hg, or maybe svn if you know you'll be doing it all alone, or bazaar or git if you already know them).</p>
25
2009-07-21T04:18:01Z
[ "python", "pygame" ]
Creating a board game simulator (Python?) (Pygame?)
1,157,245
<p>I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python.</p> <p>The game is the old Avalon Hill game <a href="http://www.boardgamegeek.com/boardgame/2808" rel="nofollow">Russian Campaign</a></p> <p>I've been playing with PyGame a little bit and was wondering if there were reasons not to try to do this with PyGame and go after some other engine/language.</p> <p>What would be the disadvantages of using Pygame to build this?</p> <p>I'm not worried about AI, primarily I'd just love to get a minimal two player version of the game up and running. Bonuses would be the ability to save the state of the game and also to play over a network.</p> <p>Do's and Dont's for starting this project would be greatly appreciated.</p>
14
2009-07-21T04:03:33Z
1,160,754
<p>I don't think you should care about multiple-plateforms support, separation of front-ends and back-ends, multiple processes with communication using XML-RPC and JSON, server, etc.</p> <p>Drop your bonuses and concentrate on your main idea : a turn-based, two players game. It's your first game so you'll have a lot to learn and taking care of all this at once can be overwhelming.</p>
2
2009-07-21T18:04:42Z
[ "python", "pygame" ]
Pygame and blitting: white on white = gray?
1,157,385
<p>I'm using pygame (1.9.0rc3, though this also happens in 1.8.1) to create a heatmap. To build the heatmap, I use a small, 24-bit 11x11px dot PNG image with a white background and a very low-opacity grey dot that stops exactly at the edges:</p> <p><img src="http://img442.imageshack.us/img442/465/dot.png" alt="Dot image" /></p> <p>The area around the dot is perfect white, #ffffff, as it should be. However, when I use pygame to blit the image multiple times to a new surface using BLEND_MULT, a grey square appears, as though the dot background wasn't perfect white, which doesn't make sense.</p> <p>The following code, plus included images, can reproduce this:</p> <pre><code>import os import numpy import pygame os.environ['SDL_VIDEODRIVER'] = 'dummy' pygame.display.init() pygame.display.set_mode((1,1), 0, 32) dot_image = pygame.image.load('dot.png').convert_alpha() surf = pygame.Surface((100, 100), 0, 32) surf.fill((255, 255, 255)) surf = surf.convert_alpha() for i in range(50): surf.blit(dot_image, (20, 40), None, pygame.BLEND_MULT) for i in range(100): surf.blit(dot_image, (60, 40), None, pygame.BLEND_MULT) pygame.image.save(surf, 'result.png') </code></pre> <p>When you run the code, you will get the following image:</p> <p><img src="http://img263.imageshack.us/img263/4568/result.png" alt="Resulting image after blending" /></p> <p>Is there a reason this happens? How can I work around it?</p>
5
2009-07-21T05:02:52Z
1,157,753
<p>After trying around, the only thing I could see was that you're 100% right. Multiplication by 255 results in a subtraction of 1 -- every time. In the end, I downloaded the pygame source code, and the answer is right there, in <code>surface.h</code>:</p> <pre><code>#define BLEND_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \ dR = (dR &amp;&amp; sR) ? (dR * sR) &gt;&gt; 8 : 0; \ dG = (dG &amp;&amp; sG) ? (dG * sG) &gt;&gt; 8 : 0; \ dB = (dB &amp;&amp; sB) ? (dB * sB) &gt;&gt; 8 : 0; </code></pre> <p>Pygame implements multiply blending as</p> <pre><code>new_val = old_dest * old_source / 256 </code></pre> <p>and not, which would be the correct way, as</p> <pre><code>new_val = old_dest * old_source / 255 </code></pre> <p>This is probably done for optimization purposes -- a bit shift is a lot faster than a division. As the ratio <code>255 / 256</code> is very close to one, the only difference this makes is an "off by one": The value you get is the expected value minus one -- except if you expected zero, in which case the result is correct.</p> <p>So, you have these possibilities:</p> <ol> <li>Ignore it, because the off-by-one doesn't matter for most purposes.</li> <li>Add <code>1</code> to all result values. Closest to the expected result, except you lose the zero.</li> <li>If overall correctness is not important, but you need <code>255 * 255 == 255</code> (you know what I mean), ORing <code>1</code> instead of adding suffices, and is faster.</li> </ol> <p>Note that if you don't choose answer 1, for performance reasons you'll probably have to write a C extension instead of using Python directly.</p>
6
2009-07-21T07:37:34Z
[ "python", "image", "pygame", "imaging" ]
Pygame and blitting: white on white = gray?
1,157,385
<p>I'm using pygame (1.9.0rc3, though this also happens in 1.8.1) to create a heatmap. To build the heatmap, I use a small, 24-bit 11x11px dot PNG image with a white background and a very low-opacity grey dot that stops exactly at the edges:</p> <p><img src="http://img442.imageshack.us/img442/465/dot.png" alt="Dot image" /></p> <p>The area around the dot is perfect white, #ffffff, as it should be. However, when I use pygame to blit the image multiple times to a new surface using BLEND_MULT, a grey square appears, as though the dot background wasn't perfect white, which doesn't make sense.</p> <p>The following code, plus included images, can reproduce this:</p> <pre><code>import os import numpy import pygame os.environ['SDL_VIDEODRIVER'] = 'dummy' pygame.display.init() pygame.display.set_mode((1,1), 0, 32) dot_image = pygame.image.load('dot.png').convert_alpha() surf = pygame.Surface((100, 100), 0, 32) surf.fill((255, 255, 255)) surf = surf.convert_alpha() for i in range(50): surf.blit(dot_image, (20, 40), None, pygame.BLEND_MULT) for i in range(100): surf.blit(dot_image, (60, 40), None, pygame.BLEND_MULT) pygame.image.save(surf, 'result.png') </code></pre> <p>When you run the code, you will get the following image:</p> <p><img src="http://img263.imageshack.us/img263/4568/result.png" alt="Resulting image after blending" /></p> <p>Is there a reason this happens? How can I work around it?</p>
5
2009-07-21T05:02:52Z
1,710,620
<p>Also encountered this problem doing heatmaps and after reading balpha's answer, chose to fix it the "right" (if slower) way. Change the various</p> <pre><code>(s * d) &gt;&gt; 8 </code></pre> <p>to</p> <pre><code>(s * d) / 255 </code></pre> <p>This required patching multiply functions in <code>alphablit.c</code> (though I patched <code>surface.h</code> as well). Not sure how much this impacts performance, but for the specific (heatmap) application, it produces much prettier images.</p>
1
2009-11-10T19:38:30Z
[ "python", "image", "pygame", "imaging" ]
python function for retrieving key and encryption
1,157,442
<p>M2Crypto package is not showing the 'recipient_public_key.pem' file at linux terminal.</p> <p>How do I get/connect with recipient public key.</p> <p>Exactly, I need to check how can I open this file through linux commands.</p> <pre><code>import M2Crypto def encrypt(): recip = M2Crypto.RSA.load_pub_key(open('recipient_public_key.pem','rb').read()) print recip; plaintext = whatever i need to encrypt msg = recip.public_encrypt(plaintext,RSA.pkcs1_padding) print msg; </code></pre> <p>after calling the function its not giving any output and even any error</p> <p>i also tried as 'Will' said </p> <pre><code>pk = open('public_key.pem','rb').read() print pk; rsa = M2Crypto.RSA.load_pub_key(pk) </code></pre> <p>what is the mistake I am not getting?</p>
0
2009-07-21T05:27:51Z
1,157,537
<p>I have never used M2Crypto, but according to the <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.RSA-module.html#load_pub_key" rel="nofollow">API documentation</a>, <code>load_pub_key</code> expects the file name as the argument, not the key itself. Try</p> <pre><code>recip = M2Crypto.RSA.load_pub_key('recipient_public_key.pem') </code></pre>
1
2009-07-21T06:19:04Z
[ "python" ]
Django Double Escaping Quotes etc
1,157,725
<p>I'm experiencing what I would consider somewhat strange behavior. Specifically if I have a string like this:</p> <blockquote> <p><b>1984: Curriculum Unit</b><br /> by Donald R. Hogue, Center for Learning, George Orwell<br /> <br /> "A center for learning publication"--Cover. </p> </blockquote> <p>It results in the following after being auto-escaped by the Django template system:</p> <blockquote> <p><b>1984: Curriculum Unit</b><br /> by Donald R. Hogue, Center for Learning, George Orwell<br /> <br /> &amp;quot;A center for learning publication&amp;quot;--Cover. </p> </blockquote> <p>The problem seems to be that the " (quote), which should become <code>&amp;quot;</code> is being escaped twice, resulting in <code>&amp;amp;&amp;quot;</code>. This results in strange looking formatting. I'm using Django 1.0.2, so it should be up to date, (though I should note I'm using the Ubuntu 9.04 included package python-django) but this behavior seems contrary to the intended behavior. </p> <p>I've looked a little at django.utils.html.py which includes the actual function:</p> <blockquote> <p>def escape(html):</p> <blockquote> <p>"""Returns the given HTML with ampersands, quotes and carets encoded."""</p> <p><code>return mark_safe(force_unicode(html).replace('&amp;','&amp;amp;').replace('&lt;','&amp;lt;').replace('&gt;', '&amp;gt;').replace('"', '&amp;quot;').replace("'",'&amp;#39;'))</code></p> </blockquote> <p>escape = allow_lazy(escape, unicode)</p> </blockquote> <p>Anyway, that looks like it should escape the &amp; before anything else, which would be fine. So my suspicion is that it is being called twice. Any thoughts?</p> <p>Thanks.</p> <p><b>Update:</b> I was suspicious that it might have something to do with Ubuntu's Django, which it lists as "1.0.2-1" so I installed "1.0.2-final" and am experiencing the same problem.</p>
1
2009-07-21T07:30:20Z
1,157,755
<p>You shouldn't have to think about escaping in 1.0 . If you have a template</p> <pre><code>&lt;html&gt; &lt;body&gt; &amp; == &amp;amp; in HTML &lt;/body&gt; &lt;/html&gt; </code></pre> <p>It should encode the <code>&amp;</code> to <code>&amp;amp;</code> before printing. </p> <p>If you have a variable</p> <pre><code>&lt;html&gt; &lt;body&gt; {{ msg }} &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and </p> <pre><code>def view(request) : msg = "&amp; == &amp;amp; in HTML" </code></pre> <p>if should be printed the same way.</p> <p>The only time you want to do the encoding yourself is if you need to paste in raw html. Like:</p> <pre><code>def view(request) : msg = '&lt;img src="http://example.com/pretty.jpg" /&gt;This picture is very pretty' </code></pre> <p>and in your template</p> <pre><code>&lt;html&gt; &lt;body&gt; {{ msg|safe }} &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2009-07-21T07:37:57Z
[ "python", "django" ]
Django Double Escaping Quotes etc
1,157,725
<p>I'm experiencing what I would consider somewhat strange behavior. Specifically if I have a string like this:</p> <blockquote> <p><b>1984: Curriculum Unit</b><br /> by Donald R. Hogue, Center for Learning, George Orwell<br /> <br /> "A center for learning publication"--Cover. </p> </blockquote> <p>It results in the following after being auto-escaped by the Django template system:</p> <blockquote> <p><b>1984: Curriculum Unit</b><br /> by Donald R. Hogue, Center for Learning, George Orwell<br /> <br /> &amp;quot;A center for learning publication&amp;quot;--Cover. </p> </blockquote> <p>The problem seems to be that the " (quote), which should become <code>&amp;quot;</code> is being escaped twice, resulting in <code>&amp;amp;&amp;quot;</code>. This results in strange looking formatting. I'm using Django 1.0.2, so it should be up to date, (though I should note I'm using the Ubuntu 9.04 included package python-django) but this behavior seems contrary to the intended behavior. </p> <p>I've looked a little at django.utils.html.py which includes the actual function:</p> <blockquote> <p>def escape(html):</p> <blockquote> <p>"""Returns the given HTML with ampersands, quotes and carets encoded."""</p> <p><code>return mark_safe(force_unicode(html).replace('&amp;','&amp;amp;').replace('&lt;','&amp;lt;').replace('&gt;', '&amp;gt;').replace('"', '&amp;quot;').replace("'",'&amp;#39;'))</code></p> </blockquote> <p>escape = allow_lazy(escape, unicode)</p> </blockquote> <p>Anyway, that looks like it should escape the &amp; before anything else, which would be fine. So my suspicion is that it is being called twice. Any thoughts?</p> <p>Thanks.</p> <p><b>Update:</b> I was suspicious that it might have something to do with Ubuntu's Django, which it lists as "1.0.2-1" so I installed "1.0.2-final" and am experiencing the same problem.</p>
1
2009-07-21T07:30:20Z
1,157,891
<p>Oh hardy har har,</p> <p>Silly me, Google is so smart that they already escaped those chars in the XML I was parsing. Wouldn't you know it, an hour of fiddling only to realize Google outsmarted me again!</p> <p>P.S. In case anyone else ever comes across a similar problem, I'm specifically referring to the XML returned when doing this sort of query: <a href="http://books.google.com/books/feeds/volumes?q=1984" rel="nofollow">http://books.google.com/books/feeds/volumes?q=1984</a> , the data is already escaped for you! That being said, it does put me on edge a little bit because putting |safe in my templates will mean that if I ever get data from another source that I don't trust so much... Anyway, thanks for reading! </p>
1
2009-07-21T08:12:03Z
[ "python", "django" ]
Problem with recursive search of xml document using python
1,157,768
<p>I am trying to write a function that will take an xml object, an arbitrary number of tags, defined by tuples containing a tag name, attribute and attribute value (e.g ('tag1', 'id', '1')) and return the most specific node possible. My code is below:</p> <pre><code>from xml.dom import minidom def _search(object, *pargs): if len(pargs) == 0: print "length of pargs was zero" return object else: print "length of pargs is %s" % len(pargs) if pargs[0][1]: for element in object.getElementsByTagName(pargs[0][0]): if element.attributes[pargs[0][1]].value == pargs[0][2]: _search(element, *pargs[1:]) else: if object.getElementsByTagName(pargs[0][0]) == 1: _search(element, *pargs[1:]) def main(): xmldoc = minidom.parse('./example.xml') tag1 = ('catalog_item', 'gender', "Men's") tag2 = ('size', 'description', 'Large') tag3 = ('color_swatch', '', '') args = (tag1, tag2, tag3) node = _search(xmldoc, *args) node.toxml() if __name__ == "__main__": main() </code></pre> <p>Unfortunately, this doesn't seem to work. Here's the output when I run the script:</p> <pre><code>$ ./secondsearch.py length of pargs is 3 length of pargs is 2 length of pargs is 1 Traceback (most recent call last): File "./secondsearch.py", line 35, in &lt;module&gt; main() File "./secondsearch.py", line 32, in main node.toxml() AttributeError: 'NoneType' object has no attribute 'toxml' </code></pre> <p>Why isn't the 'if len(pargs) == 0' clause being exercised? If I do manage to get the xml object returned to my main method, can I then pass the object into some other function (which could change the value of the node, or append a child node, etc.)?</p> <p>Background: Using python to automate testing processes, environment is is cygwin on winxp/vista/7, python version is 2.5.2. I would prefer to stay within the standard library if at all possible.</p> <p><strong>Here's the working code</strong>:</p> <pre><code>def _search(object, *pargs): if len(pargs) == 0: print "length of pargs was zero" else: print "length of pargs is %s" % len(pargs) for element in object.getElementsByTagName(pargs[0][0]): if pargs[0][1]: if element.attributes[pargs[0][1]].value == pargs[0][2]: return _search(element, *pargs[1:]) else: if object.getElementsByTagName(pargs[0][0]) == 1: return _search(element, *pargs[1:]) return object </code></pre>
0
2009-07-21T07:41:22Z
1,157,787
<p>Shouldn't you be inserting a <strong>return</strong> in front of your recursive calls to <code>_search</code>? The way you have it now, some exit paths from <code>_search</code> don't have a <code>return</code> statement, so they will return <code>None</code> - which leads to the exception you're seeing.</p>
2
2009-07-21T07:46:15Z
[ "python", "xml" ]
Problem with recursive search of xml document using python
1,157,768
<p>I am trying to write a function that will take an xml object, an arbitrary number of tags, defined by tuples containing a tag name, attribute and attribute value (e.g ('tag1', 'id', '1')) and return the most specific node possible. My code is below:</p> <pre><code>from xml.dom import minidom def _search(object, *pargs): if len(pargs) == 0: print "length of pargs was zero" return object else: print "length of pargs is %s" % len(pargs) if pargs[0][1]: for element in object.getElementsByTagName(pargs[0][0]): if element.attributes[pargs[0][1]].value == pargs[0][2]: _search(element, *pargs[1:]) else: if object.getElementsByTagName(pargs[0][0]) == 1: _search(element, *pargs[1:]) def main(): xmldoc = minidom.parse('./example.xml') tag1 = ('catalog_item', 'gender', "Men's") tag2 = ('size', 'description', 'Large') tag3 = ('color_swatch', '', '') args = (tag1, tag2, tag3) node = _search(xmldoc, *args) node.toxml() if __name__ == "__main__": main() </code></pre> <p>Unfortunately, this doesn't seem to work. Here's the output when I run the script:</p> <pre><code>$ ./secondsearch.py length of pargs is 3 length of pargs is 2 length of pargs is 1 Traceback (most recent call last): File "./secondsearch.py", line 35, in &lt;module&gt; main() File "./secondsearch.py", line 32, in main node.toxml() AttributeError: 'NoneType' object has no attribute 'toxml' </code></pre> <p>Why isn't the 'if len(pargs) == 0' clause being exercised? If I do manage to get the xml object returned to my main method, can I then pass the object into some other function (which could change the value of the node, or append a child node, etc.)?</p> <p>Background: Using python to automate testing processes, environment is is cygwin on winxp/vista/7, python version is 2.5.2. I would prefer to stay within the standard library if at all possible.</p> <p><strong>Here's the working code</strong>:</p> <pre><code>def _search(object, *pargs): if len(pargs) == 0: print "length of pargs was zero" else: print "length of pargs is %s" % len(pargs) for element in object.getElementsByTagName(pargs[0][0]): if pargs[0][1]: if element.attributes[pargs[0][1]].value == pargs[0][2]: return _search(element, *pargs[1:]) else: if object.getElementsByTagName(pargs[0][0]) == 1: return _search(element, *pargs[1:]) return object </code></pre>
0
2009-07-21T07:41:22Z
1,157,881
<p>I assume you're using <a href="http://www.eggheadcafe.com/community/aspnet/17/10084853/xml-viewer.aspx" rel="nofollow">http://www.eggheadcafe.com/community/aspnet/17/10084853/xml-viewer.aspx</a> as your sample data... </p> <p>As <a href="http://stackoverflow.com/questions/1157768/problem-with-recursive-search-of-xml-document-using-python/1157787#1157787">Vinay pointed out</a>, you don't return anything from your recursive calls to<code> _search</code>.</p> <p>In your else case, you don't define the value of element, but you pass it into the <code>_search()</code>.</p> <p>Also, you don't do anything if <code>pargs[0][1]</code> is empty, but <code>object.getElementsByTagName(pargs[0][0])</code> returns more than one Node... (which is also why your pargs == 0 case never gets hit...)</p> <p>And after all that, if that sample data is correct, there are two matching nodes. so you'll have a NodeList containing:</p> <pre><code> &lt;color_swatch image="red_cardigan.jpg"&gt;Red&lt;/color_swatch&gt; &lt;color_swatch image="burgundy_cardigan.jpg"&gt;Burgundy&lt;/color_swatch&gt; </code></pre> <p>and you can't call <code>.toxml()</code> on a NodeList...</p>
2
2009-07-21T08:09:54Z
[ "python", "xml" ]
Qt GraphicsScene constantly redrawing
1,157,773
<p>I've written my own implementation of <code>QGraphicsView.drawItems()</code>, to fit the needs of my application. The method as such works fine, however, it is called repeatedly, even if it does not need to be redrawn. This causes the application to max out processor utilization.<br /> Do I need to somehow signal that the drawing is finished? I read the source in the git tree, and I couldn't see any such thing being done.<br /> The app is in Python/PyQt, and my draw-method looks like this:</p> <pre><code>def drawItems(self, painter, items, options): markupColors={'manual':QColor(0, 0, 255), 'automatic':QColor(255, 0, 0), 'user':QColor(0, 255, 0)} for index in xrange(len(items)): item=items[index] option=options[index] dataAsInt, dataIsInt=item.data(self.DRAWABLE_INDEX).toInt() drawable=None if dataIsInt: drawable=self.drawables[dataAsInt] item.setPen(markupColors[drawable.source]) item.paint(painter, option, None) </code></pre> <p>The view's method is overridden by "monkey-patching", like this:</p> <pre><code> self.ui.imageArea.drawItems=self.drawer.drawItems </code></pre> <p>The above method is self.drawer.drawItems in the last statement.</p> <p>Any ideas why this happens?</p>
0
2009-07-21T07:42:49Z
1,158,538
<p>I think this causes the problem:</p> <pre><code>item.setPen(markupColors[drawable.source]) </code></pre> <p>If you take a look at the source code:</p> <pre><code>void QAbstractGraphicsShapeItem::setPen(const QPen &amp;pen) { Q_D(QAbstractGraphicsShapeItem); prepareGeometryChange(); d-&gt;pen = pen; d-&gt;boundingRect = QRectF(); update(); } </code></pre> <p>It calls update() each time pen is set.</p>
0
2009-07-21T11:06:25Z
[ "python", "qt" ]
Creating DateTime from user inputted date
1,157,794
<p>I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form.</p> <p>I've got the model of:</p> <pre><code>class Memory(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateProperty() </code></pre> <p>and then create an instance with:</p> <pre><code>memory = Memory() memory.author = users.get_current_user() memory.content = self.request.get('content') </code></pre> <p>But as soon as I try to do anything with the date value, I break it. I'm assuming - and entering - the date value in this format: 2009-07-21</p> <p>I've tried:</p> <pre><code>memory.date = time.strptime(self.request.get('date'), '%Y-%m-%d') memory.date = db.DateProperty(self.request.get('date')) memory.date = self.request.get('date') (wishful thinking I guess) </code></pre> <p>and a few other options I can't even remember now. Everything I try leads to an ImportError with a giant stack trace ending in:</p> <blockquote> <p>: No module named _multiprocessing args = ('No module named _multiprocessing',) message = 'No module named _multiprocessing'</p> </blockquote> <p>I have no idea what to make of that.</p> <p>I come from a PHP world where strtotime() was my magic function that gave me everything I needed for conversions, and the date() function could handle the rest of the formatting. Now I see things with inline lambda (??) functions and what not. </p> <p>What am I missing on something that would seem to be so simple.</p>
0
2009-07-21T07:47:48Z
1,157,838
<p>You were right with strptime:</p> <pre><code>&gt;&gt;&gt; dt = time.strptime('2009-07-21', '%Y-%m-%d') &gt;&gt;&gt; dt time.struct_time(tm_year=2009, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec =0, tm_wday=1, tm_yday=202, tm_isdst=-1) &gt;&gt;&gt; </code></pre> <p>You got struct that can be used by other functions. For example display date in M/D/Y convention:</p> <pre><code>&gt;&gt;&gt; time.strftime('%m/%d/%Y', dt) '07/21/2009' </code></pre> <p>Another example (import datetime module):</p> <pre><code>&gt;&gt;&gt; dt = datetime.datetime.strptime('2009-07-21', '%Y-%m-%d') &gt;&gt;&gt; td = datetime.timedelta(days=20) &gt;&gt;&gt; dt+td datetime.datetime(2009, 8, 10, 0, 0) </code></pre>
0
2009-07-21T07:59:57Z
[ "python", "datetime" ]
Creating DateTime from user inputted date
1,157,794
<p>I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form.</p> <p>I've got the model of:</p> <pre><code>class Memory(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateProperty() </code></pre> <p>and then create an instance with:</p> <pre><code>memory = Memory() memory.author = users.get_current_user() memory.content = self.request.get('content') </code></pre> <p>But as soon as I try to do anything with the date value, I break it. I'm assuming - and entering - the date value in this format: 2009-07-21</p> <p>I've tried:</p> <pre><code>memory.date = time.strptime(self.request.get('date'), '%Y-%m-%d') memory.date = db.DateProperty(self.request.get('date')) memory.date = self.request.get('date') (wishful thinking I guess) </code></pre> <p>and a few other options I can't even remember now. Everything I try leads to an ImportError with a giant stack trace ending in:</p> <blockquote> <p>: No module named _multiprocessing args = ('No module named _multiprocessing',) message = 'No module named _multiprocessing'</p> </blockquote> <p>I have no idea what to make of that.</p> <p>I come from a PHP world where strtotime() was my magic function that gave me everything I needed for conversions, and the date() function could handle the rest of the formatting. Now I see things with inline lambda (??) functions and what not. </p> <p>What am I missing on something that would seem to be so simple.</p>
0
2009-07-21T07:47:48Z
1,157,860
<p>Yeah, PHP's is much nicer. I'm using this library </p> <p><a href="http://labix.org/python-dateutil" rel="nofollow">http://labix.org/python-dateutil</a></p> <pre><code>&gt;&gt;&gt; import dateutil.parser &gt;&gt;&gt; dateutil.parser.parse("may 2 1984") datetime.datetime(1984, 5, 2, 0, 0) </code></pre>
0
2009-07-21T08:04:07Z
[ "python", "datetime" ]
Creating DateTime from user inputted date
1,157,794
<p>I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form.</p> <p>I've got the model of:</p> <pre><code>class Memory(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateProperty() </code></pre> <p>and then create an instance with:</p> <pre><code>memory = Memory() memory.author = users.get_current_user() memory.content = self.request.get('content') </code></pre> <p>But as soon as I try to do anything with the date value, I break it. I'm assuming - and entering - the date value in this format: 2009-07-21</p> <p>I've tried:</p> <pre><code>memory.date = time.strptime(self.request.get('date'), '%Y-%m-%d') memory.date = db.DateProperty(self.request.get('date')) memory.date = self.request.get('date') (wishful thinking I guess) </code></pre> <p>and a few other options I can't even remember now. Everything I try leads to an ImportError with a giant stack trace ending in:</p> <blockquote> <p>: No module named _multiprocessing args = ('No module named _multiprocessing',) message = 'No module named _multiprocessing'</p> </blockquote> <p>I have no idea what to make of that.</p> <p>I come from a PHP world where strtotime() was my magic function that gave me everything I needed for conversions, and the date() function could handle the rest of the formatting. Now I see things with inline lambda (??) functions and what not. </p> <p>What am I missing on something that would seem to be so simple.</p>
0
2009-07-21T07:47:48Z
1,158,002
<p>perhaps you are using the wrong class? I'm not sure what type your model should take</p> <p>but try:</p> <pre><code>from datetime import datetime myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d') </code></pre> <p>I use a datetime object in MySQL with MySQLdb (and a datetime field)</p> <p>...likewise you can try</p> <pre><code>from datetime import datetime myValue = datetime.strptime(self.request.get('date'), '%Y-%m-%d').date() </code></pre> <p>(notice the [obj].date() at the end)</p>
0
2009-07-21T08:45:38Z
[ "python", "datetime" ]
get group id by group name (Python, Unix)
1,157,864
<p>I want to use Python to get the group id to a corresponding group name. The routine must work for Unix-like OS (Linux and Mac OS X).</p> <p>This is what I found so far</p> <pre><code>&gt;&gt;&gt; import grp &gt;&gt;&gt; for g in grp.getgrall(): ... if g[0] == 'wurzel': ... print g[2] </code></pre>
7
2009-07-21T08:05:05Z
1,157,897
<p>See <a href="http://docs.python.org/library/grp.html#grp.getgrnam" rel="nofollow"><code>grp.getgrnam(name)</code></a>:</p> <blockquote> <p><code>grp.getgrnam(name)</code></p> <p>Return the group database entry for the given group name. KeyError is raised if the entry asked for cannot be found.</p> <p>Group database entries are reported as a tuple-like object, whose attributes correspond to the members of the group structure:</p> </blockquote> <pre><code>Index Attribute Meaning 0 gr_name the name of the group 1 gr_passwd the (encrypted) group password; often empty 2 gr_gid the numerical group ID 3 gr_mem all the group member’s user names </code></pre> <p>The numerical group ID is at index 2, or 2nd from last, or the attribute <code>gr_gid</code>.</p> <p>GID of <code>root</code> is 0:</p> <pre><code>&gt;&gt;&gt; grp.getgrnam('root') ('root', 'x', 0, ['root']) &gt;&gt;&gt; grp.getgrnam('root')[-2] 0 &gt;&gt;&gt; grp.getgrnam('root').gr_gid 0 &gt;&gt;&gt; </code></pre>
5
2009-07-21T08:13:08Z
[ "python", "linux", "unix" ]
get group id by group name (Python, Unix)
1,157,864
<p>I want to use Python to get the group id to a corresponding group name. The routine must work for Unix-like OS (Linux and Mac OS X).</p> <p>This is what I found so far</p> <pre><code>&gt;&gt;&gt; import grp &gt;&gt;&gt; for g in grp.getgrall(): ... if g[0] == 'wurzel': ... print g[2] </code></pre>
7
2009-07-21T08:05:05Z
1,157,958
<p>If you read the <a href="http://docs.python.org/library/grp.html">grp module documentation</a> you'll see that grp.getgrnam(groupname) will return one entry from the group database, which is a tuple-like object. You can either access the information by index or by attribute:</p> <pre><code>&gt;&gt;&gt; import grp &gt;&gt;&gt; groupinfo = grp.getgrnam('root') &gt;&gt;&gt; print groupinfo[2] 0 &gt;&gt;&gt; print groupinfo.gr_gid 0 </code></pre> <p>Other entries are the name, the encrypted password (usually empty, if using a shadow file, it'll be a dummy value) and all group member names. This works fine on any Unix system, including my Mac OS X laptop:</p> <pre><code>&gt;&gt;&gt; import grp &gt;&gt;&gt; admin = grp.getgrnam('admin') &gt;&gt;&gt; admin ('admin', '*', 80, ['root', 'admin', 'mj']) &gt;&gt;&gt; admin.gr_name 'admin' &gt;&gt;&gt; admin.gr_gid 80 &gt;&gt;&gt; admin.gr_mem ['root', 'admin', 'mj'] </code></pre> <p>The module also offers a method to get entries by gid, and as you discovered, a method to loop over all entries in the database:</p> <pre><code>&gt;&gt;&gt; grp.getgrgid(80) ('admin', '*', 80, ['root', 'admin', 'mj']) &gt;&gt;&gt; len(grp.getgrall()) 73 </code></pre> <p>Last but not least, python offers similar functionality to get information on the password and shadow files, in the <a href="http://docs.python.org/library/pwd.html">pwd</a> and <a href="http://docs.python.org/library/spwd.html">spwd</a> modules, which have a similar API.</p>
14
2009-07-21T08:34:41Z
[ "python", "linux", "unix" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
1,158,096
<pre><code>def touch(fname): if os.path.exists(fname): os.utime(fname, None) else: open(fname, 'a').close() </code></pre>
23
2009-07-21T09:11:18Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
1,158,388
<p>Simplistic:</p> <pre><code>def touch(fname): open(fname, 'a').close() os.utime(fname, None) </code></pre> <ul> <li>The <code>open</code> ensures there is a file there</li> <li>the <code>utime</code> ensures that the timestamps are updated</li> </ul> <p>Theoretically, it's possible someone will delete the file after the <code>open</code>, causing utime to raise an exception. But arguably that's OK, since something bad did happen.</p>
2
2009-07-21T10:30:54Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
1,158,471
<p>Complex (possibly buggy):</p> <pre><code>def utime(fname, atime=None, mtime=None) if type(atime) is tuple: atime, mtime = atime if atime is None or mtime is None: statinfo = os.stat(fname) if atime is None: atime = statinfo.st_atime if mtime is None: mtime = statinfo.st_mtime os.utime(fname, (atime, mtime)) def touch(fname, atime=None, mtime=None): if type(atime) is tuple: atime, mtime = atime open(fname, 'a').close() utime(fname, atime, mtime) </code></pre> <p>This tries to also allow setting the access or modification time, like GNU touch.</p>
0
2009-07-21T10:49:18Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
1,160,227
<p>This tries to be a little more race-free than the other solutions. (The <code>with</code> keyword is new in Python 2.5.)</p> <pre><code>import os def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) </code></pre> <p>Roughly equivalent to this.</p> <pre><code>import os def touch(fname, times=None): fhandle = open(fname, 'a') try: os.utime(fname, times) finally: fhandle.close() </code></pre> <p>Now, to really make it race-free, you need to use <a href="http://www.kernel.org/doc/man-pages/online/pages/man3/lutimes.3.html"><code>futimes</code></a> and change the timestamp of the open filehandle, instead of opening the file and then changing the timestamp on the filename (which may have been renamed). Unfortunately, Python doesn't seem to provide a way to call <code>futimes</code> without going through <code>ctypes</code> or similar...</p> <hr> <p><strong>EDIT</strong></p> <p>As noted by <a href="http://stackoverflow.com/users/34910/nate-parsons">Nate Parsons</a>, Python 3.3 will <a href="http://bugs.python.org/issue10812">add</a> <a href="http://docs.python.org/dev/library/os.html#path-fd">specifying a file descriptor</a> (when <a href="http://docs.python.org/dev/library/os.html#os.supports_fd"><code>os.supports_fd</code></a>) to functions such as <a href="http://docs.python.org/dev/library/os.html#os.utime"><code>os.utime</code></a>, which will use the <code>futimes</code> syscall instead of the <code>utimes</code> syscall under the hood. In other words:</p> <pre><code>import os def touch(fname, mode=0o666, dir_fd=None, **kwargs): flags = os.O_CREAT | os.O_APPEND with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f: os.utime(f.fileno() if os.utime in os.supports_fd else fname, dir_fd=None if os.supports_fd else dir_fd, **kwargs) </code></pre>
159
2009-07-21T16:17:59Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
6,222,692
<p>Why not try this?:</p> <pre><code>def touch(fname): try: os.utime(fname, None) except: open(fname, 'a').close() </code></pre> <p>I believe this eliminates any race condition that matters. If the file does not exist then an exception will be thrown.</p> <p>The only possible race condition here is if the file is created before open() is called but after os.utime(). But this does not matter because in this case the modification time will be as expected since it must have happened during the call to touch().</p>
14
2011-06-03T03:31:28Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
8,860,875
<p>Here's some code that uses ctypes (only tested on Linux):</p> <pre><code>from ctypes import * libc = CDLL("libc.so.6") # struct timespec { # time_t tv_sec; /* seconds */ # long tv_nsec; /* nanoseconds */ # }; # int futimens(int fd, const struct timespec times[2]); class c_timespec(Structure): _fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)] class c_utimbuf(Structure): _fields_ = [('atime', c_timespec), ('mtime', c_timespec)] utimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf)) futimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf)) # from /usr/include/i386-linux-gnu/bits/stat.h UTIME_NOW = ((1l &lt;&lt; 30) - 1l) UTIME_OMIT = ((1l &lt;&lt; 30) - 2l) now = c_timespec(0,UTIME_NOW) omit = c_timespec(0,UTIME_OMIT) # wrappers def update_atime(fileno): assert(isinstance(fileno, int)) libc.futimens(fileno, byref(c_utimbuf(now, omit))) def update_mtime(fileno): assert(isinstance(fileno, int)) libc.futimens(fileno, byref(c_utimbuf(omit, now))) # usage example: # # f = open("/tmp/test") # update_mtime(f.fileno()) </code></pre>
6
2012-01-14T07:44:18Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
11,249,346
<p>It might seem logical to create a string with the desired variables, and pass it to os.system:</p> <pre><code>touch = 'touch ' + dir + '/' + fileName os.system(touch) </code></pre> <p>This is inadequate in a number of ways (e.g.,it doesn't handle whitespace), so don't do it. </p> <p>A more robust method is to use subprocess :</p> <p><code>subprocess.call(['touch', os.path.join(dirname, fileName)])</code></p> <p>While this is much better than using a subshell (with os.system), it is still only suitable for quick-and-dirty scripts; use the accepted answer for cross-platform programs.</p>
0
2012-06-28T16:49:38Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
33,577,626
<pre><code>with open(file_name,'a') as f: pass </code></pre>
0
2015-11-07T00:20:57Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
34,603,829
<p>Looks like this is new as of Python 3.4 - <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.touch"><code>pathlib</code></a>.</p> <pre><code>from pathlib import Path Path('path/to/file.txt').touch() </code></pre> <p>This will create a <code>file.txt</code> at the path.</p> <p>--</p> <blockquote> <p>Path.touch(mode=0o777, exist_ok=True)</p> <p>Create a file at this given path. If mode is given, it is combined wit the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised. </p> </blockquote>
20
2016-01-05T03:45:06Z
[ "python", "utility" ]
Implement touch using Python?
1,158,076
<p><code>touch</code> is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.</p> <p>How would you implement it as a Python function? Try to be cross platform and complete.</p> <p>(Current Google results for "python touch file" are not that great, but point to <a href="http://docs.python.org/library/os.html#os.utime">os.utime</a>.)</p>
160
2009-07-21T09:05:11Z
37,978,434
<p>"open(file_name, 'a').close()" did not work for me in Python 2.7 on Windows. "os.utime(file_name, None)" worked just fine.</p> <p>Also, I had a need to recursively touch all files in a directory with a date older than some date. I created hte following based on ephemient's very helpful response. </p> <pre><code>def touch(file_name): # Update the modified timestamp of a file to now. if not os.path.exists(file_name): return try: os.utime(file_name, None) except Exception: open(file_name, 'a').close() def midas_touch(root_path, older_than=dt.now(), pattern='**', recursive=False): ''' midas_touch updates the modified timestamp of a file or files in a directory (folder) Arguements: root_path (str): file name or folder name of file-like object to touch older_than (datetime): only touch files with datetime older than this datetime pattern (str): filter files with this pattern (ignored if root_path is a single file) recursive (boolean): search sub-diretories (ignored if root_path is a single file) ''' # if root_path NOT exist, exit if not os.path.exists(root_path): return # if root_path DOES exist, continue. else: # if root_path is a directory, touch all files in root_path if os.path.isdir(root_path): # get a directory list (list of files in directory) dir_list=find_files(root_path, pattern='**', recursive=False) # loop through list of files for f in dir_list: # if the file modified date is older thatn older_than, touch the file if dt.fromtimestamp(os.path.getmtime(f)) &lt; older_than: touch(f) print "Touched ", f # if root_path is a file, touch the file else: # if the file modified date is older thatn older_than, touch the file if dt.fromtimestamp(os.path.getmtime(f)) &lt; older_than: touch(root_path) </code></pre>
0
2016-06-22T21:19:35Z
[ "python", "utility" ]
python - Importing a file that is a symbolic link
1,158,108
<p>If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py .</p> <p>If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice.</p> <p>What it does exactly?</p>
7
2009-07-21T09:15:35Z
1,158,116
<p>Python will import it twice.</p> <p>A link is a file system concept. To the Python interpreter, <code>x.py</code> and <code>y.py</code> are two different modules.</p> <pre> $ echo print \"importing \" + __file__ > x.py $ ln -s x.py y.py $ python -c "import x; import y" importing x.py importing y.py $ python -c "import x; import y" importing x.pyc importing y.pyc $ ls -F *.py *.pyc x.py x.pyc y.py@ y.pyc </pre>
9
2009-07-21T09:18:05Z
[ "python", "testing", "import" ]
python - Importing a file that is a symbolic link
1,158,108
<p>If I have files x.py and y.py . And y.py is the link(symbolic or hard) of x.py .</p> <p>If I import both the modules in my script. Will it import it once or it assumes both are different files and import it twice.</p> <p>What it does exactly?</p>
7
2009-07-21T09:15:35Z
1,948,735
<p>You only have to be careful in the case where your script itself is a symbolic link, in which case the first entry of sys.path will be the directory containing the target of the link.</p>
10
2009-12-22T19:54:49Z
[ "python", "testing", "import" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,158,150
<p>I don't know whether it would be any quicker, but you could simplify it with:</p> <pre><code>def GetObjKey(a): return a.points return sorted(a + b + c, key=GetObjKey) </code></pre> <p>You could also, of course, use <code>cmp</code> rather than <code>key</code> if you prefer.</p>
0
2009-07-21T09:27:55Z
[ "python", "arrays", "merge", "sorting" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,158,186
<p>Use the <a href="http://docs.python.org/library/bisect.html" rel="nofollow"><code>bisect</code></a> module. From the documentation: "This module provides support for maintaining a list in sorted order without having to sort the list after each insertion."</p> <pre><code>import bisect def magic(*args): r = [] for a in args: for i in a: bisect.insort(r, i) return r </code></pre>
1
2009-07-21T09:37:02Z
[ "python", "arrays", "merge", "sorting" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,158,196
<p>Python standard library offers a method for it: <a href="http://docs.python.org/library/heapq.html#heapq.merge"><code>heapq.merge</code></a>.<br /> As the documentation says, it is very similar to using <a href="http://docs.python.org/library/itertools.html#itertools.chain">itertools</a> (but with more limitations); if you cannot live with those limitations (or if you do not use Python 2.6) you can do something like this:</p> <pre><code>sorted(itertools.chain(args), cmp) </code></pre> <p>However, I think it has the same complexity as your own solution, although using iterators should give some quite good optimization and speed increase.</p>
12
2009-07-21T09:38:03Z
[ "python", "arrays", "merge", "sorting" ]
Merge sorted lists in python
1,158,128
<p>I have a bunch of sorted lists of objects, and a comparison function</p> <pre><code>class Obj : def __init__(p) : self.points = p def cmp(a, b) : return a.points &lt; b.points a = [Obj(1), Obj(3), Obj(8), ...] b = [Obj(1), Obj(2), Obj(3), ...] c = [Obj(100), Obj(300), Obj(800), ...] result = magic(a, b, c) assert result == [Obj(1), Obj(1), Obj(2), Obj(3), Obj(3), Obj(8), ...] </code></pre> <p>what does <code>magic</code> look like? My current implementation is </p> <pre><code>def magic(*args) : r = [] for a in args : r += a return sorted(r, cmp) </code></pre> <p>but that is quite inefficient. Better answers?</p>
10
2009-07-21T09:21:00Z
1,158,209
<p>Instead of using a list, you can use a <a href="http://en.wikipedia.org/wiki/Heap%5F%28data%5Fstructure" rel="nofollow">heap</a>.</p> <p>The insertion is O(log(n)), so merging a, b and c will be O(n log(n))</p> <p>In Python, you can use the <a href="http://docs.python.org/library/heapq.html" rel="nofollow"><code>heapq</code> module</a>.</p>
2
2009-07-21T09:40:30Z
[ "python", "arrays", "merge", "sorting" ]