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
With Python, can I keep a persistent dictionary and modify it?
1,229,068
<p>So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?</p> <p>It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.</p>
5
2009-08-04T18:10:52Z
23,137,456
<h1>Use JSON</h1> <p>Similar to Pete's answer, I like using JSON because it maps very well to python data structures and is very readable:</p> <p>Persisting data is trivial:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; db = {'hello': 123, 'foo': [1,2,3,4,5,6], 'bar': {'a': 0, 'b':9}} &gt;&gt;&gt; fh = open("db.json", 'w') &gt;&gt;&gt; json.dump(db, fh) </code></pre> <p>and loading it is about the same:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; fh = open("db.json", 'r') &gt;&gt;&gt; db = json.load(fh) &gt;&gt;&gt; db {'hello': 123, 'bar': {'a': 0, 'b': 9}, 'foo': [1, 2, 3, 4, 5, 6]} &gt;&gt;&gt; del new_db['foo'][3] &gt;&gt;&gt; new_db['foo'] [1, 2, 3, 5, 6] </code></pre> <p>In addition, JSON loading doesn't suffer from the same security issues that <code>shelve</code> and <code>pickle</code> do, although IIRC it is slower than pickle.</p> <h2>If you want to write on every operation:</h2> <p>If you want to save on every operation, you can subclass the Python dict object:</p> <pre><code>import os import json class DictPersistJSON(dict): def __init__(self, filename, *args, **kwargs): self.filename = filename self._load(); self.update(*args, **kwargs) def _load(self): if os.path.isfile(self.filename) and os.path.getsize(self.filename) &gt; 0: with open(self.filename, 'r') as fh: self.update(json.load(fh)) def _dump(self): with open(self.filename, 'w') as fh: json.dump(self, fh) def __getitem__(self, key): return dict.__getitem__(self, key) def __setitem__(self, key, val): dict.__setitem__(self, key, val) self._dump() def __repr__(self): dictrepr = dict.__repr__(self) return '%s(%s)' % (type(self).__name__, dictrepr) def update(self, *args, **kwargs): for k, v in dict(*args, **kwargs).items(): self[k] = v self._dump() </code></pre> <p>Which you can use like this: </p> <pre><code>db = DictPersistJSON("db.json") db["foo"] = "bar" # Will trigger a write </code></pre> <p>Which is woefully inefficient, but can get you off the ground quickly.</p>
1
2014-04-17T15:38:26Z
[ "python", "dictionary", "persistence", "object-persistence" ]
Parsing empty options in Python
1,229,146
<p>I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument"</p> <p>Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?</p>
4
2009-08-04T18:32:47Z
1,229,197
<p>Yes, there is an argument to do so when you add the option:</p> <pre><code>from optparse import OptionParser parser = OptionParser() parser.add_option("--SomeData",action="store", dest="TheData", default='') </code></pre> <p>Give the <em>default</em> argument the value you want the option to have it is to be specified but optionally have an argument.</p>
-1
2009-08-04T18:42:03Z
[ "python", "optparse", "optionparser" ]
Parsing empty options in Python
1,229,146
<p>I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument"</p> <p>Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?</p>
4
2009-08-04T18:32:47Z
1,229,387
<p>I don't think <code>optparse</code> can do this. <a href="http://argparse.googlecode.com/" rel="nofollow"><code>argparse</code></a> is a different (non-standard) module that can <a href="http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html#more-nargs-options" rel="nofollow">handle situations like this</a> where the options have optional values.</p> <p>With <code>optparse</code> you have to either have to specify the option including it's value or leave out both.</p>
1
2009-08-04T19:17:40Z
[ "python", "optparse", "optionparser" ]
Parsing empty options in Python
1,229,146
<p>I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument"</p> <p>Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?</p>
4
2009-08-04T18:32:47Z
1,229,667
<p>Sorry, misunderstood the question with my first answer. You can accomplish the ability to have optional arguments to command line flags use the <em>callback</em> action type when you define an option. Use the following function as a call back (you will likely wish to tailor to your needs) and configure it for each of the flags that can optionally receive an argument:</p> <pre><code>import optparse def optional_arg(arg_default): def func(option,opt_str,value,parser): if parser.rargs and not parser.rargs[0].startswith('-'): val=parser.rargs[0] parser.rargs.pop(0) else: val=arg_default setattr(parser.values,option.dest,val) return func def main(args): parser=optparse.OptionParser() parser.add_option('--foo',action='callback',callback=optional_arg('empty'),dest='foo') parser.add_option('--file',action='store_true',default=False) return parser.parse_args(args) if __name__=='__main__': import sys print main(sys.argv) </code></pre> <p><br><br></p> <p>Running from the command line you'll see this:</p> <pre><code># python parser.py (&lt;Values at 0x8e42d8: {'foo': None, 'file': False}&gt;, []) # python parser.py --foo (&lt;Values at 0x8e42d8: {'foo': 'empty', 'file': False}&gt;, []) # python parser.py --foo bar (&lt;Values at 0x8e42d8: {'foo': 'bar', 'file': False}&gt;, []) </code></pre>
8
2009-08-04T20:11:30Z
[ "python", "optparse", "optionparser" ]
Parsing empty options in Python
1,229,146
<p>I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument"</p> <p>Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?</p>
4
2009-08-04T18:32:47Z
3,139,732
<p>Optparse already allows you to pass the empty string as an option argument. So if possible, treat the empty string as "no value". For long options, any of the following work:</p> <pre><code>my_script --opt= --anotheroption my_script --opt='' --anotheroption my_script --opt="" --anotheroption my_script --opt '' --anotheroption my_script --opt "" --anotheroption </code></pre> <p>For short-style options, you can use either of:</p> <pre><code>my_script -o '' --anotheroption my_script -o "" --anotheroption </code></pre> <p>Caveat: this has been tested under Linux and should work the same under other Unixlike systems; Windows handles command line quoting differently and might not accept all of the variants listed above.</p>
0
2010-06-29T10:17:27Z
[ "python", "optparse", "optionparser" ]
Parsing empty options in Python
1,229,146
<p>I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument"</p> <p>Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?</p>
4
2009-08-04T18:32:47Z
8,081,533
<p>Mark Roddy's solution would work, but it requires attribute modification of a parser object during runtime, and has no support for alternative option formattings other than - or --. A slightly less involved solution is to modify the sys.argv array before running optparse and insert an empty string ("") after a switch which doesn't need to have arguments. The only constraint of this method is that you have your options default to a predictable value other than the one you are inserting into sys.argv (I chose None for the example below, but it really doesn't matter).</p> <p>The following code creates an example parser and set of options, extracts an array of allowed switches from the parser (using a little bit of instance variable magic), and then iterates through sys.argv, and every time it finds an allowed switch, it checks to see if it was given without any arguments following it . If there is no argument after a switch, the empty string will be inserted on the command line. After altering sys.argv, the parser is invoked, and you can check for options whose values are "", and act accordingly. </p> <pre><code>#Instantiate the parser, and add some options; set the options' default values to None, or something predictable that #can be checked later. PARSER_DEFAULTVAL = None parser = OptionParser(usage="%prog -[MODE] INPUT [options]") #This method doesn't work if interspersed switches and arguments are allowed. parser.allow_interspersed_args = False parser.add_option("-d", "--delete", action="store", type="string", dest="to_delete", default=PARSER_DEFAULTVAL) parser.add_option("-a", "--add", action="store", type="string", dest="to_add", default=PARSER_DEFAULTVAL) #Build a list of allowed switches, in this case ['-d', '--delete', '-a', '--add'] so that you can check if something #found on sys.argv is indeed a valid switch. This is trivial to make by hand in a short example, but if a program has #a lot of options, or if you want an idiot-proof way of getting all added options without modifying a list yourself, #this way is durable. If you are using OptionGroups, simply run the loop below with each group's option_list field. allowed_switches = [] for opt in parser.option_list: #Add the short (-a) and long (--add) form of each switch to the list. allowed_switches.extend(opt._short_opts + opt._long_opts) #Insert empty-string values into sys.argv whenever a switch without arguments is found. for a in range(len(sys.argv)): arg = sys.argv[a] #Check if the sys.argv value is a switch if arg in allowed_switches: #Check if it doesn't have an accompanying argument (i.e. if it is followed by another switch, or if it is last #on the command line) if a == len(sys.argv) - 1 or argv[a + 1] in allowed_switches: sys.argv.insert(a + 1, "") options, args = parser.parse_args() #If the option is present (i.e. wasn't set to the default value) if not (options.to_delete == PARSER_DEFAULTVAL): if options.droptables_ids_csv == "": #The switch was not used with any arguments. ... else: #The switch had arguments. ... </code></pre>
0
2011-11-10T15:01:48Z
[ "python", "optparse", "optionparser" ]
Parsing empty options in Python
1,229,146
<p>I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument"</p> <p>Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?</p>
4
2009-08-04T18:32:47Z
15,986,529
<p>After checking that the <code>cp</code> command understands e.g. <code>--backup=simple</code> but <em>not</em> <code>--backup simple</code>, I answered the problem like this:</p> <pre><code>import sys from optparse import OptionParser def add_optval_option(pog, *args, **kwargs): if 'empty' in kwargs: empty_val = kwargs.pop('empty') for i in range(1, len(sys.argv)): a = sys.argv[i] if a in args: sys.argv.insert(i+1, empty_val) break pog.add_option(*args, **kwargs) def main(args): parser = OptionParser() add_optval_option(parser, '--foo', '-f', default='MISSING', empty='EMPTY', help='"EMPTY" if given without a value. Note: ' '--foo=VALUE will work; --foo VALUE will *not*!') o, a = parser.parse_args(args) print 'Options:' print ' --foo/-f:', o.foo if a[1:]: print 'Positional arguments:' for arg in a[1:]: print ' ', arg else: print 'No positional arguments' if __name__=='__main__': import sys main(sys.argv) </code></pre> <p>Self-advertisement: This is part of the <code>opo</code> module of my <code>thebops</code> package ... ;-)</p>
0
2013-04-13T09:52:52Z
[ "python", "optparse", "optionparser" ]
Convert list of floats into buffer in Python?
1,229,202
<p>I am playing around with PortAudio and Python.</p> <pre><code>data = getData() stream.write( data ) </code></pre> <p>I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function:</p> <pre><code>def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ) return data </code></pre> <p>Unfortunately that doesn't work because <code>stream.write</code> wants a buffer object to be passed in:</p> <pre><code>TypeError: argument 2 must be string or read-only buffer, not list </code></pre> <p>So my question is: How can I convert my list of floats in to a buffer object?</p>
5
2009-08-04T18:43:04Z
1,229,232
<p>Consider perhaps instead:</p> <pre><code>d = [0.25 * math.sin(math.radians(i)) for i in range(0, 1024)] </code></pre> <p>Perhaps you have to use a package like pickle to serialize the data first.</p> <pre><code>import pickle f1 = open("test.dat", "wb") pickle.dump(d, f1) f1.close() </code></pre> <p>Then load it back in:</p> <pre><code>f2 = open("test.dat", "rb") d2 = pickle.Unpickler(f2).load() f2.close() d2 == d </code></pre> <p>Returns True</p>
0
2009-08-04T18:49:01Z
[ "python", "list", "floating-point", "buffer" ]
Convert list of floats into buffer in Python?
1,229,202
<p>I am playing around with PortAudio and Python.</p> <pre><code>data = getData() stream.write( data ) </code></pre> <p>I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function:</p> <pre><code>def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ) return data </code></pre> <p>Unfortunately that doesn't work because <code>stream.write</code> wants a buffer object to be passed in:</p> <pre><code>TypeError: argument 2 must be string or read-only buffer, not list </code></pre> <p>So my question is: How can I convert my list of floats in to a buffer object?</p>
5
2009-08-04T18:43:04Z
1,229,237
<p>Actually, the easiest way is to use the <a href="http://docs.python.org/library/struct.html#module-struct" rel="nofollow">struct module</a>. It is designed to convert from python objects to C-like "native" objects.</p>
2
2009-08-04T18:49:52Z
[ "python", "list", "floating-point", "buffer" ]
Convert list of floats into buffer in Python?
1,229,202
<p>I am playing around with PortAudio and Python.</p> <pre><code>data = getData() stream.write( data ) </code></pre> <p>I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function:</p> <pre><code>def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ) return data </code></pre> <p>Unfortunately that doesn't work because <code>stream.write</code> wants a buffer object to be passed in:</p> <pre><code>TypeError: argument 2 must be string or read-only buffer, not list </code></pre> <p>So my question is: How can I convert my list of floats in to a buffer object?</p>
5
2009-08-04T18:43:04Z
1,229,314
<pre><code>import struct def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ) return struct.pack('f'*len(data), *data) </code></pre>
7
2009-08-04T19:01:30Z
[ "python", "list", "floating-point", "buffer" ]
How to read/copy ctype pointers into python class?
1,229,318
<p>This is a kind of follow-up from <a href="http://stackoverflow.com/questions/1228158/python-ctype-recursive-structures">my last question</a> if this can help you.</p> <p>I'm defining a few ctype structures</p> <pre><code>class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", POINTER(c_ubyte)), ("work_count", c_ushort)] class EthercatPacket(Structure): _fields_ = [("ether_header", ETH_HEADER), ("Ethercat_header", EthercatHeader), ("data", POINTER(EthercatDatagram))] </code></pre> <p>note that this is parsed correctly by python, the missing classes are defined elsewhere. My problem is when I call the following code</p> <pre><code>packet = EthercatPacket() ethercap.RecvPacket(byref(packet)) print packet.data.header </code></pre> <p>This is incorrect. As I understand the problem, data is some kind of pointer so it isn't (really) mapped to EthercatDatagram, hence, the parser doesn't know the underlying header field.</p> <p>is there some way to read that field as well as any other field represented by POINTER()?</p>
1
2009-08-04T19:02:34Z
1,229,490
<p>Ok I got it working</p> <p>correct code was </p> <pre><code>print packet.data.header[0] </code></pre> <p>thanks to the 7 person who dared to look at the question</p> <p>the google string for the answer was : python ctype dereference pointer 3rd hit</p>
0
2009-08-04T19:36:36Z
[ "python", "variables", "pointers", "ctypes" ]
How to read/copy ctype pointers into python class?
1,229,318
<p>This is a kind of follow-up from <a href="http://stackoverflow.com/questions/1228158/python-ctype-recursive-structures">my last question</a> if this can help you.</p> <p>I'm defining a few ctype structures</p> <pre><code>class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", POINTER(c_ubyte)), ("work_count", c_ushort)] class EthercatPacket(Structure): _fields_ = [("ether_header", ETH_HEADER), ("Ethercat_header", EthercatHeader), ("data", POINTER(EthercatDatagram))] </code></pre> <p>note that this is parsed correctly by python, the missing classes are defined elsewhere. My problem is when I call the following code</p> <pre><code>packet = EthercatPacket() ethercap.RecvPacket(byref(packet)) print packet.data.header </code></pre> <p>This is incorrect. As I understand the problem, data is some kind of pointer so it isn't (really) mapped to EthercatDatagram, hence, the parser doesn't know the underlying header field.</p> <p>is there some way to read that field as well as any other field represented by POINTER()?</p>
1
2009-08-04T19:02:34Z
1,229,916
<p>The square-bracket notation is indeed correct. For reference, here's a snippet from some ctypes code I recently made:</p> <pre><code>class Message(Structure): _fields_ = [ ("id", BYTE), ("data", POINTER(BYTE)), ("data_length", DWORD) ] def __repr__(self): d = ' '.join(["0x%02X" % self.data[i] for i in range(self.data_length)]) return "&lt;Message: id = 0x%02X, " % (self.id) + "data_length = " + str(self.data_length) + (self.data_length &gt; 0 and (", data: " + d) or "") + "&gt;" </code></pre>
1
2009-08-04T20:59:32Z
[ "python", "variables", "pointers", "ctypes" ]
Unicode utf-8/utf-16 encoding in Python
1,229,414
<p>In python:</p> <pre><code>u'\u3053\n' </code></pre> <p>Is it utf-16? </p> <p>I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset, like if I have <code>a=u'\u3053\n'</code>.</p> <p><code>print</code> gives an exception and decoding gives an exception.</p> <pre><code>a.encode("utf-16") &gt; '\xff\xfeS0\n\x00' a.encode("utf-8") &gt; '\xe3\x81\x93\n' print a.encode("utf-8") &gt; πüô print a.encode("utf-16") &gt;  ■S0 </code></pre> <p>What's going on here?</p>
4
2009-08-04T19:22:40Z
1,229,467
<p>Here's the Unicode HowTo Doc for Python 2.6.2:</p> <p><a href="http://docs.python.org/howto/unicode.html" rel="nofollow">http://docs.python.org/howto/unicode.html</a></p> <p>Also see the links in the Reference section of that document for other explanations, including one by Joel Spolsky.</p>
1
2009-08-04T19:33:30Z
[ "python", "unicode", "encoding", "decoding" ]
Unicode utf-8/utf-16 encoding in Python
1,229,414
<p>In python:</p> <pre><code>u'\u3053\n' </code></pre> <p>Is it utf-16? </p> <p>I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset, like if I have <code>a=u'\u3053\n'</code>.</p> <p><code>print</code> gives an exception and decoding gives an exception.</p> <pre><code>a.encode("utf-16") &gt; '\xff\xfeS0\n\x00' a.encode("utf-8") &gt; '\xe3\x81\x93\n' print a.encode("utf-8") &gt; πüô print a.encode("utf-16") &gt;  ■S0 </code></pre> <p>What's going on here?</p>
4
2009-08-04T19:22:40Z
1,229,481
<p>It's a unicode character that doesn't seem to be displayable in your terminals encoding. <code>print</code> tries to encode the unicode object in the encoding of your terminal and if this can't be done you get an exception.</p> <p>On a terminal that can display utf-8 you get:</p> <pre><code>&gt;&gt;&gt; print u'\u3053' こ </code></pre> <p>Your terminal doesn't seem to be able to display utf-8, else at least the <code>print a.encode("utf-8")</code> line should produce the correct character.</p>
7
2009-08-04T19:35:04Z
[ "python", "unicode", "encoding", "decoding" ]
Unicode utf-8/utf-16 encoding in Python
1,229,414
<p>In python:</p> <pre><code>u'\u3053\n' </code></pre> <p>Is it utf-16? </p> <p>I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset, like if I have <code>a=u'\u3053\n'</code>.</p> <p><code>print</code> gives an exception and decoding gives an exception.</p> <pre><code>a.encode("utf-16") &gt; '\xff\xfeS0\n\x00' a.encode("utf-8") &gt; '\xe3\x81\x93\n' print a.encode("utf-8") &gt; πüô print a.encode("utf-16") &gt;  ■S0 </code></pre> <p>What's going on here?</p>
4
2009-08-04T19:22:40Z
1,229,498
<p>Character U+3053 "HIRAGANA LETTER KO".</p> <p>The <code>\xff\xfe</code> bit at the start of the UTF-16 binary format is the encoded byte order mark (U+FEFF), then "S0" is <code>\x5e\x30</code>, then there's the <code>\n</code> from the original string. (Each of the characters has its bytes "reversed" as it's using little endian UTF-16 encoding.)</p> <p>The UTF-8 form represents the same Hiragana character in three bytes, with the bit pattern as <a href="http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8" rel="nofollow">documented here</a>.</p> <p>Now, as for whether you should really have it in your data set... where is this data coming from? Is it reasonable for it to have Hiragana characters in it?</p>
1
2009-08-04T19:37:58Z
[ "python", "unicode", "encoding", "decoding" ]
Unicode utf-8/utf-16 encoding in Python
1,229,414
<p>In python:</p> <pre><code>u'\u3053\n' </code></pre> <p>Is it utf-16? </p> <p>I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset, like if I have <code>a=u'\u3053\n'</code>.</p> <p><code>print</code> gives an exception and decoding gives an exception.</p> <pre><code>a.encode("utf-16") &gt; '\xff\xfeS0\n\x00' a.encode("utf-8") &gt; '\xe3\x81\x93\n' print a.encode("utf-8") &gt; πüô print a.encode("utf-16") &gt;  ■S0 </code></pre> <p>What's going on here?</p>
4
2009-08-04T19:22:40Z
1,230,857
<p>You ask:</p> <blockquote> <p>u'\u3053\n'</p> <p>Is it utf-16?</p> </blockquote> <p>The answer is no: it's unicode, not any specific encoding. utf-16 is an encoding.</p> <p>To print a Unicode string effectively to your terminal, you need to find out what encoding that terminal is willing to accept and able to display. For example, the Terminal.app on my laptop is set to UTF-8 and with a rich font, so:</p> <p><img src="http://www.aleax.it/Picture%203.png" alt="screenshot" /></p> <p>...the Hiragana letter displays correctly. On a Linux workstation I have a terminal program that keeps resetting to Latin-1 so it would mangle things somewhat like yours -- I can set it to utf-8, but it doesn't have huge number of glyphs in the font, so it would display somewhat-useless placeholder glyphs instead.</p>
5
2009-08-05T02:15:58Z
[ "python", "unicode", "encoding", "decoding" ]
XML Parsing in Python using document builder factory
1,229,507
<p>I am working in STAF and STAX. Here python is used for coding . I am new to python. Basically my task is to parse a XML file in python using Document Factory Parser.</p> <p>The XML file I am trying to parse is :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;operating_system&gt; &lt;unix_80sp1&gt; &lt;tests type="quick_sanity_test"&gt; &lt;prerequisitescript&gt;preparequicksanityscript&lt;/prerequisitescript&gt; &lt;acbuildpath&gt;acbuildpath&lt;/acbuildpath&gt; &lt;testsuitscript&gt;test quick sanity script&lt;/testsuitscript&gt; &lt;testdir&gt;quick sanity dir&lt;/testdir&gt; &lt;/tests&gt; &lt;machine_name&gt;u80sp1_L004&lt;/machine_name&gt; &lt;machine_name&gt;u80sp1_L005&lt;/machine_name&gt; &lt;machine_name&gt;xyz.pxy.dxe.cde&lt;/machine_name&gt; &lt;vmware id="155.35.3.55"&gt;144.35.3.90&lt;/vmware&gt; &lt;vmware id="155.35.3.56"&gt;144.35.3.91&lt;/vmware&gt; &lt;/unix_80sp1&gt; &lt;/operating_system&gt; </code></pre> <ol> <li>I need to read all the tags . </li> <li><p>For the tags machine_name i need to read them into a list say all machine names should be in a list machname. so machname should be [u80sp1_L004,u80sp1_L005,xyz.pxy.dxe.cde] after reading the tags.</p></li> <li><p>I also need all the vmware tags: all attributes should be vmware_attr =[155.35.3.55,155.35.3.56] all vmware values should be vmware_value = [ 144.35.3.90,155.35.3.56]</p></li> </ol> <p>I am able to read all tags properly except vmware tags and machine name tags: I am using the following code:(i am new to xml and vmware).Help required.</p> <p>The below code needs to be modified.</p> <pre><code>factory = DocumentBuilderFactory.newInstance(); factory.setValidating(1) factory.setIgnoringElementContentWhitespace(0) builder = factory.newDocumentBuilder() document = builder.parse(xmlFileName) vmware_value = None vmware_attr = None machname = None # Get the text value for the element with tag name "vmware" nodeList = document.getElementsByTagName("vmware") for i in range(nodeList.getLength()): node = nodeList.item(i) if node.getNodeType() == Node.ELEMENT_NODE: children = node.getChildNodes() for j in range(children.getLength()): thisChild = children.item(j) if (thisChild.getNodeType() == Node.TEXT_NODE): vmware_value = thisChild.getNodeValue() vmware_attr ==??? what method to use ? # Get the text value for the element with tag name "machine_name" nodeList = document.getElementsByTagName("machine_name") for i in range(nodeList.getLength()): node = nodeList.item(i) if node.getNodeType() == Node.ELEMENT_NODE: children = node.getChildNodes() for j in range(children.getLength()): thisChild = children.item(j) if (thisChild.getNodeType() == Node.TEXT_NODE): machname = thisChild.getNodeValue() </code></pre> <p>Also how to check if a tag exists or not at all. I need to code the parsing properly. </p>
0
2009-08-04T19:39:12Z
1,230,508
<p>You are need to instantiate vmware_value, vmware_attr and machname as lists not as strings, so instead of this:</p> <pre><code>vmware_value = None vmware_attr = None machname = None </code></pre> <p>do this:</p> <pre><code>vmware_value = [] vmware_attr = [] machname = [] </code></pre> <p>Then, to add items to the list, use the <a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">append</a> method on your lists. E.g.:</p> <pre><code>factory = DocumentBuilderFactory.newInstance(); factory.setValidating(1) factory.setIgnoringElementContentWhitespace(0) builder = factory.newDocumentBuilder() document = builder.parse(xmlFileName) vmware_value = [] vmware_attr = [] machname = [] # Get the text value for the element with tag name "vmware" nodeList = document.getElementsByTagName("vmware") for i in range(nodeList.getLength()): node = nodeList.item(i) vmware_attr.append(node.attributes["id"].value) if node.getNodeType() == Node.ELEMENT_NODE: children = node.getChildNodes() for j in range(children.getLength()): thisChild = children.item(j) if (thisChild.getNodeType() == Node.TEXT_NODE): vmware_value.append(thisChild.getNodeValue()) </code></pre> <p>I've also edited the code to something I think should work to append the correct values to vmware_attr and vmware_value.</p> <p>I had to make the assumption that STAX uses xml.dom syntax, so if that isn't the case, you will have to edit my suggestion appropriately.</p>
0
2009-08-04T23:53:43Z
[ "python", "xml", "parsing" ]
Opening a wx.Frame in Python via a new thread
1,229,525
<p>I have a frame that exists as a start up screen for the user to make a selection before the main program starts. After the user makes a selection I need the screen to stay up as a sort of splash screen until the main program finishes loading in back.</p> <p>I've done this by creating an application and starting a thread:</p> <pre><code>class App(wx.App): ''' Creates the main frame and displays it Returns true if successful ''' def OnInit(self): try: ''' Initialization ''' self.newFile = False self.fileName = "" self.splashThread = Splash.SplashThread(logging, self) self.splashThread.start() #...More to the class </code></pre> <p>which launches a frame:</p> <pre><code>class SplashThread(threading.Thread): def __init__(self, logger, app): threading.Thread.__init__(self) self.logger = logger self.app = app def run(self): frame = Frame(self.logger, self.app) frame.Show() </code></pre> <p>The app value is needed as it contains the callback which allows the main program to continue when the user makes their selection. The problem is that the startup screen only flashes for a millisecond then goes away, not allowing the user to make a selection and blocking the rest of start up.</p> <p>Any ideas? Thanks in advance!</p>
0
2009-08-04T19:42:49Z
1,229,823
<p>You don't need threads for this. The drawback is that the splash window will block while loading but that is an issue only if you want to update it's contents (animate it) or if you want to be able to drag it. An issue that can be solved by periodically calling <code>wx.SafeYield</code> for example.</p> <pre><code>import time import wx class Loader(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self.btn1 = wx.Button(self, label="Option 1") self.btn2 = wx.Button(self, label="Option 2") sizer.Add(self.btn1, flag=wx.EXPAND) sizer.Add(self.btn2, flag=wx.EXPAND) self.btn1.Bind(wx.EVT_BUTTON, self.OnOption1) self.btn2.Bind( wx.EVT_BUTTON, lambda e: wx.MessageBox("There is no option 2") ) def OnOption1(self, event): self.btn1.Hide() self.btn2.Hide() self.Sizer.Add( wx.StaticText(self, label="Loading Option 1..."), 1, wx.ALL | wx.EXPAND, 15 ) self.Layout() self.Update() AppFrame(self).Show() class AppFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent) time.sleep(3) parent.Hide() # the top window (Loader) is hidden so the app needs to be told to exit # when this window is closed self.Bind(wx.EVT_CLOSE, lambda e: wx.GetApp().ExitMainLoop()) app = wx.PySimpleApp() app.TopWindow = Loader() app.TopWindow.Show() app.MainLoop() </code></pre>
0
2009-08-04T20:40:48Z
[ "python", "multithreading", "wxpython" ]
How to make two elements in gtk have the same size?
1,229,933
<p>I'm using pyGTK. I want to layout a large element with 2 smaller ones on each side. For aesthetic reasons, I want the 2 smaller ones to be the same size. As it is, they differ by a few pixels, and the middle element is not centered as a result.</p> <p>I tried using gtk.Table with 3 cells, but having homogeneous=True doesn't have the desired effect. I tried messing with it by making 8 cells, and then having the center one take up more cells, but it doesn't work well. Is there any way to do this?</p>
1
2009-08-04T21:04:00Z
1,229,981
<p>You should use GtkSizeGroup for this. Create a GtkSizeGroup, add both widgets to it. This will ensure that both widgets have the same size. If you want that widget have the same size in only one direction (width or height), set the "mode" property of SizeGroup.</p>
5
2009-08-04T21:18:35Z
[ "python", "layout", "gtk", "pygtk" ]
What is the % operator in python for?
1,230,321
<p>I've seen the % operator being used in some Python code related to strings, such as:</p> <pre><code>String = "Value: " % variable </code></pre> <p>What does that mean? How is it different from using:</p> <pre><code>String = "Value: " + variable </code></pre>
1
2009-08-04T22:58:56Z
1,230,332
<p>its for inserting values into strings containing <a href="http://www.python.org/doc/2.4/lib/typesseq-strings.html">format specifications</a></p> <pre><code>string = "number is %d" % 1 </code></pre> <p>or </p> <pre><code>string = "float is %.3f" % 3.1425 </code></pre> <p>this works in a similar way as spintf in C</p> <p>You can insert multiple values in two ways:</p> <pre><code>string = "number %d and float %f" % (1,3.1415) string = "number %(mynum)d and float %(myfloat)f" % {'mynum':1,'myfloat':3.1415} </code></pre>
11
2009-08-04T23:00:49Z
[ "python" ]
What is the % operator in python for?
1,230,321
<p>I've seen the % operator being used in some Python code related to strings, such as:</p> <pre><code>String = "Value: " % variable </code></pre> <p>What does that mean? How is it different from using:</p> <pre><code>String = "Value: " + variable </code></pre>
1
2009-08-04T22:58:56Z
1,230,346
<p>The % is the <em>string formatting operator</em> (also known as the <em>interpolation operator</em>), see <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">http://docs.python.org/library/stdtypes.html#string-formatting</a></p>
2
2009-08-04T23:04:51Z
[ "python" ]
What is the % operator in python for?
1,230,321
<p>I've seen the % operator being used in some Python code related to strings, such as:</p> <pre><code>String = "Value: " % variable </code></pre> <p>What does that mean? How is it different from using:</p> <pre><code>String = "Value: " + variable </code></pre>
1
2009-08-04T22:58:56Z
1,230,348
<p>Read <a href="http://diveintopython.net/native_data_types/formatting_strings.html" rel="nofollow">formatting strings</a></p> <ul> <li>'%' is the formatting string operator</li> <li>'+' would be the concat operator</li> </ul>
0
2009-08-04T23:05:07Z
[ "python" ]
What is the % operator in python for?
1,230,321
<p>I've seen the % operator being used in some Python code related to strings, such as:</p> <pre><code>String = "Value: " % variable </code></pre> <p>What does that mean? How is it different from using:</p> <pre><code>String = "Value: " + variable </code></pre>
1
2009-08-04T22:58:56Z
1,230,353
<p>For strings % is the <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">formatting operator</a>. It also marks the start of the format specifier. </p> <p>The + operator will concat a string at the end of the string with the right hand side of the +. The % operator will replace the format specifier in a formatted way at the location of the format specifier.</p> <p>For numbers % is the modula operator. (Remainder)</p>
2
2009-08-04T23:06:24Z
[ "python" ]
What is the % operator in python for?
1,230,321
<p>I've seen the % operator being used in some Python code related to strings, such as:</p> <pre><code>String = "Value: " % variable </code></pre> <p>What does that mean? How is it different from using:</p> <pre><code>String = "Value: " + variable </code></pre>
1
2009-08-04T22:58:56Z
1,231,334
<p>According to John E. Grayson in his book "Python and Tkinter Programming", using string formatter rather than concatenation could increase the performance for at least 25 percent.</p> <p>a = x + ' ' + y + ' ' + z</p> <p>is 25 percent slower than </p> <p>a = '%s %s %s' % (x, y, z)</p> <p>In Python 3, you could also do like this:</p> <p>a = '{} {} {}'.format(x, y, z)</p>
0
2009-08-05T05:24:27Z
[ "python" ]
What is the % operator in python for?
1,230,321
<p>I've seen the % operator being used in some Python code related to strings, such as:</p> <pre><code>String = "Value: " % variable </code></pre> <p>What does that mean? How is it different from using:</p> <pre><code>String = "Value: " + variable </code></pre>
1
2009-08-04T22:58:56Z
11,797,624
<p>(As an aside, in case you didn't know): When not being used on strings, <code>%</code> acts as a modulo function</p> <pre><code>&gt;&gt;&gt; 5 % 5 0 &gt;&gt;&gt; 1 % 4 1 </code></pre>
0
2012-08-03T14:23:44Z
[ "python" ]
Decode complex JSON in Python
1,230,347
<p>Hey, I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:</p> <pre> php > $insidejson = array('foo' => 'bar','foo1' => 'bar1'); php > $arr = array('a' => array('a1'=>json_encode($insidejson))); php > echo json_encode($arr); {"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}} </pre> <p>Then, with Python, I try deocding it using simplejson:</p> <pre> >>> import simplejson as json >>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}') </pre> <p>This fails with the following error:</p> <pre> Traceback (most recent call last): File "", line 1, in ? File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode ValueError: Expecting , delimiter: line 1 column 14 (char 14) </pre> <p>How can I get this JSON object decoded in Python? Both PHP and JS decode it successfully and I can't change it's structure since that would require major changes in many different components in different languages.</p> <p>Thanks!</p>
5
2009-08-04T23:05:07Z
1,230,402
<p>Try </p> <ul> <li><a href="http://docs.python.org/library/json.html" rel="nofollow">The Python Standard Library</a></li> <li><a href="http://opensource.xhaus.com/projects/show/jyson" rel="nofollow">jyson</a></li> </ul> <p>Maybe simplejson is too much "simple".</p>
1
2009-08-04T23:19:57Z
[ "php", "python", "json", "simplejson" ]
Decode complex JSON in Python
1,230,347
<p>Hey, I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:</p> <pre> php > $insidejson = array('foo' => 'bar','foo1' => 'bar1'); php > $arr = array('a' => array('a1'=>json_encode($insidejson))); php > echo json_encode($arr); {"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}} </pre> <p>Then, with Python, I try deocding it using simplejson:</p> <pre> >>> import simplejson as json >>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}') </pre> <p>This fails with the following error:</p> <pre> Traceback (most recent call last): File "", line 1, in ? File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode ValueError: Expecting , delimiter: line 1 column 14 (char 14) </pre> <p>How can I get this JSON object decoded in Python? Both PHP and JS decode it successfully and I can't change it's structure since that would require major changes in many different components in different languages.</p> <p>Thanks!</p>
5
2009-08-04T23:05:07Z
1,230,447
<p>If you want to insert backslashes into a string they need escaping themselves.</p> <pre><code>import simplejson as json json.loads('{"a":{"a1":"{\\"foo\\":\\"bar\\",\\"foo1\\":\\"bar1\\"}"}}') </code></pre> <p>I've tested it and Python handles that input just fine - except I used the json module included in the standard library (<code>import json</code>, Python 3.1).</p>
1
2009-08-04T23:35:09Z
[ "php", "python", "json", "simplejson" ]
Decode complex JSON in Python
1,230,347
<p>Hey, I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells:</p> <pre> php > $insidejson = array('foo' => 'bar','foo1' => 'bar1'); php > $arr = array('a' => array('a1'=>json_encode($insidejson))); php > echo json_encode($arr); {"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}} </pre> <p>Then, with Python, I try deocding it using simplejson:</p> <pre> >>> import simplejson as json >>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}') </pre> <p>This fails with the following error:</p> <pre> Traceback (most recent call last): File "", line 1, in ? File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode ValueError: Expecting , delimiter: line 1 column 14 (char 14) </pre> <p>How can I get this JSON object decoded in Python? Both PHP and JS decode it successfully and I can't change it's structure since that would require major changes in many different components in different languages.</p> <p>Thanks!</p>
5
2009-08-04T23:05:07Z
1,230,459
<p>Try prefixing your string with 'r' to make it a raw string:</p> <pre><code># Python 2.6.2 &gt;&gt;&gt; import json &gt;&gt;&gt; s = r'{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}' &gt;&gt;&gt; json.loads(s) {u'a': {u'a1': u'{"foo":"bar","foo1":"bar1"}'}} </code></pre> <p>What Alex says below is true: you can just double the slashes. (His answer was not posted when I started mine.) I think that using raw strings is simpler, if only because it's a language feature that means the same thing and it's harder to get wrong.</p>
9
2009-08-04T23:38:45Z
[ "php", "python", "json", "simplejson" ]
Does using properties on an old-style python class cause problems
1,230,383
<p>Pretty simple question. I've seen it mentioned in many places that using properties on an old-style class shouldn't work, but apparently Qt classes (through PyQt4) aren't new-style and there are properties on a few of them in the code I'm working with (and as far as I know the code isn't showing any sorts of problems)</p> <p>I did run across a pyqtProperty function, but I can't seem to find any documentation about it. Would it be a good alternative in this instance?</p>
5
2009-08-04T23:14:37Z
1,230,439
<p>Properties of the Python sort work, in my experience, just fine on PyQt4 objects. I don't know if they are explicitly supported by PyQt4 or not or if there are some hidden gotchas, but I've never seen them misbehave. Here's an example using PyQt 4.4 and Python 2.5:</p> <pre><code>from PyQt4.QtCore import QObject class X( QObject ): def __init__(self): self.__x = 10 def get_x(self): return self.__x def set_x(self, x): self.__x = x x = property(get_x, set_x) x = X() print x.x # Should be 10 x.x = 30 print x.x # Should be 30 </code></pre> <p><code>pyqtProperty</code> is to allow using <a href="http://doc.trolltech.com/4.5/properties.html" rel="nofollow">Qt's property system</a> which is not the same as Python's. Qt properties are introspectable from within Qt's C++ classes (which raw Python properties are not), and are used by Qt for such things as their <a href="http://doc.trolltech.com/4.5/designer-manual.html" rel="nofollow">Qt Designer</a> form editor, and <a href="http://www.qtsoftware.com/products/developer-tools" rel="nofollow">Qt Creator</a> IDE. They allow a lot of the sort of introspection of <em>run-time</em> state that you have in Python and miss in C++. In general Qt provides some of the features of dynamic languages to C++, and this is not the only area where PyQt provides More Than One Way To Do the same thing (consider also strings, dictionaries, file I/O and so on). With most of those choices the main advice I have is just to pick one side or the other and stick with it, just to avoid the possibility of some unpleasant incompatibility. I tend to prefer the Python version over the Qt version because Python is more core to my work than Qt is. If you were going to consider porting anything from PyQt back to C++ Qt, than you might prefer the Qt version of a feature over the Python one.</p>
3
2009-08-04T23:32:54Z
[ "python", "class", "properties", "pyqt" ]
Does using properties on an old-style python class cause problems
1,230,383
<p>Pretty simple question. I've seen it mentioned in many places that using properties on an old-style class shouldn't work, but apparently Qt classes (through PyQt4) aren't new-style and there are properties on a few of them in the code I'm working with (and as far as I know the code isn't showing any sorts of problems)</p> <p>I did run across a pyqtProperty function, but I can't seem to find any documentation about it. Would it be a good alternative in this instance?</p>
5
2009-08-04T23:14:37Z
1,230,829
<p>property works because QObject has a metaclass that takes care of them. Witness this small variation on @quark's code...:</p> <pre><code>from PyQt4.QtCore import QObject def makec(base): class X( base ): def __init__(self): self.__x = 10 def get_x(self): print 'getting', return self.__x def set_x(self, x): print 'setting', x self.__x = x x = property(get_x, set_x) print 'made class of mcl', type(X), issubclass(type(X), type) return X class old: pass for base in (QObject, old): X = makec(base) x = X() print x.x # Should be 10 x.x = 30 print x.x # Should be 30 </code></pre> <p>running this emits:</p> <pre><code>made class of mcl &lt;type 'PyQt4.QtCore.pyqtWrapperType'&gt; True getting 10 setting 30 getting 30 made class of mcl &lt;type 'classobj'&gt; False getting 10 30 </code></pre> <p>see the difference? In the class that's really a legacy (old-type) class, the one made the second time, metaclass is <code>classobj</code> (which ISN'T a subclass of type) and properties don't work right (assigning <code>x.x</code> bypasses the property, and after that getting <code>x.x</code> doesn't see the property any more either). But in the first case, the Qt case, there's a different metaclass, and it IS a subclass of type (so it's not really correct to say the class "isn't new-style"!), and things therefore DO work correctly.</p>
4
2009-08-05T02:04:04Z
[ "python", "class", "properties", "pyqt" ]
Does using properties on an old-style python class cause problems
1,230,383
<p>Pretty simple question. I've seen it mentioned in many places that using properties on an old-style class shouldn't work, but apparently Qt classes (through PyQt4) aren't new-style and there are properties on a few of them in the code I'm working with (and as far as I know the code isn't showing any sorts of problems)</p> <p>I did run across a pyqtProperty function, but I can't seem to find any documentation about it. Would it be a good alternative in this instance?</p>
5
2009-08-04T23:14:37Z
1,232,208
<p>At least in PyQt4.5, Qt classes certainly ARE new style objects, as seen from their method resolution order:</p> <pre><code>from PyQt4 import QtGui print QtGui.QWidget.__mro__ (&lt;class 'PyQt4.QtGui.QWidget'&gt;, &lt;class 'PyQt4.QtCore.QObject'&gt;, &lt;type 'sip.wrapper'&gt;, &lt;class 'PyQt4.QtGui.QPaintDevice'&gt;, &lt;type 'sip.simplewrapper'&gt;, &lt;type 'object'&gt;) </code></pre>
1
2009-08-05T09:46:37Z
[ "python", "class", "properties", "pyqt" ]
Does Django have a built in way of getting the last app url the current user visited?
1,230,392
<p>I was hoping that Django had a built in way of getting the last url that was visited in the app itself. As I write this I realize that there are some complications in doing something like that (excluding pages that redirect, for example) but i thought I'd give it a shot. </p> <p>if there isn't a built-in for this, what strategy would you use? I mean other than just storing a url in the session manually and referring to that when redirecting. That would work, of course, but I hate the thought of having to remember to do that for each view. Seems error-prone and not very elegant. </p> <p>Oh, and I'd rather not depend on server specific referral environment variables. </p>
0
2009-08-04T23:17:36Z
1,230,419
<p>you can just write a middleware that does exactly that, no need to repeat logging code on every view function.</p>
0
2009-08-04T23:23:25Z
[ "python", "django" ]
Does Django have a built in way of getting the last app url the current user visited?
1,230,392
<p>I was hoping that Django had a built in way of getting the last url that was visited in the app itself. As I write this I realize that there are some complications in doing something like that (excluding pages that redirect, for example) but i thought I'd give it a shot. </p> <p>if there isn't a built-in for this, what strategy would you use? I mean other than just storing a url in the session manually and referring to that when redirecting. That would work, of course, but I hate the thought of having to remember to do that for each view. Seems error-prone and not very elegant. </p> <p>Oh, and I'd rather not depend on server specific referral environment variables. </p>
0
2009-08-04T23:17:36Z
1,230,492
<p>No, there is nothing like that built in to Django core (and it's not built in because it isn't a common usage pattern).</p> <p>Like Javier suggested, you could make some middleware which does what you want. Something like this:</p> <pre><code>class PreviousURLMiddleware(object): def process_response(request, response): if response.status_code == 200: request.session['previous_url'] = request.get_full_url() return response </code></pre> <p>This middleware would have to go <em>after</em> SessionMiddleware in your settings to ensure that the session will be updated after this (the docs have a <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#activating-middleware">pretty picture</a> explaining why this is).</p>
5
2009-08-04T23:50:52Z
[ "python", "django" ]
Do I only need to check the users machine for the version of the MSVCR90.dll that was installed with my python installation?
1,230,479
<p>I was working on an update to my application and before I began I migrated to 2.62 because it seemed to be the time to. I walked right into the issue of having problems building my application using py2exe because of the MSVCR90.dlls. There seems to be a fair amount of information on how to solve this issue, including some good answers here on SO.</p> <p>I am deploying to users that more likely than not have 32 bit XP or Vista machines. Some of my users will be migrated to 64 bit Vista in the near future. My understanding of these issues is that I have to make sure they have the correct dlls that relate to the version of python that exists on the application development computer. Since I have an x86 processor then they need the x86 version of the dlls. The configuration of their computer is irrelevant. </p> <p>Is this correct or do I have to account for their architecture if I am going to deliver the dlls as private assemblies?</p> <p>Thanks for any responses</p>
0
2009-08-04T23:45:58Z
1,230,912
<p>Vista 64bit has a 32 bit emulator I believe, so you will not need to worry about this.</p> <p>However, I would just tell them to install the msvcrt runtime which is supposed to be the correct way to deal with this sxs mess.</p>
1
2009-08-05T02:37:16Z
[ "python", "py2exe", "msvcr90.dll" ]
Do I only need to check the users machine for the version of the MSVCR90.dll that was installed with my python installation?
1,230,479
<p>I was working on an update to my application and before I began I migrated to 2.62 because it seemed to be the time to. I walked right into the issue of having problems building my application using py2exe because of the MSVCR90.dlls. There seems to be a fair amount of information on how to solve this issue, including some good answers here on SO.</p> <p>I am deploying to users that more likely than not have 32 bit XP or Vista machines. Some of my users will be migrated to 64 bit Vista in the near future. My understanding of these issues is that I have to make sure they have the correct dlls that relate to the version of python that exists on the application development computer. Since I have an x86 processor then they need the x86 version of the dlls. The configuration of their computer is irrelevant. </p> <p>Is this correct or do I have to account for their architecture if I am going to deliver the dlls as private assemblies?</p> <p>Thanks for any responses</p>
0
2009-08-04T23:45:58Z
1,242,396
<p>From what I have gathered and learned the correct answer is that I have to worry about the MSCVCR90 dll that is used in the version of Python and mx that the application I am building rely on. This is important because it means that if the user has a different configuration I can't easily fix that problem unless I do some tricks to install the correct dll. If I have them download the MS installer from MS and their hardware (CPU type) does not match mine then they will potentially run into problems. There is a really good set of instructions on the wxpython users group site. <a href="http://groups.google.com/group/wxPython-users/browse_thread/thread/7f01edf7349b9ec1/dfad0122afda5d21#dfad0122afda5d21" rel="nofollow">WX Discussion</a>.</p>
0
2009-08-07T01:14:07Z
[ "python", "py2exe", "msvcr90.dll" ]
python unittest assertRaises throws exception when assertRaises fails
1,230,498
<p>I've got code where assertRaises throws an exception when assertRaises fails. I thought that if assertRaises fails then the test would fail and I'd get a report at the end that says the test failed. I wasn't expecting the exception to be thrown. Below is my code. I'm I doing something wrong? I'm using Python 2.6.2.</p> <pre><code>import unittest class myClass: def getName(self): raise myExcOne, "my exception one" #raise myExcTwo, "my exception two" #return "a" class myExcOne(Exception): "exception one" class myExcTwo(Exception): "exception two" class test_myClass(unittest.TestCase): def setUp(self): self.myClass = myClass() def testgetNameEmpty(self): #self.assertRaises(myExcOne,self.myClass.getName) #self.assertRaises(myExcTwo,self.myClass.getName) try: self.assertRaises(myExcTwo,self.myClass.getName) except Exception as e: pass if __name__ == "__main__": #unittest.main() suite = unittest.TestLoader().loadTestsFromTestCase(test_myClass) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre>
5
2009-08-04T23:51:42Z
1,230,537
<p>The code as posted is wrong. For a start, <code>class myClass():</code> shoudl be <code>class myClass:</code>. Also <code>if name == "main":</code> should be:</p> <pre><code>if __name__ == "__main__": unittest.main() </code></pre> <p>Apart from these problems, this fails because <code>getName()</code> is raising exception <code>myExcOne</code> and your test expects exception <code>myExcTwo</code>.</p> <p>Here is some code that works. Please edit the code in your question so that it is easy for us to cut and paste it into a Python session:</p> <pre><code>import unittest class myExcOne(Exception): "exception one" class myExcTwo(Exception): "exception two" class myClass: def getName(self): raise myExcTwo class test_myClass(unittest.TestCase): def setUp(self): self.myClass = myClass() def testgetNameEmpty(self): #self.assertRaises(myExcOne,self.myClass.getName) self.assertRaises(myExcTwo,self.myClass.getName) if __name__ == "__main__": unittest.main() </code></pre>
6
2009-08-05T00:05:41Z
[ "python", "unit-testing", "pyunit" ]
python unittest assertRaises throws exception when assertRaises fails
1,230,498
<p>I've got code where assertRaises throws an exception when assertRaises fails. I thought that if assertRaises fails then the test would fail and I'd get a report at the end that says the test failed. I wasn't expecting the exception to be thrown. Below is my code. I'm I doing something wrong? I'm using Python 2.6.2.</p> <pre><code>import unittest class myClass: def getName(self): raise myExcOne, "my exception one" #raise myExcTwo, "my exception two" #return "a" class myExcOne(Exception): "exception one" class myExcTwo(Exception): "exception two" class test_myClass(unittest.TestCase): def setUp(self): self.myClass = myClass() def testgetNameEmpty(self): #self.assertRaises(myExcOne,self.myClass.getName) #self.assertRaises(myExcTwo,self.myClass.getName) try: self.assertRaises(myExcTwo,self.myClass.getName) except Exception as e: pass if __name__ == "__main__": #unittest.main() suite = unittest.TestLoader().loadTestsFromTestCase(test_myClass) unittest.TextTestRunner(verbosity=2).run(suite) </code></pre>
5
2009-08-04T23:51:42Z
1,230,769
<p>Starting with an aside, the <code>()</code> after the classname in a <code>class</code> statement is perfectly correct in modern Python -- not an error at all.</p> <p>On the meat of the issue, <code>assertRaises(MyException, foo)</code> IS documented to propagate exceptions raised by calling <code>foo()</code> whose type is NOT a subclass of <code>MyException</code> -- it only catches <code>MyException</code> and subclasses thereof. As your code raises an exception of one type and your test expects one of a different unrelated type, the raised exception will then propagate, as per the docs of the <code>unittest</code> module, <a href="http://docs.python.org/library/unittest.html?highlight=unittest#unittest.TestCase.assertRaises">here</a>, and I quote: "test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised" -- and "is an error" means "propagates the other exception".</p> <p>As you catch the exception propagating in your try/except block, you nullify the error, and there's nothing left for unittest to diagnose. If your purpose is to turn this error into a failure (a debatable strategy...), your <code>except</code> block should call <code>self.fail</code>.</p>
5
2009-08-05T01:40:11Z
[ "python", "unit-testing", "pyunit" ]
How do you force refresh of a wx.Panel?
1,230,630
<p>I am trying to modify the controls of a Panel, have it update, then continue on with code execution. The problem seems to be that the Panel is waiting for Idle before it will refresh itself. I've tried refresh of course as well as GetSizer().Layout() and even sent a resize event to the frame using the SendSizeEvent() method, but to no avail. I'm at a loss here, I find it difficult to believe there is no way to force a redrawing of this panel. Here is the code that changes the controls:</p> <pre><code>def HideButtons(self): self.newButton.Show(False) self.openButton.Show(False) self.exitButton.Show(False) self.buttonSizer.Detach(self.newButton) self.buttonSizer.Detach(self.openButton) self.buttonSizer.Detach(self.exitButton) loadingLabel = wx.StaticText(self.splashImage, wx.ID_ANY, "Loading...", style=wx.ALIGN_LEFT) loadingLabel.SetBackgroundColour(wx.WHITE) self.buttonSizer.Add(loadingLabel) self.GetSizer().Layout() self.splashImage.Refresh() </code></pre> <p>Has anybody else encountered anything like this? And how did you resolve it if so?</p>
7
2009-08-05T00:40:39Z
1,230,736
<p>You could put the mutable part of your panel on subpanels, e.g. like this:</p> <pre><code>def MakeButtonPanels(self): self.buttonPanel1 = wx.Panel(self) self.Add(self.buttonPanel1, 0, wxALL|wxALIGN_LEFT, 5) # ... make the three buttons and the button sizer on buttonPanel1 self.buttonPanel2 = wx.Panel(self) self.Add(self.buttonPanel2, 0, wxALL|wxALIGN_LEFT, 5) # ... make the loading label and its sizer on buttonPanel2 self.buttonPanel2.Show(False) # hide it by default def HideButtons(self): self.buttonPanel1.Show(False) self.buttonPanel2.Show(True) self.Layout() </code></pre>
1
2009-08-05T01:22:19Z
[ "python", "wxpython", "refresh", "panel" ]
How do you force refresh of a wx.Panel?
1,230,630
<p>I am trying to modify the controls of a Panel, have it update, then continue on with code execution. The problem seems to be that the Panel is waiting for Idle before it will refresh itself. I've tried refresh of course as well as GetSizer().Layout() and even sent a resize event to the frame using the SendSizeEvent() method, but to no avail. I'm at a loss here, I find it difficult to believe there is no way to force a redrawing of this panel. Here is the code that changes the controls:</p> <pre><code>def HideButtons(self): self.newButton.Show(False) self.openButton.Show(False) self.exitButton.Show(False) self.buttonSizer.Detach(self.newButton) self.buttonSizer.Detach(self.openButton) self.buttonSizer.Detach(self.exitButton) loadingLabel = wx.StaticText(self.splashImage, wx.ID_ANY, "Loading...", style=wx.ALIGN_LEFT) loadingLabel.SetBackgroundColour(wx.WHITE) self.buttonSizer.Add(loadingLabel) self.GetSizer().Layout() self.splashImage.Refresh() </code></pre> <p>Has anybody else encountered anything like this? And how did you resolve it if so?</p>
7
2009-08-05T00:40:39Z
1,231,708
<p>You need to call the <a href="http://www.wxpython.org/docs/api/wx.Window-class.html#Update"><code>Update</code></a> method.</p>
10
2009-08-05T07:41:06Z
[ "python", "wxpython", "refresh", "panel" ]
How do you force refresh of a wx.Panel?
1,230,630
<p>I am trying to modify the controls of a Panel, have it update, then continue on with code execution. The problem seems to be that the Panel is waiting for Idle before it will refresh itself. I've tried refresh of course as well as GetSizer().Layout() and even sent a resize event to the frame using the SendSizeEvent() method, but to no avail. I'm at a loss here, I find it difficult to believe there is no way to force a redrawing of this panel. Here is the code that changes the controls:</p> <pre><code>def HideButtons(self): self.newButton.Show(False) self.openButton.Show(False) self.exitButton.Show(False) self.buttonSizer.Detach(self.newButton) self.buttonSizer.Detach(self.openButton) self.buttonSizer.Detach(self.exitButton) loadingLabel = wx.StaticText(self.splashImage, wx.ID_ANY, "Loading...", style=wx.ALIGN_LEFT) loadingLabel.SetBackgroundColour(wx.WHITE) self.buttonSizer.Add(loadingLabel) self.GetSizer().Layout() self.splashImage.Refresh() </code></pre> <p>Has anybody else encountered anything like this? And how did you resolve it if so?</p>
7
2009-08-05T00:40:39Z
17,626,478
<p>I had a <code>StaticBitmap</code> that, similarly, wouldn't update by any of these techniques (including the <code>Update</code> suggested in the accepted answer). </p> <p>I found that calling <code>.Hide()</code> and <code>.Show()</code> on the <code>Panel</code> was enough to refresh the image. I suspect that the same would be true if I had run the functions against a lower-level object like the <code>StaticBitmap</code>.</p>
2
2013-07-13T02:43:02Z
[ "python", "wxpython", "refresh", "panel" ]
subprocess: deleting child processes in Windows
1,230,669
<p>On Windows, <code>subprocess.Popen.terminate</code> calls win32's <code>TerminalProcess</code>. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed?</p>
25
2009-08-05T00:53:49Z
1,230,853
<p>This is a hard thing to do. Windows does not actually store a process tree in the process space. Nor is it possible to terminate a process and specify that it's children should also die.</p> <p>One way around that is to use taskkill and tell it to wack the whole tree.</p> <p>Another way to do it (assuming that you are spawning the top-level process) is to use a module that was developed with this sort of thing in mind: <a href="http://benjamin.smedbergs.us/blog/tag/killableprocess/">http://benjamin.smedbergs.us/blog/tag/killableprocess/</a></p> <p>In order to do this generically for yourself, you have to spend some time building the list backwards. That is, a process stores pointers to it's PARENT, but parents appear to not store information about children. </p> <p>So you have to look at all the processes in the system (which really isn't that hard), and then manually connect the dots yourself by looking at the parent process field. Then, you select the tree you are interested in and walk the whole thing, killing each node in turn, one by one.</p> <p>Note that Windows doesn't update a child's parent pointer when the parent dies, so there may be gaps in your tree. I'm not aware of anything you can do about those.</p>
7
2009-08-05T02:12:55Z
[ "python", "windows", "process", "subprocess", "kill-process" ]
subprocess: deleting child processes in Windows
1,230,669
<p>On Windows, <code>subprocess.Popen.terminate</code> calls win32's <code>TerminalProcess</code>. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed?</p>
25
2009-08-05T00:53:49Z
1,231,192
<p>Put the children in a NT <a href="http://msdn.microsoft.com/en-us/library/ms684161%28VS.85%29.aspx">Job object</a>, then you can kill all children</p>
6
2009-08-05T04:30:00Z
[ "python", "windows", "process", "subprocess", "kill-process" ]
subprocess: deleting child processes in Windows
1,230,669
<p>On Windows, <code>subprocess.Popen.terminate</code> calls win32's <code>TerminalProcess</code>. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed?</p>
25
2009-08-05T00:53:49Z
4,229,404
<p>By using <a href="http://code.google.com/p/psutil">psutil</a>:</p> <pre><code>import psutil, os def kill_proc_tree(pid, including_parent=True): parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: child.kill() psutil.wait_procs(children, timeout=5) if including_parent: parent.kill() parent.wait(5) me = os.getpid() kill_proc_tree(me) </code></pre>
41
2010-11-19T21:11:59Z
[ "python", "windows", "process", "subprocess", "kill-process" ]
subprocess: deleting child processes in Windows
1,230,669
<p>On Windows, <code>subprocess.Popen.terminate</code> calls win32's <code>TerminalProcess</code>. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed?</p>
25
2009-08-05T00:53:49Z
10,830,753
<p>Use <code>taskkill</code> with the <code>/T</code> flag</p> <pre><code>p = subprocess.Popen(...) &lt;wait&gt; subprocess.call(['taskkill', '/F', '/T', '/PID', str(p.pid)]) </code></pre> <p>The flags to taskkill has the following docs:</p> <pre><code>TASKKILL [/S system [/U username [/P [password]]]] { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F] /S system Specifies the remote system to connect to. /U [domain\]user Specifies the user context under which the command should execute. /P [password] Specifies the password for the given user context. Prompts for input if omitted. /FI filter Applies a filter to select a set of tasks. Allows "*" to be used. ex. imagename eq acme* /PID processid Specifies the PID of the process to be terminated. Use TaskList to get the PID. /IM imagename Specifies the image name of the process to be terminated. Wildcard '*' can be used to specify all tasks or image names. /T Terminates the specified process and any child processes which were started by it. /F Specifies to forcefully terminate the process(es). /? Displays this help message. </code></pre> <p>Or walk the process tree using comtypes and win32api:</p> <pre><code>def killsubprocesses(parent_pid): '''kill parent and all subprocess using COM/WMI and the win32api''' log = logging.getLogger('killprocesses') try: import comtypes.client except ImportError: log.debug("comtypes not present, not killing subprocesses") return logging.getLogger('comtypes').setLevel(logging.INFO) log.debug('Querying process tree...') # get pid and subprocess pids for all alive processes WMI = comtypes.client.CoGetObject('winmgmts:') processes = WMI.InstancesOf('Win32_Process') subprocess_pids = {} # parent pid -&gt; list of child pids for process in processes: pid = process.Properties_('ProcessID').Value parent = process.Properties_('ParentProcessId').Value log.trace("process %i's parent is: %s" % (pid, parent)) subprocess_pids.setdefault(parent, []).append(pid) subprocess_pids.setdefault(pid, []) # find which we need to kill log.debug('Determining subprocesses for pid %i...' % parent_pid) processes_to_kill = [] parent_processes = [parent_pid] while parent_processes: current_pid = parent_processes.pop() subps = subprocess_pids[current_pid] log.debug("process %i children are: %s" % (current_pid, subps)) parent_processes.extend(subps) processes_to_kill.extend(subps) # kill the subprocess tree if processes_to_kill: log.info('Process pid %i spawned %i subprocesses, terminating them...' % (parent_pid, len(processes_to_kill))) else: log.debug('Process pid %i had no subprocesses.' % parent_pid) import ctypes kernel32 = ctypes.windll.kernel32 for pid in processes_to_kill: hProcess = kernel32.OpenProcess(PROCESS_TERMINATE, FALSE, pid) if not hProcess: log.warning('Unable to open process pid %i for termination' % pid) else: log.debug('Terminating pid %i' % pid) kernel32.TerminateProcess(hProcess, 3) kernel32.CloseHandle(hProcess) </code></pre>
17
2012-05-31T09:21:14Z
[ "python", "windows", "process", "subprocess", "kill-process" ]
subprocess: deleting child processes in Windows
1,230,669
<p>On Windows, <code>subprocess.Popen.terminate</code> calls win32's <code>TerminalProcess</code>. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed?</p>
25
2009-08-05T00:53:49Z
12,942,797
<p>Here's example code for the Job object method, but instead of <code>subprocess</code> it uses <code>win32api.CreateProcess</code></p> <pre><code>import win32process import win32job startup = win32process.STARTUPINFO() (hProcess, hThread, processId, threadId) = win32process.CreateProcess(None, command, None, None, True, win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup) hJob = win32job.CreateJobObject(None, '') extended_info = win32job.QueryInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation) extended_info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE win32job.SetInformationJobObject(hJob, win32job.JobObjectExtendedLimitInformation, extended_info) win32job.AssignProcessToJobObject(hJob, hProcess) </code></pre>
6
2012-10-17T20:25:37Z
[ "python", "windows", "process", "subprocess", "kill-process" ]
How should I close a multi-line variable/comment in Python?
1,231,333
<p>I am receiving this error:</p> <pre><code> File "/DateDbLoop.py", line 33 d.Id""" % (str(day), str(2840))" ^ SyntaxError: EOL while scanning single-quoted string </code></pre> <p>Here is the script. There are 4 double quotes to open this, but I am unsure how to correctly close this out?</p> <p>Follow Up Question:</p> <p>Does this % (str(day), str(2840)) need to go in both the sql variable and the os.system() call?</p> <pre><code>#!/usr/bin/python import datetime import sys, os, time, string a = datetime.date(2009, 1, 1) b = datetime.date(2009, 2, 1) one_day = datetime.timedelta(1) day = a while day &lt;= b: print "Running query for \"" + str(day) + "\"" sql=""""SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' AND d.Id = %s GROUP BY d.Date """ % (str(day), str(2840))" os.system('mysql -h -sN -u -p -e %s &gt; FileName-%s.txt db' % (sql, str(day))) day += one_day </code></pre>
0
2009-08-05T05:23:32Z
1,231,340
<p>You use triple quotes for this.</p> <pre><code>s = """ Python is awesome. Python is cool. I use Python. And so should you. """ print s Python is awesome. Python is cool. I use Python. And so should you. </code></pre>
0
2009-08-05T05:27:23Z
[ "python" ]
How should I close a multi-line variable/comment in Python?
1,231,333
<p>I am receiving this error:</p> <pre><code> File "/DateDbLoop.py", line 33 d.Id""" % (str(day), str(2840))" ^ SyntaxError: EOL while scanning single-quoted string </code></pre> <p>Here is the script. There are 4 double quotes to open this, but I am unsure how to correctly close this out?</p> <p>Follow Up Question:</p> <p>Does this % (str(day), str(2840)) need to go in both the sql variable and the os.system() call?</p> <pre><code>#!/usr/bin/python import datetime import sys, os, time, string a = datetime.date(2009, 1, 1) b = datetime.date(2009, 2, 1) one_day = datetime.timedelta(1) day = a while day &lt;= b: print "Running query for \"" + str(day) + "\"" sql=""""SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' AND d.Id = %s GROUP BY d.Date """ % (str(day), str(2840))" os.system('mysql -h -sN -u -p -e %s &gt; FileName-%s.txt db' % (sql, str(day))) day += one_day </code></pre>
0
2009-08-05T05:23:32Z
1,231,341
<p>You have 4 double-quotes at your sql= line, make it 3 instead. Also remove the single quote after your %-substitution value.</p> <pre><code>#!/usr/bin/python import datetime import sys, os, time, string a = datetime.date(2009, 1, 1) b = datetime.date(2009, 2, 1) one_day = datetime.timedelta(1) day = a while day &lt;= b: print "Running query for \"" + str(day) + "\"" sql="""SELECT d.Date, SUM(d.Revenue) FROM Table d WHERE d.Date = '%s' AND d.Id = %s GROUP BY d.Date """ % (str(day), str(2840)) os.system('mysql -h -sN -u -p -e "%s" &gt; FileName-%s.txt db' % (sql, str(day))) day += one_day </code></pre> <p>Multi-line string values are done with paired triplets of double-quotes in Python, and don't nest inside regular double-quotes.</p>
5
2009-08-05T05:27:40Z
[ "python" ]
How should I close a multi-line variable/comment in Python?
1,231,333
<p>I am receiving this error:</p> <pre><code> File "/DateDbLoop.py", line 33 d.Id""" % (str(day), str(2840))" ^ SyntaxError: EOL while scanning single-quoted string </code></pre> <p>Here is the script. There are 4 double quotes to open this, but I am unsure how to correctly close this out?</p> <p>Follow Up Question:</p> <p>Does this % (str(day), str(2840)) need to go in both the sql variable and the os.system() call?</p> <pre><code>#!/usr/bin/python import datetime import sys, os, time, string a = datetime.date(2009, 1, 1) b = datetime.date(2009, 2, 1) one_day = datetime.timedelta(1) day = a while day &lt;= b: print "Running query for \"" + str(day) + "\"" sql=""""SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' AND d.Id = %s GROUP BY d.Date """ % (str(day), str(2840))" os.system('mysql -h -sN -u -p -e %s &gt; FileName-%s.txt db' % (sql, str(day))) day += one_day </code></pre>
0
2009-08-05T05:23:32Z
1,231,356
<p>Open and close the string with three quotes </p> <pre><code>sql = """ SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' AND d.Id = %s GROUP BY d.Date """ % (str(day), str(2840)) </code></pre> <p>You can also break a line in the middle of a string with the \ character. </p> <pre><code>#!/usr/bin/python import datetime import sys, os, time, string a = datetime.date(2009, 1, 1) b = datetime.date(2009, 2, 1) one_day = datetime.timedelta(1) day = a while day &lt;= b: print "Running query for \"" + str(day) + "\"" sql="SELECT d.Date, SUM(d.Revenue), FROM Table d WHERE d.Date = '%s' \ AND d.Id = %s GROUP BY d.Date " % (str(day), str(2840)) os.system('mysql -h -sN -u -p -e %s &gt; FileName-%s.txt db' % (sql, str(day))) </code></pre>
1
2009-08-05T05:31:44Z
[ "python" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,419
<p>The <a href="http://wiki.python.org/moin/BeginnersGuide" rel="nofollow">Python Beginner's Guide</a> and the official <a href="http://docs.python.org/tutorial/" rel="nofollow">Python Tutorial</a> both seem like good places to start.</p>
0
2009-08-05T05:55:57Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,439
<p>On my mac/Linux machines, python came pre-installed. On windows I use both <a href="http://jython.org" rel="nofollow">jython</a> under the <a href="http://eclipse.org" rel="nofollow">eclipse</a> IDE and <a href="http://ActiveState.com/activepython" rel="nofollow">ActivePython</a> with their IDE/eclipse.   With <a href="http://eclipse.org" rel="nofollow">eclipse</a> you'll want <a href="http://pydev.sourceforge.net/" rel="nofollow">PyDev</a>. </p>
1
2009-08-05T06:01:31Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,658
<p>Under Unix, Emacs is a good choice, to which I always come back, because it is convenient to have a single editor for everything, and because it's open source.</p> <p>What is best for you depends on your past experience with IDEs. I'd say: stick with what you've been using, or take this opportunity to try an even better IDE.</p> <p>Note: Python comes with Idle, which is a very simple (if limited) IDE.</p>
3
2009-08-05T07:25:49Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,739
<p>Geany is a good option for a Linux setup, it's intellisense isn't that great but syntax highlighting is good and it can compile your code directly from inside the editor, plus it handles other languages such as C/C++, PHP, Java etc... Eric is another popular choice as it's a full IDE and I know some people use Eclipse.</p> <p>On windows I use Notepad++, but it's mostly because I like text editors instead of fully blown IDE's.</p> <p>Reference wise Daniel's choices are very good places to start, also check out <a href="http://www.greenteapress.com/" rel="nofollow">Green Tea Press</a> who do free computer books, there are two Python choices on there but the "Python for Software Design" book hasn't yet been published properly although you can download the manuscript. The "How to Think Like a Computer Scientist" book is a good one and not as scary as it sounds.</p>
0
2009-08-05T07:51:22Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,761
<p><a href="http://en.wikipedia.org/wiki/IDLE%5F%28Python%29" rel="nofollow">IDLE</a> is nice to try out things. Other tools that people like are <a href="http://www.eclipse.org/" rel="nofollow">Eclipse</a> with the <a href="http://pydev.sourceforge.net/" rel="nofollow">Pydev</a> plugin which seems to work ok, although it has crashed a few times (Eclipse, that is) and <a href="http://www.netbeans.org/" rel="nofollow">NetBeans</a> (which I haven't tried) but some people seem to like.</p>
0
2009-08-05T07:57:34Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,790
<p>It all depends on what you are looking for and what you are already using. </p> <p>For instance, if you are using a more 'simple' editor at the moment: as long as it's got Python syntax you've got the basics.</p> <p>If you are used to e.g. <a href="http://eclipse.org/" rel="nofollow">Eclipse</a> you can just continue to use that, combined with <a href="http://pydev.sourceforge.net" rel="nofollow">Pydev</a>. Besides syntax highlighting you'll also get more fancy features to help you debug and <a href="http://en.wikipedia.org/wiki/Code_refactoring" rel="nofollow">refactor</a> your code.</p> <p>Personally I use <a href="http://www.gnu.org/software/emacs/" rel="nofollow">Emacs</a> with <a href="https://launchpad.net/python-mode" rel="nofollow">python-mode</a> (and a few other modes to interface with Subversion and Git). In the past I used <a href="http://www.vim.org/" rel="nofollow">Vim</a> which also worked quite well.</p> <p>My advice would be to start out with your current environment as long as it has some rudimentary support for Python. Once you are familiar with the language, start exploring what your environment is missing and either add it or if you cannot, switch to an enviroment which does support the feature.</p>
1
2009-08-05T08:06:15Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,813
<p>I can only help you if you're running a Mac. Download <a href="http://developer.apple.com/technology/xcode.html" rel="nofollow">Xcode</a>. I believe that Python 2.3 comes bundled with these development tools. Luckily enough, this is all you really need to get started, unless you want a newer version of Python.</p> <p>All you need to do is open up Terminal and type <code>python</code>. You're done!</p>
0
2009-08-05T08:11:42Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,819
<p>Be sure to check out IPython. It's an enhanced interactive python shell with a bunch of useful features such as Tab-Completion using introspection (eg, type "my_object." to see a list of its attributes and methods), logging your interactive session to an executable python-file, defining macros, etc. The <a href="http://ipython.scipy.org/moin/Documentation" rel="nofollow">documentation page</a> has a link to the tutorial as well as screencasts showing it in action.</p>
2
2009-08-05T08:12:34Z
[ "python", "ide" ]
New to Python. Need info on the environment for it
1,231,397
<p>I'm a complete newbie to Python. I've worked on PHP/JavaScript earlier but starting today I'm moving onto Python. I have no idea about the environment needed for it. I could use some suggestions on it for me to get started. </p>
1
2009-08-05T05:47:52Z
1,231,931
<p>I use gvim with some plugin in order to have better support for python.</p> <p>If you like IDE, look at <a href="http://www.wingware.com/" rel="nofollow">wing IDE</a> wich is the best I have tested so far. Especially the debuger included is really helpful.</p>
1
2009-08-05T08:44:06Z
[ "python", "ide" ]
Python Multiprocessing Exit Elegantly How?
1,231,599
<pre><code>import multiprocessing import time class testM(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) self.exit = False def run(self): while not self.exit: pass print "You exited!" return def shutdown(self): self.exit = True print "SHUTDOWN initiated" def dostuff(self): print "haha", self.exit a = testM() a.start() time.sleep(3) a.shutdown() time.sleep(3) print a.is_alive() a.dostuff() exit() </code></pre> <p>I am just wondering how come the code above doesn't really print "you exited". What am I doing wrong? if so, may someone point me out the correct way to exit gracefully? (I am not referring to process.terminate or kill)</p>
30
2009-08-05T07:07:23Z
1,231,648
<p>The reason you are not seeing this happen is because you are not communicating with the subprocess. You are trying to use a local variable (local to the parent process) to signal to the child that it should shutdown.</p> <p>Take a look at the information on <a href="http://docs.python.org/library/multiprocessing.html#synchronization-between-processes%5D">synchonization primatives</a>. You need to setup a signal of some sort that can be referenced in both processes. Once you have this you should be able to flick the switch in the parent process and wait for the child to die.</p> <p>Try the following code:</p> <pre><code>import multiprocessing import time class MyProcess(multiprocessing.Process): def __init__(self, ): multiprocessing.Process.__init__(self) self.exit = multiprocessing.Event() def run(self): while not self.exit.is_set(): pass print "You exited!" def shutdown(self): print "Shutdown initiated" self.exit.set() if __name__ == "__main__": process = MyProcess() process.start() print "Waiting for a while" time.sleep(3) process.shutdown() time.sleep(3) print "Child process state: %d" % process.is_alive() </code></pre>
34
2009-08-05T07:23:47Z
[ "python", "multiprocessing" ]
How to get a reference to the module something is implemented in from within that implementation?
1,231,631
<p>Say I have the following code:</p> <pre><code> from foo.bar import Foo from foo.foo import Bar __all__ = ["Foo", "Bar"] def iterate_over_all(): ... </code></pre> <p>How can I implement code in the function <code>iterate_over_all()</code> that can dynamically obtain references to whatever is referenced in <code>__all__</code> the module where the function is implemented? IE: in <code>iterate_over_all()</code> I want to work with <code>foo.bar.Foo</code> and <code>foo.foo.Bar</code>.</p>
0
2009-08-05T07:19:25Z
1,231,705
<p><code>eval</code> is one way. e.g. <code>eval("Foo")</code> would give you <code>Foo</code>. However you can also just put Foo and Bar directly in your list e.g. <code>__all__ = [Foo, Bar]</code> </p> <p>It would depend on where the contents of <code>__all__</code> is coming from in your actual program.</p>
0
2009-08-05T07:40:21Z
[ "python", "module" ]
How to get a reference to the module something is implemented in from within that implementation?
1,231,631
<p>Say I have the following code:</p> <pre><code> from foo.bar import Foo from foo.foo import Bar __all__ = ["Foo", "Bar"] def iterate_over_all(): ... </code></pre> <p>How can I implement code in the function <code>iterate_over_all()</code> that can dynamically obtain references to whatever is referenced in <code>__all__</code> the module where the function is implemented? IE: in <code>iterate_over_all()</code> I want to work with <code>foo.bar.Foo</code> and <code>foo.foo.Bar</code>.</p>
0
2009-08-05T07:19:25Z
1,232,214
<p>You can easily index with the strings from <em>__all__</em> into the module's <em>__dict__</em>:</p> <pre><code>__dict__["Foo"] == foo.bar.Foo # -&gt; True </code></pre>
0
2009-08-05T09:48:36Z
[ "python", "module" ]
How to get a reference to the module something is implemented in from within that implementation?
1,231,631
<p>Say I have the following code:</p> <pre><code> from foo.bar import Foo from foo.foo import Bar __all__ = ["Foo", "Bar"] def iterate_over_all(): ... </code></pre> <p>How can I implement code in the function <code>iterate_over_all()</code> that can dynamically obtain references to whatever is referenced in <code>__all__</code> the module where the function is implemented? IE: in <code>iterate_over_all()</code> I want to work with <code>foo.bar.Foo</code> and <code>foo.foo.Bar</code>.</p>
0
2009-08-05T07:19:25Z
1,232,542
<p>Would this do?</p> <pre><code>def iterate_over_all(): for name in __all__: value = globals()[name] yield value # or do whatever with it </code></pre>
2
2009-08-05T11:03:05Z
[ "python", "module" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
1,231,745
<p>There are <a href="http://thingsilearned.com/2009/04/13/easy_install-uninstalling/">several</a> sources on the net suggesting a hack by reinstalling the package with the -m option and then just removing the .egg file in lib/ and the binaries in bin/. Also, discussion about this setuptools issue can be found on the python bug tracker as setuptools <a href="http://bugs.python.org/setuptools/issue21">issue 21</a>.</p> <p>Edit: Added the link to the python bugtracker.</p>
27
2009-08-05T07:53:43Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
1,233,261
<p>If the problem is a serious-enough annoyance to you, you might consider <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>. It allows you to create an environment that encapsulates python libraries. You install packages there rather than in the global site-packages directory. Any scripts you run in that environment have access to those packages (and optionally, your global ones as well). I use this a lot when evaluating packages that I am not sure I want/need to install globally. If you decide you don't need the package, it's easy enough to just blow that virtual environment away. It's pretty easy to use. Make a new env:</p> <pre><code>$&gt;virtualenv /path/to/your/new/ENV </code></pre> <p>virtual_envt installs setuptools for you in the new environment, so you can do:</p> <pre><code>$&gt;ENV/bin/easy_install </code></pre> <p>You can even create your own boostrap scripts that setup your new environment. So, with one command, you can create a new virtual env with, say, python 2.6, psycopg2 and django installed by default (you can can install an env-specific version of python if you want).</p>
23
2009-08-05T13:28:37Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
1,233,282
<p>To uninstall an <code>.egg</code> you need to <code>rm -rf</code> the egg (it might be a directory) and remove the matching line from <code>site-packages/easy-install.pth</code></p>
164
2009-08-05T13:31:53Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
3,297,522
<p>try</p> <pre><code>$ easy_install -m [PACKAGE] </code></pre> <p>then</p> <pre><code>$ rm -rf .../python2.X/site-packages/[PACKAGE].egg </code></pre>
14
2010-07-21T08:40:36Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
3,297,564
<p><a href="http://pypi.python.org/pypi/pip/">pip</a>, an alternative to setuptools/easy_install, provides an "uninstall" command. </p> <p>Install pip according to the <a href="http://pip.readthedocs.org/en/stable/installing/">installation instructions</a>:</p> <pre><code>$ wget https://bootstrap.pypa.io/get-pip.py $ python get-pip.py </code></pre> <p>Then you can use <code>pip uninstall</code> to remove packages installed with <code>easy_install</code></p>
536
2010-07-21T08:47:21Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
3,454,856
<p>Official(?) instructions: <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages" rel="nofollow">http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages</a></p> <blockquote> <p>If you have replaced a package with another version, then you can just delete the package(s) you don't need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).</p> <p>If you want to delete the currently installed version of a package (or all versions of a package), you should first run:</p> <pre><code>easy_install -mxN PackageName </code></pre> <p>This will ensure that Python doesn't continue to search for a package you're planning to remove. After you've done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.</p> </blockquote>
13
2010-08-11T02:28:14Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
4,320,437
<p>To list installed Python packages, you can use <code>yolk -l</code>. You'll need to use <code>easy_install yolk</code> first though.</p>
6
2010-12-01T01:25:11Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
4,321,319
<p>Came across this question, while trying to uninstall the many random Python packages installed over time.</p> <p>Using information from this thread, this is what I came up with:</p> <pre><code>cat package_list | xargs -n1 sudo pip uninstall -y </code></pre> <p>The <code>package_list</code> is cleaned up (awk) from a <code>pip freeze</code> in a virtualenv.</p> <p>To remove <em>almost</em> all Python packages:</p> <pre><code>yolk -l | cut -f 1 -d " " | grep -v "setuptools|pip|ETC.." | xargs -n1 pip uninstall -y </code></pre>
5
2010-12-01T04:56:40Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
5,677,700
<p>I ran into the same problem on my MacOS X Leopard 10.6.blah.</p> <p>Solution is to make sure you're calling the MacPorts Python:</p> <pre><code>sudo port install python26 sudo port install python_select sudo python_select python26 sudo port install py26-mysql </code></pre> <p>Hope this helps.</p>
2
2011-04-15T13:45:56Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
6,263,564
<p>First you have to run this command:</p> <pre><code>$ easy_install -m [PACKAGE] </code></pre> <p>It removes all dependencies of the package.</p> <p>Then remove egg file of that package:</p> <pre><code>$ sudo rm -rf /usr/local/lib/python2.X/site-packages/[PACKAGE].egg </code></pre>
128
2011-06-07T09:56:47Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
8,718,590
<p>All the info is in the other answers, but none summarizes <em>both</em> your requests or seem to make things needlessly complex:</p> <ul> <li><p>For your removal needs use:</p> <pre><code>pip uninstall &lt;package&gt; </code></pre> <p>(install using <code>easy_install pip</code>)</p></li> <li><p>For your 'list installed packages' needs either use: </p> <pre><code>pip freeze </code></pre> <p>Or:</p> <pre><code>yolk -l </code></pre> <p>which can output more package details.</p> <p>(Install via <code>easy_install yolk</code> or <code>pip install yolk</code>)</p></li> </ul>
49
2012-01-03T21:04:44Z
[ "python", "packages", "setuptools", "easy-install" ]
How do I remove packages installed with Python's easy_install?
1,231,688
<p>Python's <code>easy_install</code> makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.</p> <p>What is the best way of finding out what's installed, and what is the preferred way of removing installed packages? Are there any files that need to be updated if I remove packages manually (e.g. by <code>rm /usr/local/lib/python2.6/dist-packages/my_installed_pkg.egg</code> or similar)?</p>
572
2009-08-05T07:33:13Z
26,481,670
<p>For me only deleting this file : easy-install.pth worked, rest pip install django==1.3.7 </p>
1
2014-10-21T08:00:54Z
[ "python", "packages", "setuptools", "easy-install" ]
python String Formatting Operations
1,231,784
<p>Faulty code:</p> <pre><code>pos_1 = 234 pos_n = 12890 min_width = len(str(pos_n)) # is there a better way for this? # How can I use min_width as the minimal width of the two conversion specifiers? # I don't understand the Python documentation on this :( raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n} </code></pre> <p>Required output:</p> <pre><code>... from 00234 to 12890 ... ______________________EDIT______________________ </code></pre> <p>New code:</p> <pre><code># I changed my code according the second answer pos_1 = 10234 # can be any value between 1 and pos_n pos_n = 12890 min_width = len(str(pos_n)) raw_str = '... from % *d to % *d ...' % (min_width, pos_1, min_width, pos_n) </code></pre> <p>New Problem:</p> <p>There is one extra whitespace (I marked it *_*) in front of the integer values, for intigers with *min_width* digits:</p> <pre><code>print raw_str ... from _10234 to _12890 ... </code></pre> <p>Also, I wonder if there is a way to add Mapping keys? </p>
0
2009-08-05T08:04:10Z
1,231,809
<pre><code>"1234".rjust(13,"0") </code></pre> <p>Should do what you need</p> <p>addition:</p> <pre><code>a = ["123", "12"] max_width = sorted([len(i) for i in a])[-1] </code></pre> <p>put max_width instead of 13 above and put all your strings in a single array a (which seems to me much more usable than having a stack of variables).</p> <p>additional nastyness: (Using array of numbers to get closer to your question.)</p> <pre><code>a = [123, 33, 0 ,223] [str(x).rjust(sorted([len(str(i)) for i in a])[-1],"0") for x in a] </code></pre> <p>Who said Perl is the only language to easily produce braindumps in? If regexps are the godfather of complex code, then list comprehension is the godmother. </p> <p>(I am relatively new to python and rather convinced that there must be a max-function on arrays somewhere, which would reduce above complexity. .... OK, checked, there is. Pity, have to reduce the example.)</p> <pre><code>[str(x).rjust(max([len(str(i) for i in a]),"0") for x in a] </code></pre> <p>And please observe below comments on "not putting calculation of an invariant (the max value) inside the outer list comprehension". </p>
1
2009-08-05T08:11:14Z
[ "python", "string", "formatting" ]
python String Formatting Operations
1,231,784
<p>Faulty code:</p> <pre><code>pos_1 = 234 pos_n = 12890 min_width = len(str(pos_n)) # is there a better way for this? # How can I use min_width as the minimal width of the two conversion specifiers? # I don't understand the Python documentation on this :( raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n} </code></pre> <p>Required output:</p> <pre><code>... from 00234 to 12890 ... ______________________EDIT______________________ </code></pre> <p>New code:</p> <pre><code># I changed my code according the second answer pos_1 = 10234 # can be any value between 1 and pos_n pos_n = 12890 min_width = len(str(pos_n)) raw_str = '... from % *d to % *d ...' % (min_width, pos_1, min_width, pos_n) </code></pre> <p>New Problem:</p> <p>There is one extra whitespace (I marked it *_*) in front of the integer values, for intigers with *min_width* digits:</p> <pre><code>print raw_str ... from _10234 to _12890 ... </code></pre> <p>Also, I wonder if there is a way to add Mapping keys? </p>
0
2009-08-05T08:04:10Z
1,231,833
<pre><code>pos_1 = 234 pos_n = 12890 min_width = len(str(pos_n)) raw_str = '... from %0*d to %0*d ...' % (min_width, pos_1, min_width, pos_n) </code></pre>
2
2009-08-05T08:18:58Z
[ "python", "string", "formatting" ]
python String Formatting Operations
1,231,784
<p>Faulty code:</p> <pre><code>pos_1 = 234 pos_n = 12890 min_width = len(str(pos_n)) # is there a better way for this? # How can I use min_width as the minimal width of the two conversion specifiers? # I don't understand the Python documentation on this :( raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n} </code></pre> <p>Required output:</p> <pre><code>... from 00234 to 12890 ... ______________________EDIT______________________ </code></pre> <p>New code:</p> <pre><code># I changed my code according the second answer pos_1 = 10234 # can be any value between 1 and pos_n pos_n = 12890 min_width = len(str(pos_n)) raw_str = '... from % *d to % *d ...' % (min_width, pos_1, min_width, pos_n) </code></pre> <p>New Problem:</p> <p>There is one extra whitespace (I marked it *_*) in front of the integer values, for intigers with *min_width* digits:</p> <pre><code>print raw_str ... from _10234 to _12890 ... </code></pre> <p>Also, I wonder if there is a way to add Mapping keys? </p>
0
2009-08-05T08:04:10Z
1,232,559
<p>Concerning using a mapping type as second argument to '%':</p> <p>I presume you mean something like that <em>'%(mykey)d' % {'mykey': 3}</em>, right?! I think you cannot use this if you use the "%*d" syntax, since there is no way to provide the necessary width arguments with a dict.</p> <p>But why don't you generate your format string dynamically:</p> <pre><code>fmt = '... from %%%dd to %%%dd ...' % (min_width, min_width) # assuming min_width is e.g. 7 fmt would be: '... from %7d to %7d ...' raw_string = fmt % pos_values_as_tuple_or_dict </code></pre> <p>This way you decouple the width issue from the formatting of the actual values, and you can use a tuple or a dict for the latter, as it suits you.</p>
1
2009-08-05T11:05:59Z
[ "python", "string", "formatting" ]
Classes nested in functions and attribute lookup
1,231,814
<p>The following works Ok, i.e. it doesn't give any errors:</p> <pre><code>def foo(arg): class Nested(object): x = arg foo('hello') </code></pre> <p>But the following throws an exception:</p> <pre><code>def foo(arg): class Nested(object): arg = arg # note that names are the same foo('hello') </code></pre> <p>Traceback:</p> <pre><code>Traceback (most recent call last): File "test.py", line 6, in &lt;module&gt; foo('hello') File "test.py", line 3, in foo class Nested(object): File "test.py", line 4, in Nested arg = arg NameError: name 'arg' is not defined </code></pre> <p>I can't understand the reason of such behavior. Could anybody explain?</p>
3
2009-08-05T08:11:48Z
1,231,888
<p>The <code>arg</code> property shadows the <code>arg</code> function argument (inner scoping)</p> <pre><code>def foo(arg): class Nested(object): arg = arg # you try to read the `arg` property which isn't initialized </code></pre> <p><br> You get the same error if you type <code>i = i</code> in the interpreter window without having initialized the <code>i</code> variable.</p>
4
2009-08-05T08:32:45Z
[ "python", "class", "nested" ]
Classes nested in functions and attribute lookup
1,231,814
<p>The following works Ok, i.e. it doesn't give any errors:</p> <pre><code>def foo(arg): class Nested(object): x = arg foo('hello') </code></pre> <p>But the following throws an exception:</p> <pre><code>def foo(arg): class Nested(object): arg = arg # note that names are the same foo('hello') </code></pre> <p>Traceback:</p> <pre><code>Traceback (most recent call last): File "test.py", line 6, in &lt;module&gt; foo('hello') File "test.py", line 3, in foo class Nested(object): File "test.py", line 4, in Nested arg = arg NameError: name 'arg' is not defined </code></pre> <p>I can't understand the reason of such behavior. Could anybody explain?</p>
3
2009-08-05T08:11:48Z
1,231,892
<p>If you try and assign to a variable within a function, Python assumes that variable is local to that function. So by trying to assign arg to the value of itself, you are implicitly declaring it as a local variable.</p>
3
2009-08-05T08:33:46Z
[ "python", "class", "nested" ]
Classes nested in functions and attribute lookup
1,231,814
<p>The following works Ok, i.e. it doesn't give any errors:</p> <pre><code>def foo(arg): class Nested(object): x = arg foo('hello') </code></pre> <p>But the following throws an exception:</p> <pre><code>def foo(arg): class Nested(object): arg = arg # note that names are the same foo('hello') </code></pre> <p>Traceback:</p> <pre><code>Traceback (most recent call last): File "test.py", line 6, in &lt;module&gt; foo('hello') File "test.py", line 3, in foo class Nested(object): File "test.py", line 4, in Nested arg = arg NameError: name 'arg' is not defined </code></pre> <p>I can't understand the reason of such behavior. Could anybody explain?</p>
3
2009-08-05T08:11:48Z
1,231,897
<p>It is due to Python's scoping rules:</p> <pre><code>def foo(arg): # (1) class Nested(object): arg = arg # (2) </code></pre> <p>(2) defines a new 'arg' name in the class' namespace, which opaques the value of the other 'arg' in the outer namespace (1).</p> <p>However, (2) is unnecessary and the following is completely valid:</p> <pre><code>def foo(arg): class Nested(object): def message(self): print arg return Nested() nested = foo('hello') nested.message() </code></pre> <p>(prints <code>hello</code>)</p>
2
2009-08-05T08:35:10Z
[ "python", "class", "nested" ]
How does mercurial work without Python installed?
1,231,853
<p>I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.</p> <p>How does it work?</p> <p>Also, is it possible to force Mercurial run on IronPython and will it be compatible?</p> <p>Thank you.</p>
8
2009-08-05T08:22:55Z
1,231,883
<p>Mercurial bundles the necessary python binaries within it, I believe.</p>
3
2009-08-05T08:31:04Z
[ "python", "mercurial", "ironpython" ]
How does mercurial work without Python installed?
1,231,853
<p>I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.</p> <p>How does it work?</p> <p>Also, is it possible to force Mercurial run on IronPython and will it be compatible?</p> <p>Thank you.</p>
8
2009-08-05T08:22:55Z
1,232,605
<p>Since there is a "library.zip"(9MB), Mercurial's Windows binary package maybe made by <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>, py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation. </p>
7
2009-08-05T11:16:36Z
[ "python", "mercurial", "ironpython" ]
How does mercurial work without Python installed?
1,231,853
<p>I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.</p> <p>How does it work?</p> <p>Also, is it possible to force Mercurial run on IronPython and will it be compatible?</p> <p>Thank you.</p>
8
2009-08-05T08:22:55Z
1,232,767
<p>The Mercurial windows installer is packaged using <a href="http://www.py2exe.org/">py2exe</a>. This places the python interpreter as a DLL inside of a file called "library.zip". </p> <p>On my machine, it is placed in "C:\Program Files\TortoiseHg\library.zip"</p> <p>This zip file also contains the python libraries that are required by mercurial. </p> <p>For a detailed description of how mercurial is packaged for windows, see the developer page describing <a href="http://mercurial.selenic.com/wiki/BuildingWindowsInstaller">building windows installer</a>.</p>
17
2009-08-05T11:52:12Z
[ "python", "mercurial", "ironpython" ]
How does mercurial work without Python installed?
1,231,853
<p>I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.</p> <p>How does it work?</p> <p>Also, is it possible to force Mercurial run on IronPython and will it be compatible?</p> <p>Thank you.</p>
8
2009-08-05T08:22:55Z
1,283,908
<p>Others have answered the first question -- let me give a guess about the second part. </p> <p>Mercurial will normally use some C extensions for speed. You cannot use those with IronPython.</p> <p>But we also ship pure Python versions of these modules, and depending on how much IronPython implements of a standard Python 2.4 environment, those modules could be compatible. I have seen reports on IRC about Jython (the Java port of Python) being able to do a few operations using the pure modules. You should download Mercurial and take a look at the <code>mercurial/pure</code> folder. These modules simply has to be moved up one directory level to be found, the <code>setup.py</code> script can do this if you pass the <code>--pure</code> flag. Please see its source or come talk with us on the Mercurial mailinglist/IRC.</p>
6
2009-08-16T09:47:36Z
[ "python", "mercurial", "ironpython" ]
MySQL LOAD DATA LOCAL INFILE example in python?
1,231,900
<p>I am looking for a syntax definition, example, sample code, wiki, etc. for executing a LOAD DATA LOCAL INFILE command from python.</p> <p>I believe I can use mysqlimport as well if that is available, so any feedback (and code snippet) on which is the better route, is welcome. A Google search is not turning up much in the way of current info</p> <p>The goal in either case is the same: Automate loading hundreds of files with a known naming convention &amp; date structure, into a single MySQL table.</p> <p>David</p>
10
2009-08-05T08:36:26Z
1,234,705
<p>Well, using python's MySQLdb, I use this:</p> <pre><code>connection = MySQLdb.Connect(host='**', user='**', passwd='**', db='**') cursor = connection.cursor() query = "LOAD DATA INFILE '/path/to/my/file' INTO TABLE sometable FIELDS TERMINATED BY ';' ENCLOSED BY '\"' ESCAPED BY '\\\\'" cursor.execute( query ) connection.commit() </code></pre> <p>replacing the host/user/passwd/db as appropriate for your needs. This is based on the MySQL docs <a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html">here</a>, The exact LOAD DATA INFILE statement would depend on your specific requirements etc (note the FIELDS TERMINATED BY, ENCLOSED BY, and ESCAPED BY statements will be specific to the type of file you are trying to read in). </p>
18
2009-08-05T17:46:39Z
[ "python", "mysql", "load-data-infile" ]
MySQL LOAD DATA LOCAL INFILE example in python?
1,231,900
<p>I am looking for a syntax definition, example, sample code, wiki, etc. for executing a LOAD DATA LOCAL INFILE command from python.</p> <p>I believe I can use mysqlimport as well if that is available, so any feedback (and code snippet) on which is the better route, is welcome. A Google search is not turning up much in the way of current info</p> <p>The goal in either case is the same: Automate loading hundreds of files with a known naming convention &amp; date structure, into a single MySQL table.</p> <p>David</p>
10
2009-08-05T08:36:26Z
2,802,111
<p>You can also get the results for the import by adding the following lines after your query:</p> <pre><code>results = connection.info() </code></pre>
0
2010-05-10T11:09:23Z
[ "python", "mysql", "load-data-infile" ]
how to overwrite User model
1,231,943
<p>I don't like models.User, but I like Admin view, and I will keep admin view in my application. </p> <p>How to overwirte models.User ? Make it just look like following:</p> <pre><code>from django.contrib.auth.models import User class ShugeUser(User) username = EmailField(uniqute=True, verbose_name='EMail as your username', ...) email = CharField(verbose_name='Nickname, ...) User = ShugeUser </code></pre>
0
2009-08-05T08:47:59Z
1,232,099
<p>That isn't possible right now. If all you want is to use the email address as the username, you could write a <a href="http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend" rel="nofollow">custom auth backend</a> that checks if the email/password combination is correct instead of the username/password combination (<a href="http://www.djangosnippets.org/snippets/74/" rel="nofollow">here</a>'s an example from djangosnippets.org).</p> <p>If you want more, you'll have to hack up Django pretty badly, or wait until Django better supports subclassing of the User model (according to <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/b016acdd8d128bd1/c18c515fe9903522?lnk=raot" rel="nofollow">this conversation</a> on the django-users mailing list, it could happen as soon as Django 1.2, but don't count on it).</p>
4
2009-08-05T09:23:08Z
[ "python", "django", "django-models", "django-admin" ]
how to overwrite User model
1,231,943
<p>I don't like models.User, but I like Admin view, and I will keep admin view in my application. </p> <p>How to overwirte models.User ? Make it just look like following:</p> <pre><code>from django.contrib.auth.models import User class ShugeUser(User) username = EmailField(uniqute=True, verbose_name='EMail as your username', ...) email = CharField(verbose_name='Nickname, ...) User = ShugeUser </code></pre>
0
2009-08-05T08:47:59Z
1,237,517
<p>The answer above is good and we use it on several sites successfully. I want to also point out though that many times people want to change the User model they are adding more information fields. This can be accommodated with the built in user profile support in the the contrib admin module.</p> <p>You access the profile by utilizing the get_profile() method of a User object.</p> <p>Related documentation is available <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users" rel="nofollow">here.</a></p>
0
2009-08-06T08:06:24Z
[ "python", "django", "django-models", "django-admin" ]
How can I use a class instance variable as an argument for a method decorator in Python?
1,231,950
<p>How can I use a class instance variable as an argument for a method decorator in Python? The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decorator.</p> <pre><code>def decorator1(arg1): def wrapper(function): print "decorator argument: %s" % arg1 return function return wrapper class Foo(object): def __init__(self, arg1): self.var1 = arg1 @decorator1(self.var1) def method1(self): print "method1" foo = Foo("abc") foo.method1() </code></pre>
4
2009-08-05T08:49:25Z
1,232,003
<p>The decorator is executed when the class is defined, so you can't pass an instance variable to it.</p>
0
2009-08-05T08:59:54Z
[ "python", "decorator" ]
How can I use a class instance variable as an argument for a method decorator in Python?
1,231,950
<p>How can I use a class instance variable as an argument for a method decorator in Python? The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decorator.</p> <pre><code>def decorator1(arg1): def wrapper(function): print "decorator argument: %s" % arg1 return function return wrapper class Foo(object): def __init__(self, arg1): self.var1 = arg1 @decorator1(self.var1) def method1(self): print "method1" foo = Foo("abc") foo.method1() </code></pre>
4
2009-08-05T08:49:25Z
1,232,055
<p>It's not going to work; the decorator is called during <em>class creation</em> time, which is long before an instance is created (<em>if</em> that ever happens). So if your "decorator" needs the instance, you have to do the "decorating" at instantiation time:</p> <pre><code>def get_decorator(arg1): def my_decorator(function): print "get_decorator argument: %s" % arg1 return function return my_decorator class Foo(object): def __init__(self, arg1): self.var1 = arg1 self.method1 = get_decorator(self.var1)(self.method1) def method1(self): print "method1" foo = Foo("abc") foo.method1() </code></pre> <p>Note that I changed the function names according to their meanings; the actual "decorator", i.e. the function that (potentially) modifies the method, is <code>wrapper</code> in your case, not <code>decorator1</code>.</p>
7
2009-08-05T09:11:19Z
[ "python", "decorator" ]
How can I use a class instance variable as an argument for a method decorator in Python?
1,231,950
<p>How can I use a class instance variable as an argument for a method decorator in Python? The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decorator.</p> <pre><code>def decorator1(arg1): def wrapper(function): print "decorator argument: %s" % arg1 return function return wrapper class Foo(object): def __init__(self, arg1): self.var1 = arg1 @decorator1(self.var1) def method1(self): print "method1" foo = Foo("abc") foo.method1() </code></pre>
4
2009-08-05T08:49:25Z
1,232,295
<p>Your “warper” function is actually a decorator, rather than a warper. Your “decorator1” function is a decorator constructor. If you want to have access to self.var1 in runtime you have to make a warper not decorator: </p> <pre><code>def decorator(function): def wrapper(self,*args,**kwargs): print "Doing something with self.var1==%s" % self.var1 return function(self,*args,**kwargs) return wrapper class Foo(object): def __init__(self, arg1): self.var1 = arg1 @decorator def method1(self): print "method1" foo = Foo("abc") foo.method1() </code></pre> <p>If you want to have more generic decorator, it's better idea to declare a callable class: </p> <pre><code>class decorator: def __init__(self,varname): self.varname = varname def __call__(self,function): varname=self.varname def wrapper(self,*args,**kwargs): print "Doing something with self.%s==%s" % (varname,getattr(self,varname)) return function(self,*args,**kwargs) return wrapper </code></pre> <p>Using:</p> <pre><code> @decorator("var1") </code></pre>
4
2009-08-05T10:06:42Z
[ "python", "decorator" ]
How can I use a class instance variable as an argument for a method decorator in Python?
1,231,950
<p>How can I use a class instance variable as an argument for a method decorator in Python? The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decorator.</p> <pre><code>def decorator1(arg1): def wrapper(function): print "decorator argument: %s" % arg1 return function return wrapper class Foo(object): def __init__(self, arg1): self.var1 = arg1 @decorator1(self.var1) def method1(self): print "method1" foo = Foo("abc") foo.method1() </code></pre>
4
2009-08-05T08:49:25Z
1,235,366
<p>Here's how we used to do this in the olden days.</p> <pre><code>class Foo(object): def __init__(self, arg1): self.var1 = arg1 def method1(self): self.lock() try: self.do_method1() except Exception: pass # Might want to log this finally: self.unlock() def do_method1(self): print "method1" def lock(self): print "locking: %s" % self.arg1 def unlock(self): print "unlocking: %s" % self.arg1 </code></pre> <p>Now, a subclass only needs to o override <code>do_method1</code> to get the benefits of the "wrapping". Done the old way, without any <code>with</code> statement.</p> <p>Yes, it's long-winded. However, it doesn't involve any magic, either.</p>
0
2009-08-05T19:49:45Z
[ "python", "decorator" ]
setuptools / dpkg-buildpackage: Refuse to build if nosetests fail
1,231,958
<p>I have a very simple python package that I build into debian packages using setuptools, cdbs and pycentral:</p> <p>setup.py:</p> <pre><code>from setuptools import setup setup(name='PHPSerialize', version='1.0', py_modules=['PHPSerialize'], test_suite = 'nose.collector' ) </code></pre> <p>debian/rules:</p> <pre><code>#!/usr/bin/make -f DEB_PYTHON_SYSTEM = pycentral include /usr/share/cdbs/1/rules/debhelper.mk include /usr/share/cdbs/1/class/python-distutils.mk </code></pre> <p>Now, is there an easy way to make dpkg-buildpackage execute the unit tests and refuse to create the .deb if the test suite fails?</p>
3
2009-08-05T08:50:03Z
1,420,883
<p>Try</p> <pre><code>build/yourpackage:: nosetests </code></pre>
2
2009-09-14T10:58:40Z
[ "python", "debian", "setuptools", "nose", "cdbs" ]
Django - Following a foreign key relationship (i.e JOIN in SQL)
1,232,172
<p>Busy playing with django, but one thing seems to be tripping me up is following a foreign key relationship. Now, I have a ton of experience in writing SQL, so i could prob. return the result if the ORM was not there. </p> <p>Basically this is the SQL query i want returned</p> <pre><code>Select table1.id table1.text table1.user table2.user_name table2.url from table1, table2 where table1.user_id = table2.id </code></pre> <p>My model classes have been defined as:</p> <pre><code>class Table1(models.Model): #other fields text = models.TextField() user = models.ForeignKey('table2') class Table2(models.Model): # other fields user_name = models.CharField(max_length=50) url = models.URLField(blank=True, null=True) </code></pre> <p>I have been through the documentation and reference for querysets, models and views on the django website. But its still not clear on how to do this. </p> <p>I have also setup the url with a generic list view, but would like to access the *user_name* field from the second table in the template. I tried *select_related* in urls.py and also via the shell but it does not seem to work. See examples below.</p> <p>config in urls</p> <pre><code>url(r'^$','django.views.generic.list_detail.object_list', { 'queryset': Table1.objects.select_related() }), </code></pre> <p>At the shell</p> <pre><code>&gt;&gt;&gt; a = Table1.objects.select_related().get(id=1) &gt;&gt;&gt; a.id 1 &gt;&gt;&gt; a.user_name Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'Table1' object has no attribute 'user_name' </code></pre> <p>So basically, </p> <ul> <li>What am i doing wrong? </li> <li>Am i missing something? </li> <li>What's the best way to pass fields from two tables in the same queryset to your template (So fields from both tables can be accessed) </li> <li>Can this be done with generic views?</li> </ul>
0
2009-08-05T09:40:01Z
1,232,221
<p>Something like this should work:</p> <pre><code>u = Table1.objects.get(id=1) print u.id print u.user.user_name </code></pre> <p>If you want to follow a foreign key, you must do it explicitly. You don't get an automatic join, when you retrieve an object from Table1. You will only get an object from Table2, when you access a foreign key field, which is user in this example</p>
3
2009-08-05T09:49:30Z
[ "python", "django", "django-models", "django-urls" ]
Django - Following a foreign key relationship (i.e JOIN in SQL)
1,232,172
<p>Busy playing with django, but one thing seems to be tripping me up is following a foreign key relationship. Now, I have a ton of experience in writing SQL, so i could prob. return the result if the ORM was not there. </p> <p>Basically this is the SQL query i want returned</p> <pre><code>Select table1.id table1.text table1.user table2.user_name table2.url from table1, table2 where table1.user_id = table2.id </code></pre> <p>My model classes have been defined as:</p> <pre><code>class Table1(models.Model): #other fields text = models.TextField() user = models.ForeignKey('table2') class Table2(models.Model): # other fields user_name = models.CharField(max_length=50) url = models.URLField(blank=True, null=True) </code></pre> <p>I have been through the documentation and reference for querysets, models and views on the django website. But its still not clear on how to do this. </p> <p>I have also setup the url with a generic list view, but would like to access the *user_name* field from the second table in the template. I tried *select_related* in urls.py and also via the shell but it does not seem to work. See examples below.</p> <p>config in urls</p> <pre><code>url(r'^$','django.views.generic.list_detail.object_list', { 'queryset': Table1.objects.select_related() }), </code></pre> <p>At the shell</p> <pre><code>&gt;&gt;&gt; a = Table1.objects.select_related().get(id=1) &gt;&gt;&gt; a.id 1 &gt;&gt;&gt; a.user_name Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'Table1' object has no attribute 'user_name' </code></pre> <p>So basically, </p> <ul> <li>What am i doing wrong? </li> <li>Am i missing something? </li> <li>What's the best way to pass fields from two tables in the same queryset to your template (So fields from both tables can be accessed) </li> <li>Can this be done with generic views?</li> </ul>
0
2009-08-05T09:40:01Z
1,232,225
<p>select_related() do not add second table result directly to the query, it just "Loads" them, insead of giving to you lazily. You should only use it, when you are sure it can boost your site performance. To get second table you need to write</p> <pre><code>a.user.username </code></pre> <p>In Django to get related table you need to follow them through foreign-keys that you have designed. Query itself do not directly translate to SQL query, because it is "lazy". It will execute only SQL that you need and only when you need.</p> <p>If you have <code>select_related</code> SQL would have been executed at the moment when you do original query for <code>a</code>. But if you didn't have <code>select_related</code> then it would load DB only when you actually execute <code>a.user.username</code>. </p>
2
2009-08-05T09:50:13Z
[ "python", "django", "django-models", "django-urls" ]
How to make server accepting connections from multiple ports?
1,232,366
<p>How can I make a simple server(simple as in accepting a connection and print to terminal whatever is received) accept connection from multiple ports or a port range?</p> <p>Do I have to use multiple threads, one for each bind call. Or is there another solution?</p> <p>The simple server can look something like this.</p> <pre><code>def server(): import sys, os, socket port = 11116 host = '' backlog = 5 # Number of clients on wait. buf_size = 1024 try: listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listening_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) listening_socket.bind((host, port)) listening_socket.listen(backlog) except socket.error, (value, message): if listening_socket: listening_socket.close() print 'Could not open socket: ' + message sys.exit(1) while True: accepted_socket, adress = listening_socket.accept() data = accepted_socket.recv(buf_size) if data: accepted_socket.send('Hello, and goodbye.') accepted_socket.close() server() </code></pre> <p>EDIT: This is an example of how it can be done. Thanks everyone.</p> <pre><code>import socket, select def server(): import sys, os, socket port_wan = 11111 port_mob = 11112 port_sat = 11113 sock_lst = [] host = '' backlog = 5 # Number of clients on wait. buf_size = 1024 try: for item in port_wan, port_mob, port_sat: sock_lst.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) sock_lst[-1].setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) sock_lst[-1].bind((host, item)) sock_lst[-1].listen(backlog) except socket.error, (value, message): if sock_lst[-1]: sock_lst[-1].close() sock_lst = sock_lst[:-1] print 'Could not open socket: ' + message sys.exit(1) while True: read, write, error = select.select(sock_lst,[],[]) for r in read: for item in sock_lst: if r == item: accepted_socket, adress = item.accept() print 'We have a connection with ', adress data = accepted_socket.recv(buf_size) if data: print data accepted_socket.send('Hello, and goodbye.') accepted_socket.close() server() </code></pre>
4
2009-08-05T10:26:35Z
1,232,387
<p>I'm not a python guy, but the function you are interested in is "select". This will allow you to watch multiple sockets and breaks out when activity occurs on any one of them.</p> <p>Here's a <a href="http://code.activestate.com/recipes/531824/">python example that uses select</a>.</p>
6
2009-08-05T10:31:47Z
[ "python", "network-programming" ]
How to make server accepting connections from multiple ports?
1,232,366
<p>How can I make a simple server(simple as in accepting a connection and print to terminal whatever is received) accept connection from multiple ports or a port range?</p> <p>Do I have to use multiple threads, one for each bind call. Or is there another solution?</p> <p>The simple server can look something like this.</p> <pre><code>def server(): import sys, os, socket port = 11116 host = '' backlog = 5 # Number of clients on wait. buf_size = 1024 try: listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listening_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) listening_socket.bind((host, port)) listening_socket.listen(backlog) except socket.error, (value, message): if listening_socket: listening_socket.close() print 'Could not open socket: ' + message sys.exit(1) while True: accepted_socket, adress = listening_socket.accept() data = accepted_socket.recv(buf_size) if data: accepted_socket.send('Hello, and goodbye.') accepted_socket.close() server() </code></pre> <p>EDIT: This is an example of how it can be done. Thanks everyone.</p> <pre><code>import socket, select def server(): import sys, os, socket port_wan = 11111 port_mob = 11112 port_sat = 11113 sock_lst = [] host = '' backlog = 5 # Number of clients on wait. buf_size = 1024 try: for item in port_wan, port_mob, port_sat: sock_lst.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) sock_lst[-1].setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) sock_lst[-1].bind((host, item)) sock_lst[-1].listen(backlog) except socket.error, (value, message): if sock_lst[-1]: sock_lst[-1].close() sock_lst = sock_lst[:-1] print 'Could not open socket: ' + message sys.exit(1) while True: read, write, error = select.select(sock_lst,[],[]) for r in read: for item in sock_lst: if r == item: accepted_socket, adress = item.accept() print 'We have a connection with ', adress data = accepted_socket.recv(buf_size) if data: print data accepted_socket.send('Hello, and goodbye.') accepted_socket.close() server() </code></pre>
4
2009-08-05T10:26:35Z
1,232,676
<p>If you really wanted to be lazy (from a <em>programmer</em> standpoint, not an evaluation standpoint), you could set a timeout on your blocking read and just loop through all your sockets; if a timeout occurs, there wasn't any data available. Functionally, this is similar to what the <code>select</code> is doing, but it is taking that control away from the OS and putting it in your application.</p> <p>Of course, this implies that as your sleep time gets smaller, your program will approach 100% CPU usage, so you wouldn't use it on a production app. It's fine for a toy though.</p> <p>It would go something like this: (not tested)</p> <pre><code>def server(): import sys, os, socket port = 11116 host = '' backlog = 5 # Number of clients on wait. buf_size = 1024 NUM_SOCKETS = 10 START_PORT = 2000 try: socket.setdefaulttimeout(0.5) # raise a socket.timeout error after a half second listening_sockets = [] for i in range(NUM_SOCKETS): listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listening_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) listening_socket.bind((host, START_PORT + i)) listening_socket.listen(backlog) listening_sockets.append(listening_socket) except socket.error, (value, message): if listening_socket: listening_socket.close() print 'Could not open socket: ' + message sys.exit(1) while True: for sock in listening_sockets: try: accepted_socket, adress = sock_socket.accept() data = sock.recv(buf_size) if data: sock_socket.send('Hello, and goodbye.') sock.close() except socket.timeout: pass server() </code></pre>
1
2009-08-05T11:30:38Z
[ "python", "network-programming" ]
How to make server accepting connections from multiple ports?
1,232,366
<p>How can I make a simple server(simple as in accepting a connection and print to terminal whatever is received) accept connection from multiple ports or a port range?</p> <p>Do I have to use multiple threads, one for each bind call. Or is there another solution?</p> <p>The simple server can look something like this.</p> <pre><code>def server(): import sys, os, socket port = 11116 host = '' backlog = 5 # Number of clients on wait. buf_size = 1024 try: listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listening_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) listening_socket.bind((host, port)) listening_socket.listen(backlog) except socket.error, (value, message): if listening_socket: listening_socket.close() print 'Could not open socket: ' + message sys.exit(1) while True: accepted_socket, adress = listening_socket.accept() data = accepted_socket.recv(buf_size) if data: accepted_socket.send('Hello, and goodbye.') accepted_socket.close() server() </code></pre> <p>EDIT: This is an example of how it can be done. Thanks everyone.</p> <pre><code>import socket, select def server(): import sys, os, socket port_wan = 11111 port_mob = 11112 port_sat = 11113 sock_lst = [] host = '' backlog = 5 # Number of clients on wait. buf_size = 1024 try: for item in port_wan, port_mob, port_sat: sock_lst.append(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) sock_lst[-1].setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) sock_lst[-1].bind((host, item)) sock_lst[-1].listen(backlog) except socket.error, (value, message): if sock_lst[-1]: sock_lst[-1].close() sock_lst = sock_lst[:-1] print 'Could not open socket: ' + message sys.exit(1) while True: read, write, error = select.select(sock_lst,[],[]) for r in read: for item in sock_lst: if r == item: accepted_socket, adress = item.accept() print 'We have a connection with ', adress data = accepted_socket.recv(buf_size) if data: print data accepted_socket.send('Hello, and goodbye.') accepted_socket.close() server() </code></pre>
4
2009-08-05T10:26:35Z
19,575,664
<p>Since Python's got so much overhead, multithreaded apps are a big point of debate. Then there's the whole blocking-operation-GIL issue too. Luckily, the Python motto of <em>"If it seems like a big issue, someone's probably already come up with a solution (or several!)"</em> holds true here. My favorite solution tends to be the microthread model, specifically <a href="http://www.gevent.org/" rel="nofollow"><code>gevent</code></a>.</p> <p>Gevent is an event-driven single-thread concurrency library that handles most issues for you out of the box via monkey-patching. <code>gevent.monkey.patch_socket()</code> is a function that replaces the normal socket calls with non-blocking variants, polling and sleeping to allow the switch to other greenlets as need be. If you want more control, or it's not cutting it for you, you can easily manage the switching with select and <code>gevent</code>'s cooperative yield.</p> <p>Here's a simple example.</p> <pre><code>import gevent import socket import gevent.monkey; gevent.monkey.patch_socket() ALL_PORTS=[i for i in xrange(1024, 2048)] MY_ADDRESS = "127.0.0.1" def init_server_sock(port): try: s=socket.socket() s.setblocking(0) s.bind((MY_ADDRESS, port)) s.listen(5) return s except Exception, e: print "Exception creating socket at port %i: %s" % (port, str(e)) return False def interact(port, sock): while 1: try: csock, addr = sock.accept() except: continue data = "" while not data: try: data=csock.recv(1024) print data except: gevent.sleep(0) #this is the cooperative yield csock.send("Port %i got your message!" % port) csock.close() gevent.sleep(0) def main(): socks = {p:init_server_sock(p) for p in ALL_PORTS} greenlets = [] for k,v in socks.items(): if not v: socks.pop(k) else: greenlets.append(gevent.spawn(interact, k, v)) #now we've got our sockets, let's start accepting gevent.joinall(greenlets) </code></pre> <p>That would be a super-simple, completely untested server serving plain text <code>We got your message!</code> on ports 1024-2048. Involving select is a little harder; you'd have to have a manager greenlet which calls select and then starts up the active ones; but that's not massively hard to implement.</p> <p>Hope this helps! The nice part of the greenlet-based philosophy is that the select call is actually part of their hub module, as I recall, which will allow you to create a much more scalable and complex server more easily. It's pretty efficient too; there are a couple benchmarks floating around.</p>
2
2013-10-24T20:10:11Z
[ "python", "network-programming" ]
"Upload" a file from django shell
1,232,434
<p>I need to import some data from a excel file and a folder with images, every row in the excel describes every entry and have a list of filenames in the folder (photos related to the entry).</p> <p>I've done a script which creates every entry in the database and saves it trough the django shell, but i have no idea how to instantiate a InMemoryUploadedFile for save it with the model.</p> <p>In django 1.0 I had this small class which allowed me to do what i need, but with changes in django 1.1 it's not working any more.</p> <pre><code>class ImportFile(file): def __init__(self, *args, **kwargs): super(ImportFile, self).__init__(*args, **kwargs) self._file = self self.size = os.path.getsize(self.name) def __len__(self): return self.size def chunks(self, chunk_size=None): self._file.seek(0) yield self.read() </code></pre> <p>I was using this class with this piece of code to load images and saving them with the model instance.</p> <pre><code>for photo in photos: f = ImportFile(os.path.join(IMPORT_DIR, 'fotos', photo), 'r') p = Photo(name=f.name, image=f, parent=supply.supply_ptr) name = str(uuid1()) + os.path.splitext(f.name)[1] p.image.save(name, f) p.save() </code></pre> <p>The question is, how do I create a InMemoryUploadedFile or TemporaryUploadedFile from a file in python?, or any other thing that could work in this context.</p>
10
2009-08-05T10:41:15Z
1,232,567
<p>Finally I found the answer.</p> <pre><code>from django.core.files import File f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'r')) p = Photo(name=f.name, image=f, parent=supply.supply_ptr) name = str(uuid1()) + os.path.splitext(f.name)[1] p.image.save(name, f) p.save() </code></pre>
17
2009-08-05T11:07:11Z
[ "python", "django", "file", "import", "data-importer" ]
"Upload" a file from django shell
1,232,434
<p>I need to import some data from a excel file and a folder with images, every row in the excel describes every entry and have a list of filenames in the folder (photos related to the entry).</p> <p>I've done a script which creates every entry in the database and saves it trough the django shell, but i have no idea how to instantiate a InMemoryUploadedFile for save it with the model.</p> <p>In django 1.0 I had this small class which allowed me to do what i need, but with changes in django 1.1 it's not working any more.</p> <pre><code>class ImportFile(file): def __init__(self, *args, **kwargs): super(ImportFile, self).__init__(*args, **kwargs) self._file = self self.size = os.path.getsize(self.name) def __len__(self): return self.size def chunks(self, chunk_size=None): self._file.seek(0) yield self.read() </code></pre> <p>I was using this class with this piece of code to load images and saving them with the model instance.</p> <pre><code>for photo in photos: f = ImportFile(os.path.join(IMPORT_DIR, 'fotos', photo), 'r') p = Photo(name=f.name, image=f, parent=supply.supply_ptr) name = str(uuid1()) + os.path.splitext(f.name)[1] p.image.save(name, f) p.save() </code></pre> <p>The question is, how do I create a InMemoryUploadedFile or TemporaryUploadedFile from a file in python?, or any other thing that could work in this context.</p>
10
2009-08-05T10:41:15Z
24,699,274
<p>If using <strong>Python 3</strong> one adjustment is needed - change 'r' to 'rb': </p> <pre><code>f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'rb')) </code></pre>
2
2014-07-11T13:45:43Z
[ "python", "django", "file", "import", "data-importer" ]
Concatenating Dictionaries
1,232,904
<p>I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List_1[0] has corresponding data in List_2[0] and List_3[0], etc. I would like to turn these three lists into a dictionary inside a dictionary, with the values in List_1 being the primary keys. How do I do this while keeping everything in order?</p>
6
2009-08-05T12:22:03Z
1,232,938
<pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; b = [4,5,6] &gt;&gt;&gt; c = [7,8,9] &gt;&gt;&gt; dict(zip(a, zip(b, c))) {1: (4, 7), 2: (5, 8), 3: (6, 9)} </code></pre> <p>See the <a href="http://docs.python.org/library/functions.html#zip" rel="nofollow">documentation</a> for more info on <code>zip</code>.</p> <p>As lionbest points out below, you might want to look at <a href="http://docs.python.org/library/itertools.html" rel="nofollow"><code>itertools.izip()</code></a> if your input data is large. <code>izip</code> does essentially the same thing as <code>zip</code>, but it creates iterators instead of lists. This way, you don't create large temporary lists before creating the dictionary.</p>
13
2009-08-05T12:27:35Z
[ "python", "dictionary", "merge", "key" ]