title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Making a wxPython application multilingual
1,043,708
<p>I have a application written in wxPython which I want to make multilingual. Our options are</p> <ol> <li>using gettext <a href="http://docs.python.org/library/gettext.html" rel="nofollow">http://docs.python.org/library/gettext.html</a></li> <li>seprating out all UI text to a messages.py file, and using it to translate text </li> </ol> <p>I am very much inclined towards 2nd and I see no benefit in going gettext way, using 2nd way i can have all my messages at one place not in code, so If i need to change a message, code need not be changed, in case of gettext i may have confusing msg-constants as I will be just wrapping the orginal msg instead of converting it to a constant in messages.py</p> <p>basically instead of </p> <pre><code>wx.MessageBox(_("Hi stackoverflow!")) </code></pre> <p>I think</p> <pre><code>wx.MessageBox(messages.GREET_SO) </code></pre> <p>is better, so is there any advantage in gettext way and disadvantage 2nd way? and is there a 3rd way?</p> <p>edit: also gettext languages files seems to be too tied to code, and what happens if i want two messages same in english but different in french e.g. suppose french has more subtle translation for different scnerarios for english one is ok</p> <p>experience: I have already gone 2nd way, and i must say every application should try to extract UI text from code, it gives a chance to refactor, see where UI is creeping into model and where UI text can be improved, gettext in comparison is mechanic, doesn't gives any input for coder, and i think would be more difficult to maintain.</p> <p>and while creating a name for text e.g. PRINT_PROGRESS_MSG, gives a chance to see that at many places, same msg is being used slightly differently and can be merged into a single name, which later on will help when i need to change msg only once.</p> <p>Conclusion: I am still not sure of any advantage to use gettext and am using my own messages file. but I have selected the answer which at least explained few points why gettext can be beneficial. The final solution IMO is which takes the best from both ways i.e my own message identifier wrapped by gettext e.g</p> <pre><code>wx.MessageBox(_("GREET_SO")) </code></pre>
2
2009-06-25T12:49:08Z
1,069,016
<p>Gettext is the way to go, in your example you can also use gettext to "avoid storing the translations in the code":</p> <pre><code>wx.MessageBox(messages.GREET_SO) </code></pre> <p>might be the same with gettext as:</p> <pre><code>wx.MessageBox(_("GREET_SO")) or wx.MessageBox(_("messages.GREET_SO")) </code></pre> <p>Gettext is pretty much the standard for multilingual applications, and I'm pretty sure you'll benefit from using it in the future. Example, you can use Poedit (or other similar app) to assign translations to your collaborators or contributors and later on flag one or several messages as not properly translated. Also if there are missing / extra entries poedit will warn you. Don't fool yourself, gettext is the only proven reliable way to maintain translations.</p>
1
2009-07-01T12:58:30Z
[ "python", "internationalization", "multilingual", "gettext" ]
What is the most secure python "password" encryption
1,043,735
<p>I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.</p> <p>So what is the most secure way to encrypt/decrypt something using python?</p>
5
2009-06-25T12:52:58Z
1,043,759
<p>If it's a web game, can't you store the codes server side and send them to the client when he completed a task? What's the architecture of your game?</p> <p>As for encryption, maybe try something like <a href="http://twhiteman.netfirms.com/des.html" rel="nofollow">pyDes</a>?</p>
2
2009-06-25T12:58:45Z
[ "python", "security", "encryption" ]
What is the most secure python "password" encryption
1,043,735
<p>I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.</p> <p>So what is the most secure way to encrypt/decrypt something using python?</p>
5
2009-06-25T12:52:58Z
1,043,762
<p>The most secure encryption is no encryption. Passwords should be reduced to a hash. This is a one-way transformation, making the password (almost) unrecoverable.</p> <p>When giving someone a code, you can do the following to be <em>actually</em> secure. </p> <p>(1) generate some random string.</p> <p>(2) give them the string.</p> <p>(3) save the hash of the string you generated.</p> <p>Once.</p> <p>If they "forget" the code, you have to (1) be sure they're authorized to be given the code, then (2) do the process again (generate a new code, give it to them, save the hash.)</p>
5
2009-06-25T12:59:12Z
[ "python", "security", "encryption" ]
What is the most secure python "password" encryption
1,043,735
<p>I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.</p> <p>So what is the most secure way to encrypt/decrypt something using python?</p>
5
2009-06-25T12:52:58Z
1,046,926
<p>Your question isn't quite clear. Where do you want the decryption to occur? One way or another, the plaintext has to surface since you need players to eventually know it.</p> <p>Pick a <a href="http://en.wikipedia.org/wiki/Stream%5Fcipher" rel="nofollow">cipher</a> and be done with it.</p>
0
2009-06-26T01:13:02Z
[ "python", "security", "encryption" ]
What is the most secure python "password" encryption
1,043,735
<p>I am making a little webgame that has tasks and solutions, the solutions are solved by entering a code given to user after completion of a task. To have some security (against cheating) i dont want to store the codes genereted by the game in plain text. But since i need to be able to give a player the code when he has accomplished the task i cant hash it since then i cant retrive it.</p> <p>So what is the most secure way to encrypt/decrypt something using python?</p>
5
2009-06-25T12:52:58Z
1,047,013
<p>If your script can decode the passwords, so can someone breaking in to your server. Encryption is only really useful when someone enters a password to unlock it - if it remains unlocked (or the script has the password to unlock it), the encryption is pointless</p> <p>This is why hashing is more useful, since it is a one way process - even if someone knows your password hash, they don't know the plain-text they must enter to generate it (without lots of brute-force)</p> <p>I wouldn't worry about keeping the game passwords as plain-text. If you are concerned about securing them, fix up possibly SQL injections/etc, make sure your web-server and other software is up to date and configured correctly and so on.</p> <p>Perhaps think of a way to make it less appealing to steal the passwords than actually play the game? For example, there was a game (I don't recall what it was) which if you used the level skip cheat, you went to the next level but it didn't mark it as "complete", or you could skip the level but didn't get any points. Or look at Project Euler, you can do any level, but you only get points if you enter the answer (and working out the answer is the whole point of the game, so cheating defeats the playing of the game)</p> <p>If you are really paranoid, you could <em>possibly</em> use asymmetric crypto, where you basically encrypt something with <code>key A</code>, and you can only read it with <code>key B</code>..</p> <p>I came up with an similar concept for using GPG encryption (popular asymmetric crypto system, mainly used for email encryption or signing) <a href="http://neverfear.org/blog/view/Secure%5Fwebsite%5Fauthentication%5Fusing%5FGPG%5Fkeys">to secure website data</a>. I'm not quite sure how this would apply to securing game level passwords, and as I said, you'd need to be really paranoid to even consider this..</p> <p>In short, I'd say store the passwords in plain-text, and concentrate your security-concerns elsewhere (the web applications code itself)</p>
5
2009-06-26T02:01:28Z
[ "python", "security", "encryption" ]
How to do cleanup reliably in python?
1,044,073
<p>I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic references.</p> <p>I think It'd solve if I'd find a reliable way to hook destructor to an object. (weakrefs would help if they'd give me the callback just <em>before</em> the data is dropped.</p> <p>So obviously this code megafails when I put in velocity_func:</p> <pre><code>class Body(object): def __init__(self, mass, inertia): self._body = body.New(mass, inertia) def __del__(self): print '__del__ %r' % self if body: body.Free(self._body) ... def set_velocity_func(self, func): self._body.contents.velocity_func = ctypes_wrapping(func) </code></pre> <p>I also tried to solve it through weakrefs, with those the things seem getting just worse, just only largely more unpredictable.</p> <p>Even if I don't put in the velocity_func, there will appear cycles at least then when I do this:</p> <pre><code>class Toy(object): def __init__(self, body): self.body.owner = self ... def collision(a, b, contacts): whatever(a.body.owner) </code></pre> <p>So how to make sure Structures will get garbage collected, even if they are allocated/freed by the shared library?</p> <p>There's repository if you are interested about more details: <a href="http://bitbucket.org/cheery/ctypes-chipmunk/" rel="nofollow">http://bitbucket.org/cheery/ctypes-chipmunk/</a></p>
3
2009-06-25T13:53:08Z
1,044,297
<p>What you want to do, that is create an object that allocates things and then deallocates automatically when the object is no longer in use, is almost impossible in Python, unfortunately. The <strong>del</strong> statement is not guaranteed to be called, so you can't rely on that. </p> <p>The standard way in Python is simply:</p> <pre><code>try: allocate() dostuff() finally: cleanup() </code></pre> <p>Or since 2.5 you can also create context-managers and use the with statement, which is a neater way of doing that.</p> <p>But both of these are primarily for when you allocate/lock in the beginning of a code snippet. If you want to have things allocated for the whole run of the program, you need to allocate the resource at startup, before the main code of the program runs, and deallocate afterwards. There is one situation which isn't covered here, and that is when you want to allocate and deallocate many resources dynamically and use them in many places in the code. For example of you want a pool of memory buffers or similar. But most of those cases are for memory, which Python will handle for you, so you don't have to bother about those. There are of course cases where you want to have dynamic pool allocation of things that are NOT memory, and then you would want the type of deallocation you try in your example, and that <em>is</em> tricky to do with Python.</p>
3
2009-06-25T14:33:21Z
[ "python", "ctypes", "cyclic-reference" ]
How to do cleanup reliably in python?
1,044,073
<p>I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic references.</p> <p>I think It'd solve if I'd find a reliable way to hook destructor to an object. (weakrefs would help if they'd give me the callback just <em>before</em> the data is dropped.</p> <p>So obviously this code megafails when I put in velocity_func:</p> <pre><code>class Body(object): def __init__(self, mass, inertia): self._body = body.New(mass, inertia) def __del__(self): print '__del__ %r' % self if body: body.Free(self._body) ... def set_velocity_func(self, func): self._body.contents.velocity_func = ctypes_wrapping(func) </code></pre> <p>I also tried to solve it through weakrefs, with those the things seem getting just worse, just only largely more unpredictable.</p> <p>Even if I don't put in the velocity_func, there will appear cycles at least then when I do this:</p> <pre><code>class Toy(object): def __init__(self, body): self.body.owner = self ... def collision(a, b, contacts): whatever(a.body.owner) </code></pre> <p>So how to make sure Structures will get garbage collected, even if they are allocated/freed by the shared library?</p> <p>There's repository if you are interested about more details: <a href="http://bitbucket.org/cheery/ctypes-chipmunk/" rel="nofollow">http://bitbucket.org/cheery/ctypes-chipmunk/</a></p>
3
2009-06-25T13:53:08Z
1,044,393
<p>If weakrefs aren't broken, I guess this may work:</p> <pre><code>from weakref import ref pointers = set() class Pointer(object): def __init__(self, cfun, ptr): pointers.add(self) self.ref = ref(ptr, self.cleanup) self.data = cast(ptr, c_void_p).value # python cast it so smart, but it can't be smarter than this. self.cfun = cfun def cleanup(self, obj): print 'cleanup 0x%x' % self.data self.cfun(self.data) pointers.remove(self) def cleanup(cfun, ptr): Pointer(cfun, ptr) </code></pre> <p>I yet try it. The important piece is that the Pointer doesn't have any strong references to the foreign pointer, except an integer. This should work if ctypes doesn't free memory that I should free with the bindings. Yeah, it's basicly a hack, but I think it may work better than the earlier things I've been trying.</p> <p>Edit: Tried it, and it seem to work after small finetuning my code. A surprising thing is that even if I got <strong>del</strong> out from all of my structures, it seem to still fail. Interesting but frustrating.</p> <p>Neither works, from some weird chance I've been able to drop away cyclic references in places, but things stay broke.</p> <p>Edit: Well.. weakrefs WERE broken after all! so there's likely no solution for reliable cleanup in python, except than forcing it being explicit.</p>
0
2009-06-25T14:52:06Z
[ "python", "ctypes", "cyclic-reference" ]
How to do cleanup reliably in python?
1,044,073
<p>I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic references.</p> <p>I think It'd solve if I'd find a reliable way to hook destructor to an object. (weakrefs would help if they'd give me the callback just <em>before</em> the data is dropped.</p> <p>So obviously this code megafails when I put in velocity_func:</p> <pre><code>class Body(object): def __init__(self, mass, inertia): self._body = body.New(mass, inertia) def __del__(self): print '__del__ %r' % self if body: body.Free(self._body) ... def set_velocity_func(self, func): self._body.contents.velocity_func = ctypes_wrapping(func) </code></pre> <p>I also tried to solve it through weakrefs, with those the things seem getting just worse, just only largely more unpredictable.</p> <p>Even if I don't put in the velocity_func, there will appear cycles at least then when I do this:</p> <pre><code>class Toy(object): def __init__(self, body): self.body.owner = self ... def collision(a, b, contacts): whatever(a.body.owner) </code></pre> <p>So how to make sure Structures will get garbage collected, even if they are allocated/freed by the shared library?</p> <p>There's repository if you are interested about more details: <a href="http://bitbucket.org/cheery/ctypes-chipmunk/" rel="nofollow">http://bitbucket.org/cheery/ctypes-chipmunk/</a></p>
3
2009-06-25T13:53:08Z
1,045,020
<p>In CPython, <code>__del__</code> <em>is</em> a reliable destructor of an object, because it will always be called when the reference count reaches zero (note: there may be cases - like circular references of items with <code>__del__</code> method defined - where the reference count will never reaches zero, but that is another issue).</p> <p><strong>Update</strong> From the comments, I understand the problem is related to the order of destruction of objects: <em>body</em> is a global object, and it is being destroyed before all other objects, thus it is no longer available to them.<br /> Actually, using global objects is not good; not only because of issues like this one, but also because of maintenance.</p> <p>I would then change your class with something like this</p> <pre><code>class Body(object): def __init__(self, mass, inertia): self._bodyref = body self._body = body.New(mass, inertia) def __del__(self): print '__del__ %r' % self if body: body.Free(self._body) ... def set_velocity_func(self, func): self._body.contents.velocity_func = ctypes_wrapping(func) </code></pre> <p>A couple of notes:</p> <ol> <li>The change is only adding a reference to the global <em>body</em> object, that thus will live at least as much as all the objects derived from that class.</li> <li>Still, using a global object is not good because of unit testing and maintenance; better would be to have a factory for the object, that will set the correct "body" to the class, and in case of unit test will easily put a mock object. But that's really up to you and how much effort you think makes sense in this project.</li> </ol>
0
2009-06-25T16:55:14Z
[ "python", "ctypes", "cyclic-reference" ]
BeanStalkd on Solaris doesnt return anything when called from the python library
1,044,473
<p>i am using Solaris 10 OS(x86). i installed beanstalkd and it starts fine by using command "beanstalkd -d -l hostip -p 11300".</p> <p>i have Python 2.4.4 on my system i installed YAML and beanstalkc python libraries to connect beanstalkd with python my problem is when i try to write some code:</p> <p>import beanstalkc beanstalk = beanstalkc.Connection(host='hostip', port=11300) </p> <p>no error so far but when i try to do someting on beanstalk like say listing queues. nothing happens.</p> <p>beanstalk.tubes()</p> <p>it just hangs and nothing returns. if i cancel the operation(using ctr+c on python env.) or stop the server i immediately see an output:</p> <p>Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 134, in tubes return self._interact_yaml('list-tubes\r\n', ['OK']) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 83, in _interact_yaml size, = self._interact(command, expected_ok, expected_err) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 57, in _interact status, results = self._read_response() File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 66, in _read_response response = self.socket_file.readline().split() File "/usr/lib/python2.4/socket.py", line 332, in readline data = self._sock.recv(self._rbufsize)</p> <p>any idea whats going? i am an Unix newbie so i have no idea what i did setup wrong to cause this. </p> <p>edit: seems like the problem lies within BeanStalkd itself, anyone have used this on Solaris 10? if so which version did you use? The v1.3 labeled one doesnt compile on Solaris while the latest from git code repository compiles it causes the above problem(or perhaps there is some configuration to do on Solaris?).</p> <p>edit2: i installed and compiled same components with beanstalkd, PyYAML, pythonbeanstalc and libevent to an UBUNTU machine and it works fine. problems seems to be about compilation of beanstalkd on solaris, i have yet to produce or read any solution.</p>
2
2009-06-25T15:06:41Z
1,044,719
<p>It seems that the python-client listens to the server, but the server has nothing to say.</p> <p>Is there something to read for the client?</p> <p>Is there a consumer AND a producer ?</p> <p><a href="http://parand.com/say/index.php/2008/10/12/beanstalkd-python-basic-tutorial/" rel="nofollow">Look at this</a></p>
1
2009-06-25T15:51:37Z
[ "python", "solaris", "yaml", "beanstalkd" ]
BeanStalkd on Solaris doesnt return anything when called from the python library
1,044,473
<p>i am using Solaris 10 OS(x86). i installed beanstalkd and it starts fine by using command "beanstalkd -d -l hostip -p 11300".</p> <p>i have Python 2.4.4 on my system i installed YAML and beanstalkc python libraries to connect beanstalkd with python my problem is when i try to write some code:</p> <p>import beanstalkc beanstalk = beanstalkc.Connection(host='hostip', port=11300) </p> <p>no error so far but when i try to do someting on beanstalk like say listing queues. nothing happens.</p> <p>beanstalk.tubes()</p> <p>it just hangs and nothing returns. if i cancel the operation(using ctr+c on python env.) or stop the server i immediately see an output:</p> <p>Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 134, in tubes return self._interact_yaml('list-tubes\r\n', ['OK']) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 83, in _interact_yaml size, = self._interact(command, expected_ok, expected_err) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 57, in _interact status, results = self._read_response() File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 66, in _read_response response = self.socket_file.readline().split() File "/usr/lib/python2.4/socket.py", line 332, in readline data = self._sock.recv(self._rbufsize)</p> <p>any idea whats going? i am an Unix newbie so i have no idea what i did setup wrong to cause this. </p> <p>edit: seems like the problem lies within BeanStalkd itself, anyone have used this on Solaris 10? if so which version did you use? The v1.3 labeled one doesnt compile on Solaris while the latest from git code repository compiles it causes the above problem(or perhaps there is some configuration to do on Solaris?).</p> <p>edit2: i installed and compiled same components with beanstalkd, PyYAML, pythonbeanstalc and libevent to an UBUNTU machine and it works fine. problems seems to be about compilation of beanstalkd on solaris, i have yet to produce or read any solution.</p>
2
2009-06-25T15:06:41Z
1,048,086
<p>After looking in the code (beanstalkc):</p> <p>your client has send his 'list-tubes' message, and is waiting for an answer. (until you kill it) your server doesn't answer or can't send the answer to the client. (or the answer is shorter than the client expect)</p> <p>is a network-admin at your side (or site) :-)</p>
1
2009-06-26T08:56:06Z
[ "python", "solaris", "yaml", "beanstalkd" ]
BeanStalkd on Solaris doesnt return anything when called from the python library
1,044,473
<p>i am using Solaris 10 OS(x86). i installed beanstalkd and it starts fine by using command "beanstalkd -d -l hostip -p 11300".</p> <p>i have Python 2.4.4 on my system i installed YAML and beanstalkc python libraries to connect beanstalkd with python my problem is when i try to write some code:</p> <p>import beanstalkc beanstalk = beanstalkc.Connection(host='hostip', port=11300) </p> <p>no error so far but when i try to do someting on beanstalk like say listing queues. nothing happens.</p> <p>beanstalk.tubes()</p> <p>it just hangs and nothing returns. if i cancel the operation(using ctr+c on python env.) or stop the server i immediately see an output:</p> <p>Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 134, in tubes return self._interact_yaml('list-tubes\r\n', ['OK']) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 83, in _interact_yaml size, = self._interact(command, expected_ok, expected_err) File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 57, in _interact status, results = self._read_response() File "/usr/lib/python2.4/site-packages/beanstalkc-0.1.1-py2.4.egg/beanstalkc.py", line 66, in _read_response response = self.socket_file.readline().split() File "/usr/lib/python2.4/socket.py", line 332, in readline data = self._sock.recv(self._rbufsize)</p> <p>any idea whats going? i am an Unix newbie so i have no idea what i did setup wrong to cause this. </p> <p>edit: seems like the problem lies within BeanStalkd itself, anyone have used this on Solaris 10? if so which version did you use? The v1.3 labeled one doesnt compile on Solaris while the latest from git code repository compiles it causes the above problem(or perhaps there is some configuration to do on Solaris?).</p> <p>edit2: i installed and compiled same components with beanstalkd, PyYAML, pythonbeanstalc and libevent to an UBUNTU machine and it works fine. problems seems to be about compilation of beanstalkd on solaris, i have yet to produce or read any solution.</p>
2
2009-06-25T15:06:41Z
1,093,128
<p>I might know what is wrong: don't start it in daemon (-d) mode. I have experienced the same and by accident I found out what is wrong.</p> <p>Or rather, I don't know what is wrong, but it works without running it in daemon mode.</p> <p>./beanstalkd -p 9977 &amp; </p> <p>as an alternative.</p>
1
2009-07-07T15:46:41Z
[ "python", "solaris", "yaml", "beanstalkd" ]
Unable to solve a Python error message
1,044,705
<p><strong>The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":</strong></p> <pre><code>def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) if laina_aika &lt; 1: print "liian lyhyt laina-aika" else: kk_lkm = 12 * laina_aika rivi = raw_input("Anna korkoprosentti: ") korko = float(rivi) lyhennys = lainasumma / kk_lkm paaoma = lainasumma i = 0 print " lyhennys korko yhteensa" while i &lt; kk_lkm: i = i + 1 korkoera = korko / 1200.0 * paaoma paaoma = paaoma - lyhennys kuukausiera = korkoera + lyhennys print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) main() </code></pre> <p>I get the syntax error</p> <pre><code>SyntaxError: unexpected character after line continuation character </code></pre> <p><strong>How can you solve the error message?</strong></p>
1
2009-06-25T15:49:33Z
1,044,717
<p>Try modifying these lines:</p> <pre><code> print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) </code></pre> <p>to this line:</p> <pre><code> print "%2d. %8.2f %8.2f %8.2f" % (i, lyhennys, korkoera, kuukausiera) </code></pre> <p>Also, note that a line ending with a backslash cannot carry a comment. So your <code>#mistake probably here</code> comment is likely causing the problem. </p>
2
2009-06-25T15:51:33Z
[ "python" ]
Unable to solve a Python error message
1,044,705
<p><strong>The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":</strong></p> <pre><code>def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) if laina_aika &lt; 1: print "liian lyhyt laina-aika" else: kk_lkm = 12 * laina_aika rivi = raw_input("Anna korkoprosentti: ") korko = float(rivi) lyhennys = lainasumma / kk_lkm paaoma = lainasumma i = 0 print " lyhennys korko yhteensa" while i &lt; kk_lkm: i = i + 1 korkoera = korko / 1200.0 * paaoma paaoma = paaoma - lyhennys kuukausiera = korkoera + lyhennys print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) main() </code></pre> <p>I get the syntax error</p> <pre><code>SyntaxError: unexpected character after line continuation character </code></pre> <p><strong>How can you solve the error message?</strong></p>
1
2009-06-25T15:49:33Z
1,044,721
<p>You can't have <em>anything</em>, even whitespace, after the line continuation character.</p> <p>Either delete the whitespace, or wrap the entire line in a pair of parentheses. <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#implicit-line-joining">Python implicitly joins lines between parentheses, curly braces, and square brackets</a>:</p> <pre><code>print ( "%2d. %8.2f %8.2f %8.2f" % (i, lyhennys, korkoera, kuukausiera) ) </code></pre>
6
2009-06-25T15:51:49Z
[ "python" ]
Unable to solve a Python error message
1,044,705
<p><strong>The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":</strong></p> <pre><code>def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) if laina_aika &lt; 1: print "liian lyhyt laina-aika" else: kk_lkm = 12 * laina_aika rivi = raw_input("Anna korkoprosentti: ") korko = float(rivi) lyhennys = lainasumma / kk_lkm paaoma = lainasumma i = 0 print " lyhennys korko yhteensa" while i &lt; kk_lkm: i = i + 1 korkoera = korko / 1200.0 * paaoma paaoma = paaoma - lyhennys kuukausiera = korkoera + lyhennys print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) main() </code></pre> <p>I get the syntax error</p> <pre><code>SyntaxError: unexpected character after line continuation character </code></pre> <p><strong>How can you solve the error message?</strong></p>
1
2009-06-25T15:49:33Z
1,044,731
<p>Try rewriting this:</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) </code></pre> <p>To this:</p> <pre><code>print ("%2d. %8.2f %8.2f %8.2f" % (i, lyhennys, korkoera, kuukausiera)) </code></pre> <p><code>\</code> should work too, but IMO it's less readable.</p>
2
2009-06-25T15:54:11Z
[ "python" ]
Unable to solve a Python error message
1,044,705
<p><strong>The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":</strong></p> <pre><code>def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) if laina_aika &lt; 1: print "liian lyhyt laina-aika" else: kk_lkm = 12 * laina_aika rivi = raw_input("Anna korkoprosentti: ") korko = float(rivi) lyhennys = lainasumma / kk_lkm paaoma = lainasumma i = 0 print " lyhennys korko yhteensa" while i &lt; kk_lkm: i = i + 1 korkoera = korko / 1200.0 * paaoma paaoma = paaoma - lyhennys kuukausiera = korkoera + lyhennys print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) main() </code></pre> <p>I get the syntax error</p> <pre><code>SyntaxError: unexpected character after line continuation character </code></pre> <p><strong>How can you solve the error message?</strong></p>
1
2009-06-25T15:49:33Z
1,044,744
<p>Replace:</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % \ (i, lyhennys, korkoera, kuukausiera) </code></pre> <p>By:</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, lyhennys, korkoera, kuukausiera) </code></pre> <p>General remark: always use English for identifiers</p>
2
2009-06-25T15:56:44Z
[ "python" ]
Unable to solve a Python error message
1,044,705
<p><strong>The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":</strong></p> <pre><code>def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) if laina_aika &lt; 1: print "liian lyhyt laina-aika" else: kk_lkm = 12 * laina_aika rivi = raw_input("Anna korkoprosentti: ") korko = float(rivi) lyhennys = lainasumma / kk_lkm paaoma = lainasumma i = 0 print " lyhennys korko yhteensa" while i &lt; kk_lkm: i = i + 1 korkoera = korko / 1200.0 * paaoma paaoma = paaoma - lyhennys kuukausiera = korkoera + lyhennys print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) main() </code></pre> <p>I get the syntax error</p> <pre><code>SyntaxError: unexpected character after line continuation character </code></pre> <p><strong>How can you solve the error message?</strong></p>
1
2009-06-25T15:49:33Z
1,044,754
<p>Several answers already gave you the crux of your problem, but I want to make a plug for my favorite way to get logical line continuation in Python, when feasible:</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( # no mistake here i, lyhennys, korkoera, kuukausiera) </code></pre> <p>i.e., instead of using extra parentheses as some answers advise, you can take advantage of any parenthesis you already naturally happen to have -- that will tell Python that you need logical line continuation, too;-)</p>
10
2009-06-25T15:57:51Z
[ "python" ]
Unable to solve a Python error message
1,044,705
<p><strong>The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":</strong></p> <pre><code>def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) if laina_aika &lt; 1: print "liian lyhyt laina-aika" else: kk_lkm = 12 * laina_aika rivi = raw_input("Anna korkoprosentti: ") korko = float(rivi) lyhennys = lainasumma / kk_lkm paaoma = lainasumma i = 0 print " lyhennys korko yhteensa" while i &lt; kk_lkm: i = i + 1 korkoera = korko / 1200.0 * paaoma paaoma = paaoma - lyhennys kuukausiera = korkoera + lyhennys print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) main() </code></pre> <p>I get the syntax error</p> <pre><code>SyntaxError: unexpected character after line continuation character </code></pre> <p><strong>How can you solve the error message?</strong></p>
1
2009-06-25T15:49:33Z
1,044,758
<p>In general, I find I don't use line continuation in Python. You can make it cleaner with parentheses and so on.</p>
1
2009-06-25T15:58:18Z
[ "python" ]
Unable to solve a Python error message
1,044,705
<p><strong>The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":</strong></p> <pre><code>def main(): print "Ohjelma laskee asuntolainan kuukausierat." rivi = raw_input("Anna lainasumma: ") lainasumma = float(rivi) rivi = raw_input("Anna laina-aika vuosina: ") laina_aika = int(rivi) if laina_aika &lt; 1: print "liian lyhyt laina-aika" else: kk_lkm = 12 * laina_aika rivi = raw_input("Anna korkoprosentti: ") korko = float(rivi) lyhennys = lainasumma / kk_lkm paaoma = lainasumma i = 0 print " lyhennys korko yhteensa" while i &lt; kk_lkm: i = i + 1 korkoera = korko / 1200.0 * paaoma paaoma = paaoma - lyhennys kuukausiera = korkoera + lyhennys print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here (i, lyhennys, korkoera, kuukausiera) main() </code></pre> <p>I get the syntax error</p> <pre><code>SyntaxError: unexpected character after line continuation character </code></pre> <p><strong>How can you solve the error message?</strong></p>
1
2009-06-25T15:49:33Z
1,044,759
<p>"\" means "this line continue to the next line" and it can't have any character after it. There probably is a space right after.</p> <p>Two solution :</p> <p>Ensure there is not spaces after;</p> <p>Rewrite the statement on one line :</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % (i, lyhennys, korkoera, kuukausiera) </code></pre> <p>You can even use parenthesis to make it fit on several lines :</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, lyhennys, korkoera, kuukausiera) </code></pre>
0
2009-06-25T15:58:25Z
[ "python" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,044,859
<p>Double stars (<code>**</code>) are exponentiation. So "2 times 2" and "2 to the power 2" are the same. Change the numbers and you'll see a difference.</p>
29
2009-06-25T16:24:35Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,044,864
<p>2**2 = 2 power-of 2</p> <p>2*2 = 2 times 2 </p>
2
2009-06-25T16:25:28Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,044,865
<p>The <code>**</code> operator in Python is really "power;" that is, <code>2**3 = 8</code>.</p>
1
2009-06-25T16:25:38Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,044,866
<p>Try:</p> <pre><code>2**3*2 </code></pre> <p>and</p> <pre><code>2*3*2 </code></pre> <p>to see the difference.</p> <p><code>**</code> is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2. </p>
83
2009-06-25T16:25:55Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,044,867
<pre><code> 2**2 means 2 squared (2^2) 2*2 mean 2 times 2 (2x2) </code></pre> <p>In this case they happen to have the same value, but...</p> <pre><code> 3**3*4 != 3*3*4 </code></pre>
11
2009-06-25T16:25:57Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,044,869
<p>The top one is a "power" operator, so in this case it is the same as 2 * 2 equal to is 2 to the power of 2. If you put a 3 in the middle position, you will see a difference.</p>
1
2009-06-25T16:26:09Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,044,933
<p>To specifically answer your question <strong>Why is the code1 used if we can use code2?</strong> I might suggest that the programmer was thinking in a mathematically broader sense. Specifically, perhaps the broader equation is a power equation, and the fact that both first numbers are "2" is more coincidence than mathematical reality. I'd want to make sure that the broader context of the code supports it being <pre><code>var = x * x * y</code></pre> in all cases, rather than in this specific case alone. This could get you in big trouble if x is anything but 2.</p>
4
2009-06-25T16:36:26Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
1,045,786
<p>A double asterisk means to the power of. A single asterisk means multiplied by. 2<sup>2</sup> is the same as 2x2 which is why both answers came out as 4.</p>
1
2009-06-25T19:32:23Z
[ "python", "syntax" ]
What's the difference between "2*2" and "2**2" in Python?
1,044,854
<p>What is the difference between the following codes?</p> <p><strong>code1</strong>:</p> <pre><code>var=2**2*3 </code></pre> <p><strong>code2:</strong></p> <pre><code>var2=2*2*3 </code></pre> <p>I see no difference. This raises the following question.</p> <p><strong>Why is the code1 used if we can use code2?</strong></p>
33
2009-06-25T16:23:16Z
12,082,829
<p>Power has more precedence than multiply, so:</p> <pre><code>2**2*3 = (2^2)*3 2*2*3 = 2*2*3 </code></pre>
1
2012-08-22T23:36:53Z
[ "python", "syntax" ]
Unable to understand a line of Python code exactly
1,044,889
<p><a href="http://stackoverflow.com/questions/1044705/unable-to-solve-a-python-error-message/1044754#1044754">Alex's answer</a> has the following line when translated to English</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) </code></pre> <p>I am unsure about the line</p> <pre><code>"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? </code></pre> <p>It seems to mean the following</p> <ol> <li>apply %2d. to i</li> <li>apply %8.2f to payment</li> <li>apply %8.2f to interest</li> <li>apply %8.2f to monthPayment</li> </ol> <p>The %-words seem to mean the following</p> <ol> <li><p>%2d.: a decimal presentation of two decimals</p> <p>2-4. %8.2f: a floating point presentation of two decimals</p></li> </ol> <p>I am not sure why we use the 8 in %8.2f.</p> <p><strong>How do you understand the challenging line?</strong></p>
1
2009-06-25T16:30:45Z
1,044,915
<p>the %8.2f means allow 8 character spaces to hold the number given by the corrisponding variable holding a float, and then have decimal precision of 2.</p>
0
2009-06-25T16:33:54Z
[ "python", "syntax" ]
Unable to understand a line of Python code exactly
1,044,889
<p><a href="http://stackoverflow.com/questions/1044705/unable-to-solve-a-python-error-message/1044754#1044754">Alex's answer</a> has the following line when translated to English</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) </code></pre> <p>I am unsure about the line</p> <pre><code>"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? </code></pre> <p>It seems to mean the following</p> <ol> <li>apply %2d. to i</li> <li>apply %8.2f to payment</li> <li>apply %8.2f to interest</li> <li>apply %8.2f to monthPayment</li> </ol> <p>The %-words seem to mean the following</p> <ol> <li><p>%2d.: a decimal presentation of two decimals</p> <p>2-4. %8.2f: a floating point presentation of two decimals</p></li> </ol> <p>I am not sure why we use the 8 in %8.2f.</p> <p><strong>How do you understand the challenging line?</strong></p>
1
2009-06-25T16:30:45Z
1,044,925
<p>The last % is an operator that takes the string before it and the tuple after and applies the formatting as you note. See the <a href="http://docs.python.org/library/stdtypes.html#index-586" rel="nofollow">Python tutorial</a> for more details.</p>
4
2009-06-25T16:35:08Z
[ "python", "syntax" ]
Unable to understand a line of Python code exactly
1,044,889
<p><a href="http://stackoverflow.com/questions/1044705/unable-to-solve-a-python-error-message/1044754#1044754">Alex's answer</a> has the following line when translated to English</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) </code></pre> <p>I am unsure about the line</p> <pre><code>"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? </code></pre> <p>It seems to mean the following</p> <ol> <li>apply %2d. to i</li> <li>apply %8.2f to payment</li> <li>apply %8.2f to interest</li> <li>apply %8.2f to monthPayment</li> </ol> <p>The %-words seem to mean the following</p> <ol> <li><p>%2d.: a decimal presentation of two decimals</p> <p>2-4. %8.2f: a floating point presentation of two decimals</p></li> </ol> <p>I am not sure why we use the 8 in %8.2f.</p> <p><strong>How do you understand the challenging line?</strong></p>
1
2009-06-25T16:30:45Z
1,044,935
<p>The % is an operator which makes a format string. A simple example would be:</p> <pre><code>"%s is %s" % ( "Alice", "Happy" ) </code></pre> <p>Which would evaluate to the string <code>"Alice is Happy"</code>. The format string that is provided defines how the values you pass are put into the string; the syntax is available <a href="http://docs.python.org/library/string.html#formatstrings" rel="nofollow">here</a>. In short the <code>d</code> is "treat as a decimal number" and the <code>8.2</code> is "pad to 8 characters and round to 2 decimal places". In essence it looks like that format in particular is being used so that the answers line up when viewed with a monospace font. :)</p> <p>In my code example the <code>s</code> means "treat as a string".</p>
1
2009-06-25T16:37:08Z
[ "python", "syntax" ]
Unable to understand a line of Python code exactly
1,044,889
<p><a href="http://stackoverflow.com/questions/1044705/unable-to-solve-a-python-error-message/1044754#1044754">Alex's answer</a> has the following line when translated to English</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) </code></pre> <p>I am unsure about the line</p> <pre><code>"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? </code></pre> <p>It seems to mean the following</p> <ol> <li>apply %2d. to i</li> <li>apply %8.2f to payment</li> <li>apply %8.2f to interest</li> <li>apply %8.2f to monthPayment</li> </ol> <p>The %-words seem to mean the following</p> <ol> <li><p>%2d.: a decimal presentation of two decimals</p> <p>2-4. %8.2f: a floating point presentation of two decimals</p></li> </ol> <p>I am not sure why we use the 8 in %8.2f.</p> <p><strong>How do you understand the challenging line?</strong></p>
1
2009-06-25T16:30:45Z
1,044,936
<p>The 8 in 8.2 is the width<br /> "Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger"<br /> The 2 is the number of decimal places</p> <p>The final % just links the format string (in quotes) with the list of arguments (in brackets). It's a bit confusing that they chose a % to do this - there is probably some deep python reason.</p> <p>edit: Apparently '%' is used simply because '%' is used inside the format - which is IMHO stupid and guaranteed to cause confusion. It's like requiring an extra dot at the end of a floating point number to show that it's floating point!</p>
7
2009-06-25T16:37:12Z
[ "python", "syntax" ]
Unable to understand a line of Python code exactly
1,044,889
<p><a href="http://stackoverflow.com/questions/1044705/unable-to-solve-a-python-error-message/1044754#1044754">Alex's answer</a> has the following line when translated to English</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) </code></pre> <p>I am unsure about the line</p> <pre><code>"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? </code></pre> <p>It seems to mean the following</p> <ol> <li>apply %2d. to i</li> <li>apply %8.2f to payment</li> <li>apply %8.2f to interest</li> <li>apply %8.2f to monthPayment</li> </ol> <p>The %-words seem to mean the following</p> <ol> <li><p>%2d.: a decimal presentation of two decimals</p> <p>2-4. %8.2f: a floating point presentation of two decimals</p></li> </ol> <p>I am not sure why we use the 8 in %8.2f.</p> <p><strong>How do you understand the challenging line?</strong></p>
1
2009-06-25T16:30:45Z
1,044,975
<p>The % after a string tells Python to attempt to fill in the variables on the left side of the '%' operator with the items in the list on the right side of the '%' operator.</p> <p>The '%' operator knows to find the variable in the string by looking for character in the string starting with %. </p> <p>Your confusion is that you think the % operator and the % character in the string are the same.</p> <p>Try to look at it this way, outside a string % is an operator, inside a string it is possibly a template for substitution. </p>
1
2009-06-25T16:45:13Z
[ "python", "syntax" ]
Unable to understand a line of Python code exactly
1,044,889
<p><a href="http://stackoverflow.com/questions/1044705/unable-to-solve-a-python-error-message/1044754#1044754">Alex's answer</a> has the following line when translated to English</p> <pre><code>print "%2d. %8.2f %8.2f %8.2f" % ( i, payment, interest, monthPayment) </code></pre> <p>I am unsure about the line</p> <pre><code>"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here? </code></pre> <p>It seems to mean the following</p> <ol> <li>apply %2d. to i</li> <li>apply %8.2f to payment</li> <li>apply %8.2f to interest</li> <li>apply %8.2f to monthPayment</li> </ol> <p>The %-words seem to mean the following</p> <ol> <li><p>%2d.: a decimal presentation of two decimals</p> <p>2-4. %8.2f: a floating point presentation of two decimals</p></li> </ol> <p>I am not sure why we use the 8 in %8.2f.</p> <p><strong>How do you understand the challenging line?</strong></p>
1
2009-06-25T16:30:45Z
1,045,007
<p>As usual, a quote of the doc is required - <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">string-formatting</a>:</p> <blockquote> <p>String and Unicode objects have one unique built-in operation: <strong>the % operator</strong> (modulo). This is also known as the <em>string formatting</em> or <em>interpolation operator</em>. Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf in the C language. </p> </blockquote> <p>And the description of the conversion specifier to explain <code>%8.2f</code></p> <blockquote> <p>A conversion specifier contains two or more characters and has the following components, which must occur in this order:</p> </blockquote> <ol> <li>The '%' character, which marks the start of the specifier.</li> <li>Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).</li> <li>Conversion flags (optional), which affect the result of some conversion types.</li> <li>Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.</li> <li><strong>Precision (optional), given as a '.' (dot) followed by the precision</strong>. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.</li> <li>Length modifier (optional).</li> <li>Conversion type.</li> </ol> <p>When the right argument is a dictionary (or other mapping type), the format string includes mapping keys (2). Breaking the example to 2 steps, we have a dictionary and a format that includes keys from the dictionary (the <code>#</code> is a key):</p> <pre><code>&gt;&gt;&gt; mydict = {'language':'python', '#':2} &gt;&gt;&gt; '%(language)s has %(#)03d quote types.' % mydict 'python has 002 quote types.' &gt;&gt;&gt; </code></pre>
1
2009-06-25T16:52:04Z
[ "python", "syntax" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,174
<p>The line</p> <pre><code>a, b = b, b+a </code></pre> <p>Doesn't easily translate. It's something like this. You could simplify it. This is the literal meaning.</p> <pre><code>t1 = b t2 = b+a a = t1 b = t2 </code></pre>
4
2009-06-25T17:23:04Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,182
<p>I'd do it this way:</p> <pre><code>public class FibonacciAlgorithm { private int a = 0; private int b = 1; public FibonacciAlgorithm() { } public int increment() { int temp = b; b = a + b; a = temp; return value; } public int getValue() { return b; } } </code></pre> <p>This keeps it as close to your original Java code as possible.</p> <p><em>[Editor's note: <code>Integers</code> have been replaced with <code>ints</code>. There is no reason to use <code>Integers</code> for this.]</em></p>
7
2009-06-25T17:23:51Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,184
<p>public Integer increment() { a = b; b = a + b; return value; }</p> <p>Is certainly wrong. I think switching the first two lines should do the trick</p>
-1
2009-06-25T17:23:52Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,186
<p>You need to store the value of either a or b in a temporary variable first;</p> <pre><code> public Integer increment() { int temp = a; a = b; b = temp + b; return value; } </code></pre>
2
2009-06-25T17:24:19Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,201
<p>Java integers can only store the first 46 Fibonacci numbers, use a lookup table.</p>
1
2009-06-25T17:28:20Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,208
<p>I'll just translate your earlier code:</p> <pre><code>public void fibb(int max) { int a = 0; int b = 1; while (a &lt; max) { System.out.println(a); int temp = a + b; a = b; b = temp; } } </code></pre>
0
2009-06-25T17:29:50Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,252
<p>Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid:</p> <pre><code>public int Fibb(int index) { if (index &lt; 2) return 1; else return Fibb(index-1)+Fibb(index-2); }; </code></pre> <p>Given the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover.</p>
0
2009-06-25T17:39:21Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,259
<p>The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this:</p> <pre><code>Make a list out of 'b' and 'a + b' Make another list out of references to 'a' and 'b' Assign all the elements from the second list to the first one </code></pre> <p>(It might actually be a tuple, I'm not exactly fluent in Python.)</p> <p>So the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java.</p> <p>In general, a statement in Python like</p> <pre><code>var1, var2, ...varN = expression1, expression2, ...expressionN </code></pre> <p>is going to translate in Java to</p> <pre><code>temp1 = expression1; temp2 = expression2; ... tempN = expressionN; var1 = temp1; var2 = temp2; ... varN = tempN; </code></pre> <p>This way all the expressions resolve to values <strong>before</strong> the assignments happen, and none of the assignments have side effects on the expressions.</p> <p>If I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible.</p>
0
2009-06-25T17:40:39Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
1,045,871
<p>There was a recursive solution posted above, but this solution is tail recursive so it grows linearly.</p> <pre><code>public class Fibonacci { public long fibonacci(int number) { return fib(0,1,number); } private long fib(long result, long next, int n) { if (n == 0) return result; else return fib(next, result+next, n-1); } } </code></pre>
0
2009-06-25T19:49:48Z
[ "java", "python" ]
How to create Fibonacci Sequence in Java
1,045,151
<p>I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:</p> <pre><code>a = 0 b = 1 while b &lt; 10: print b a, b = b, b+a </code></pre> <p>The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:</p> <pre><code> public class FibonacciAlgorithm { private Integer a = 0; private Integer b = 1; public FibonacciAlgorithm() { } public Integer increment() { a = b; b = a + b; return value; } public Integer getValue() { return b; } } </code></pre> <p>All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me. </p>
5
2009-06-25T17:20:15Z
2,616,189
<p>i'll do this</p> <pre><code>fib = 100; for(int a = 1, b = 0;a &lt;= fib;a += b, b = (a-b)) { System.out.print(a + ","); } </code></pre>
0
2010-04-11T06:01:41Z
[ "java", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,349
<p>I would not convert unless you are converting as part of an enterprise-wide switch from one language to another. Even then I would avoid converting until absolutely necessary. If it works, why change it? </p>
1
2009-06-25T18:01:24Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,351
<p>Quote: "If it doesn't break, don't fix it."</p> <p>Unless your company is moving towards .NET and/or there are no more qualified Python developer available anymore, then don't.</p>
13
2009-06-25T18:01:33Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,356
<p>Leave them as Python unless you hear a very good <em>business</em> reason to convert.</p>
6
2009-06-25T18:02:34Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,361
<p>There's IronPython , a python implementation for .NET. You could port it to that if you really need to get away from the "standard" python vm and onto the .NET platform</p>
8
2009-06-25T18:03:48Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,378
<p>If you're the only Python developer in a C# shop, then it makes plenty of sense to convert. If you quit tomorrow, no one will be able to maintain these systems.</p>
3
2009-06-25T18:06:03Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,446
<p>Changing languages just for the sake of changing languages is rarely a good idea. If the app is doing its obj then let it do its job. If you've got a corporate mandate to only use C#, that may be a different story (estimate the work involved, give the estimate to management, let them decide to pursue it or write up an exception). Even if there isn't a strong (or any) knowledge of Python across the organization, developers are rather proficient at picking up new languages {it's a survival thing}, so that tends to be less of a concern.</p> <p>Moral of the story, if an app is to be rewritten, there should really be more of a justification to do the rewrite than just to change languages. If you were to add features that would be significantly easier to implement and maintain using another languages library/framework ... good justification. If maintaining the environment/framework for one language is causing a significant operational expense that could be saved by a re-write, cool. "Because our other code is in c#" ... not cool.</p>
4
2009-06-25T18:20:37Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,479
<p>i will convert it from language a to language b for 1 million dollars. &lt;--- this would be the only business reason I would consider legit.</p>
-1
2009-06-25T18:26:16Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,512
<p>As long as the application is running fine there is no reason to switch to C#.</p>
1
2009-06-25T18:32:02Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,532
<p>The only thing I can think of is the performance boost C# will give you.</p>
0
2009-06-25T18:36:13Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,561
<p>Some reasons that come to mind:</p> <ul> <li>Performance </li> <li>Easier to find developers</li> <li>Huge huge huge developer and tools ecosystem</li> </ul> <p>But I second what the others have stated: if it ain't broke, don't fix it. Unless your boss is saying, "hey, we're moving all our crap to .NET", or you're presented with some other business reason for migrating, just stick with what you've got.</p>
0
2009-06-25T18:41:48Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,045,606
<p><strong>IF</strong> you are looking for reasons to convert them, I can think of a few. These don't necessarily mean you <em>should</em>, these are just possible reasons in the "recode" corner.</p> <ul> <li><strong>Maintainability</strong></li> </ul> <p>If you have a dev-shop that is primarily C# focused, then have python applications around may not be useful for maintainability reasons. It would mean that they need to keep python staffers around (assuming it's a complicated app) in order to maintain it. This probably isn't a restriction they want, especially if they don't intend to write <em>anything</em> in python from here on out.</p> <ul> <li><strong>Consistency</strong></li> </ul> <p>This sort of falls under maintainability, but it is of a different flavour. If they wanted to integrate part of this (python) application into a C# application, but not the whole thing, it's possible to write some boilerplate code, but again, that's messy to maintain. Ultimately, you would want to code of P_App to be able to be seamlessly integrated into C#_App, and not have to run them separately. </p> <p><hr /></p> <p>On the other side of the coin, it is fair to point out that you are throwing time and money at converting something which already works. </p>
1
2009-06-25T18:54:54Z
[ "c#", ".net", "python" ]
Is there any good reason to convert an app written in python to c#?
1,045,334
<p>I have written several Python tools for my company. Is there any good reason to convert them from Python to C# now that their usefulness has been proven? Would I be better off just leaving them in Python?</p>
2
2009-06-25T17:59:20Z
1,046,028
<p>Short and to the point answer: No, there is no reason.</p>
1
2009-06-25T20:23:25Z
[ "c#", ".net", "python" ]
How do you create an incremental ID in a Python Class
1,045,344
<p>I would like to create a unique ID for each object I created - here's the class:</p> <blockquote> <pre><code>class resource_cl : def __init__(self, Name, Position, Type, Active): self.Name = Name self.Position = Position self.Type = Type self.Active = Active </code></pre> </blockquote> <p>I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:</p> <blockquote> <pre><code>resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) </code></pre> </blockquote> <p>I know I can reference resource_cl, but I'm not sure how to proceed from there...</p>
7
2009-06-25T18:00:22Z
1,045,368
<p>First, use Uppercase Names for Classes. lowercase names for attributes.</p> <pre><code>class Resource( object ): class_counter= 0 def __init__(self, name, position, type, active): self.name = name self.position = position self.type = type self.active = active self.id= Resource.class_counter Resource.class_counter += 1 </code></pre>
9
2009-06-25T18:04:54Z
[ "python", "class" ]
How do you create an incremental ID in a Python Class
1,045,344
<p>I would like to create a unique ID for each object I created - here's the class:</p> <blockquote> <pre><code>class resource_cl : def __init__(self, Name, Position, Type, Active): self.Name = Name self.Position = Position self.Type = Type self.Active = Active </code></pre> </blockquote> <p>I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:</p> <blockquote> <pre><code>resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) </code></pre> </blockquote> <p>I know I can reference resource_cl, but I'm not sure how to proceed from there...</p>
7
2009-06-25T18:00:22Z
1,045,433
<p>Using count from <a href="http://docs.python.org/library/itertools.html">itertools</a> is great for this:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; counter = itertools.count() &gt;&gt;&gt; a = next(counter) &gt;&gt;&gt; print a 0 &gt;&gt;&gt; print next(counter) 1 &gt;&gt;&gt; print next(counter) 2 &gt;&gt;&gt; class A(object): ... id_generator = itertools.count(100) # first generated is 100 ... def __init__(self): ... self.id = next(self.id_generator) &gt;&gt;&gt; objs = [A(), A()] &gt;&gt;&gt; print objs[0].id, objs[1].id 100 101 &gt;&gt;&gt; print next(counter) # each instance is independent 3 </code></pre> <p>The same interface works if you later need to change how the values are generated, you just change the definition of <code>id_generator</code>.</p>
6
2009-06-25T18:16:54Z
[ "python", "class" ]
How do you create an incremental ID in a Python Class
1,045,344
<p>I would like to create a unique ID for each object I created - here's the class:</p> <blockquote> <pre><code>class resource_cl : def __init__(self, Name, Position, Type, Active): self.Name = Name self.Position = Position self.Type = Type self.Active = Active </code></pre> </blockquote> <p>I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:</p> <blockquote> <pre><code>resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) </code></pre> </blockquote> <p>I know I can reference resource_cl, but I'm not sure how to proceed from there...</p>
7
2009-06-25T18:00:22Z
1,045,491
<p>Are you aware of the <a href="http://docs.python.org/library/functions.html#id" rel="nofollow">id function</a> in python, and could you use it instead of your counter idea?</p> <pre><code>class C(): pass x = C() y = C() print(id(x), id(y)) #(4400352, 16982704) </code></pre>
5
2009-06-25T18:28:23Z
[ "python", "class" ]
How do you create an incremental ID in a Python Class
1,045,344
<p>I would like to create a unique ID for each object I created - here's the class:</p> <blockquote> <pre><code>class resource_cl : def __init__(self, Name, Position, Type, Active): self.Name = Name self.Position = Position self.Type = Type self.Active = Active </code></pre> </blockquote> <p>I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:</p> <blockquote> <pre><code>resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) </code></pre> </blockquote> <p>I know I can reference resource_cl, but I'm not sure how to proceed from there...</p>
7
2009-06-25T18:00:22Z
1,045,724
<p>Concise and elegant:</p> <pre><code>import itertools class resource_cl(): newid = itertools.count().next def __init__(self): self.id = resource_cl.newid() ... </code></pre>
25
2009-06-25T19:16:23Z
[ "python", "class" ]
How do you create an incremental ID in a Python Class
1,045,344
<p>I would like to create a unique ID for each object I created - here's the class:</p> <blockquote> <pre><code>class resource_cl : def __init__(self, Name, Position, Type, Active): self.Name = Name self.Position = Position self.Type = Type self.Active = Active </code></pre> </blockquote> <p>I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:</p> <blockquote> <pre><code>resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) </code></pre> </blockquote> <p>I know I can reference resource_cl, but I'm not sure how to proceed from there...</p>
7
2009-06-25T18:00:22Z
11,548,525
<p>Another note on id() and rethinking other's answer about it. id() may return a unique number, if and only if it remembers every id ever returned even if an object is deleted; which it (id()) does not do. So therefore...</p> <p>In support of what others were saying that id() does not return a unique number; It is true that it can not guarentee a unique value if and only if you are storing those id() values as references to objects AND that you are deleting the instances of objects you are getting id()s for. BUT ! using id() as a reference means that you basically have an object that has a key linked somehow with another object. </p> <p>This is not invalidated by non-uniqueness of id(). It is only invalidated if you do not check if adding a new object has a preexisting id() already stored as a reference to some other instance of the object.</p> <pre><code>storeit = {} object1 = object() print id(object1) 4357891223 storeit[ id(object1) ] = object1 object2 = object() print id(object2) 9834923411 storeit[ id(object2) ] = object2 storeit[ id(object1) ] = object() del object1 object3 = object() print id(object3) # after some 2 gigawatt tries magically i got 4357891223 # the same id as object1 had </code></pre> <p>BUT storeit[ 4357891223 ] returns some other object instance not object3; therefore the &lt; link > remains valid but the uniqueness fails.</p>
0
2012-07-18T19:04:12Z
[ "python", "class" ]
How do you create an incremental ID in a Python Class
1,045,344
<p>I would like to create a unique ID for each object I created - here's the class:</p> <blockquote> <pre><code>class resource_cl : def __init__(self, Name, Position, Type, Active): self.Name = Name self.Position = Position self.Type = Type self.Active = Active </code></pre> </blockquote> <p>I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:</p> <blockquote> <pre><code>resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) </code></pre> </blockquote> <p>I know I can reference resource_cl, but I'm not sure how to proceed from there...</p>
7
2009-06-25T18:00:22Z
11,548,577
<p>I like to use generators for ids. Allow the generator to maintain a list of ids already used.</p> <pre><code># devplayer@gmail.com # 2012-07(jul)-19 class MakeUniqueStr(object): ''' unqstr = MakeUniqueStr(default_name='widget', sep='_') print(repr(unqstr('window'))) print(repr(unqstr('window'))) print(repr(unqstr('window'))) print(repr(unqstr('hello'))) print(repr(unqstr('hello'))) print(repr(unqstr('window'))) print(repr(unqstr('hello'))) 'window' 'window_00000' 'window_00001' 'hello' 'hello_00000' 'window_00002' 'hello_00001' ''' def __init__(self, default_name='default', sep='_'): self.default_name = default_name self.last_base_name = default_name self.sep = sep self.used_names = [] self.generator = self.Generator() self.generator.next() # initialize def __call__(self, name=None): if name &lt;&gt; None: self.last_base_name = name return self.generator.send(self.last_base_name) def _MakeName(self, name, index=1): '''_MakeName is called by the Generator. Generator will always have a name and an index to pass to _MakeName. Over ride this method to customize it.''' return name + self.sep + '%0.5d' % index def Generator(self): try_name = yield 'ready' # initialize index = 0 while 1: if try_name not in self.used_names: self.used_names.append( try_name ) sent_name = yield try_name try_name = sent_name continue try_name = self._MakeName( sent_name, index ) while try_name in self.used_names: index += 1 try_name = self._MakeName( sent_name, index ) index = 0 </code></pre> <p>Although this is not a memory effiecent way for huge in-memory datasets. If you wanted to use something like that then modify this to have the OS handle caching to a file... say via a named pipe.</p>
0
2012-07-18T19:08:24Z
[ "python", "class" ]
How do you create an incremental ID in a Python Class
1,045,344
<p>I would like to create a unique ID for each object I created - here's the class:</p> <blockquote> <pre><code>class resource_cl : def __init__(self, Name, Position, Type, Active): self.Name = Name self.Position = Position self.Type = Type self.Active = Active </code></pre> </blockquote> <p>I would like to have a self.ID that auto increments everytime I create a new reference to the class, such as:</p> <blockquote> <pre><code>resources = [] resources.append(resource_cl('Sam Sneed', 'Programmer', 'full time', True)) </code></pre> </blockquote> <p>I know I can reference resource_cl, but I'm not sure how to proceed from there...</p>
7
2009-06-25T18:00:22Z
11,548,746
<p>Ids sometimes benefit from using some fields of the object you wanted to reference. This is a old style database technique.</p> <p>for example if you have a app that keeps records for incoming customer phone calls, then possible use an id generated by time = some thing else</p> <pre><code>ident = '%s:%.4s:%.9s' % ( time.time(), time.clock(), agent.name ) # don't forget to time.clock() once to initialize it </code></pre> <p>only beaware the time.time() and time.clock() are individual computer return value unless on generated on the server. And if on the server make sure your server clock is set right; as always.</p>
0
2012-07-18T19:18:57Z
[ "python", "class" ]
Can I use Win32 COM to replace text inside a word document?
1,045,628
<p>I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported. I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?</p> <p>Thanks!</p>
4
2009-06-25T18:58:32Z
1,045,690
<p>Checkout this link: <a href="http://python.net/crew/pirx/spam7/" rel="nofollow">http://python.net/crew/pirx/spam7/</a></p> <p>The links on the left side point to the documentation. </p> <p>You can generalize this using the object model, which is found here: </p> <p><a href="http://msdn.microsoft.com/en-us/library/kw65a0we" rel="nofollow">http://msdn.microsoft.com/en-us/library/kw65a0we</a>(VS.80).aspx</p>
2
2009-06-25T19:09:40Z
[ "python", "winapi", "com", "ms-word", "replace" ]
Can I use Win32 COM to replace text inside a word document?
1,045,628
<p>I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported. I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?</p> <p>Thanks!</p>
4
2009-06-25T18:58:32Z
1,045,701
<p>If <a href="http://mail.python.org/pipermail/python-list/2004-April/259213.html" rel="nofollow">this mailing list post</a> is right, accessing the document's text is a simple as:</p> <pre><code>MSWord = win32com.client.Dispatch("Word.Application") MSWord.Visible = 0 MSWord.Documents.Open(filename) docText = MSWord.Documents[0].Content </code></pre> <p>Also see <a href="http://msdn.microsoft.com/en-us/library/f65x8z3d.aspx" rel="nofollow">How to: Search for and Replace Text in Documents</a>. The examples use VB and C#, but the basics should apply to Python too.</p>
3
2009-06-25T19:11:42Z
[ "python", "winapi", "com", "ms-word", "replace" ]
Can I use Win32 COM to replace text inside a word document?
1,045,628
<p>I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported. I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?</p> <p>Thanks!</p>
4
2009-06-25T18:58:32Z
1,045,710
<p>See if <a href="http://www.devshed.com/c/a/Python/Windows-Programming-in-Python/2/">this</a> gives you a start on word automation using python.</p> <p>Once you open a document, you could do the following.<br /> After the following code, you can Close the document &amp; open another.</p> <pre><code>Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = "test" .Replacement.Text = "test2" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchKashida = False .MatchDiacritics = False .MatchAlefHamza = False .MatchControl = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.Find.Execute Replace:=wdReplaceAll </code></pre> <p>The above code replaces the text "test" with "test2" and does a "replace all".<br /> You can turn other options true/false depending on what you need.</p> <p>The simple way to learn this is to create a macro with actions you want to take, see the generated code &amp; use it in your own example (with/without modified parameters).</p> <p>EDIT: After looking at some code by Matthew, you could do the following</p> <pre><code>MSWord.Documents.Open(filename) Selection = MSWord.Selection </code></pre> <p>And then translate the above VB code to Python.<br /> Note: The following VB code is shorthand way of assigning property without using the long syntax.</p> <p>(VB)</p> <pre><code>With Selection.Find .Text = "test" .Replacement.Text = "test2" End With </code></pre> <p>Python</p> <pre><code>find = Selection.Find find.Text = "test" find.Replacement.Text = "test2" </code></pre> <p>Pardon my python knowledge. But, I hope you get the idea to move forward.<br /> Remember to do a Save &amp; Close on Document, after you are done with the find/replace operation.</p> <p>In the end, you could call <code>MSWord.Quit</code> (to release Word object from memory).</p>
8
2009-06-25T19:13:28Z
[ "python", "winapi", "com", "ms-word", "replace" ]
Can I use Win32 COM to replace text inside a word document?
1,045,628
<p>I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported. I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?</p> <p>Thanks!</p>
4
2009-06-25T18:58:32Z
1,045,808
<p>I like the answers so far; <br /> here's a tested example (slightly modified from <a href="http://www.programmingforums.org/post105986.html">here</a>) <br /> that replaces all occurrences of a string in a Word document:</p> <pre><code>import win32com.client def search_replace_all(word_file, find_str, replace_str): ''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` ''' wdFindContinue = 1 wdReplaceAll = 2 # Dispatch() attempts to do a GetObject() before creating a new one. # DispatchEx() just creates a new one. app = win32com.client.DispatchEx("Word.Application") app.Visible = 0 app.DisplayAlerts = 0 app.Documents.Open(word_file) # expression.Execute(FindText, MatchCase, MatchWholeWord, # MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, # Wrap, Format, ReplaceWith, Replace) app.Selection.Find.Execute(find_str, False, False, False, False, False, \ True, wdFindContinue, False, replace_str, wdReplaceAll) app.ActiveDocument.Close(SaveChanges=True) app.Quit() f = 'c:/path/to/my/word.doc' search_replace_all(f, 'string_to_be_replaced', 'replacement_str') </code></pre>
10
2009-06-25T19:36:43Z
[ "python", "winapi", "com", "ms-word", "replace" ]
Can I use Win32 COM to replace text inside a word document?
1,045,628
<p>I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if text replacement is supported. I'd like to be able to perform this task in python? Is it possible? Could you post a code snippet showing how to access the document's text?</p> <p>Thanks!</p>
4
2009-06-25T18:58:32Z
1,063,746
<p>You can also achieve this using <strong>VBScript</strong>. Just type the code into a file named <code>script.vbs</code>, then open a command prompt (Start -> Run -> Cmd), then switch to the folder where the script is and type: <pre><code>cscript script.vbs </code></pre></p> <pre><code> strFolder = "C:\Files" Const wdFormatDocument = 0 'Select all files in strFolder strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colFiles = objWMIService.ExecQuery _ ("ASSOCIATORS OF {Win32_Directory.Name='" & strFolder & "'} Where " _ & "ResultClass = CIM_DataFile") 'Start MS Word Set objWord = CreateObject("Word.Application") Const wdReplaceAll = 2 Const wdOrientLandscape = 1 For Each objFile in colFiles If objFile.Extension = "doc" Then strFile = strFolder & "\" & objFile.FileName & "." & objFile.Extension strNewFile = strFolder & "\" & objFile.FileName & ".doc" Wscript.Echo "Processing " & objFile.Name & "..." Set objDoc = objWord.Documents.Open(strFile) objDoc.PageSetup.Orientation = wdOrientLandscape 'Replace text - ^p in a string stands for new paragraph; ^m stands for page break Set objSelection = objWord.Selection objSelection.Find.Text = "String to replace" objSelection.Find.Forward = TRUE objSelection.Find.Replacement.Text = "New string" objSelection.Find.Execute ,,,,,,,,,,wdReplaceAll objDoc.SaveAs strNewFile, wdFormatDocument objDoc.Close Wscript.Echo "Ready" End If Next objWord.Quit </code></pre>
2
2009-06-30T13:39:50Z
[ "python", "winapi", "com", "ms-word", "replace" ]
Formatting output when writing a list to textfile
1,045,699
<p>i have a list of lists that looks like this:</p> <pre><code>dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt']] </code></pre> <p>I write it to a file using a very basic function():</p> <pre><code>try: file_name = open("dupe.txt", "w") except IOError: pass for a in range (len(dupe)): file_name.write(dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] + "\n"); file_name.close() </code></pre> <p>With the output in the file looking like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt 95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a jude.txt </code></pre> <p>However, how can i make the output in the dupe.txt file to look like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt, knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt, jude.txt </code></pre>
1
2009-06-25T19:11:36Z
1,045,720
<p>If this is your actual answer, you can:</p> <ol> <li>Output one line per every two elements in dupe. This is easier. Or, </li> <li>If your data isn't as structured (so you may you can make a dictionary where your long hash is the key, and the tail end of the string is your output. Make sense?</li> </ol> <p>In idea one, mean that you can something like this:</p> <pre><code>tmp_string = "" for a in range (len(dupe)): if isOdd(a): tmp_string = dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] else: tmp_string += ", " + dupe[a][2] file_name.write(dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] + "\n"); </code></pre> <p>In idea two, you may have something like this:</p> <pre><code>x=dict() for a in range(len(dupe)): # check if the hash exists in x; bad syntax - I dunno "exists?" syntax if (exists(x[dupe[a][0]])): x[a] += "," + dupe[a][2] else: x[a] = dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] for b in x: # bad syntax: basically, for every key in dictionary x file_name.write(x[b]); </code></pre>
0
2009-06-25T19:15:28Z
[ "python", "list" ]
Formatting output when writing a list to textfile
1,045,699
<p>i have a list of lists that looks like this:</p> <pre><code>dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt']] </code></pre> <p>I write it to a file using a very basic function():</p> <pre><code>try: file_name = open("dupe.txt", "w") except IOError: pass for a in range (len(dupe)): file_name.write(dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] + "\n"); file_name.close() </code></pre> <p>With the output in the file looking like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt 95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a jude.txt </code></pre> <p>However, how can i make the output in the dupe.txt file to look like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt, knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt, jude.txt </code></pre>
1
2009-06-25T19:11:36Z
1,045,749
<p>Use a dict to group them:</p> <pre><code>data = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], \ ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], \ ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], \ ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt']] dupes = {} for row in data: if dupes.has_key(row[0]): dupes[row[0]].append(row) else: dupes[row[0]] = [row] for dupe in dupes.itervalues(): print "%s\t%s\t%s" % (dupe[0][0], dupe[0][1], ",".join([x[2] for x in dupe])) </code></pre>
0
2009-06-25T19:23:47Z
[ "python", "list" ]
Formatting output when writing a list to textfile
1,045,699
<p>i have a list of lists that looks like this:</p> <pre><code>dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt']] </code></pre> <p>I write it to a file using a very basic function():</p> <pre><code>try: file_name = open("dupe.txt", "w") except IOError: pass for a in range (len(dupe)): file_name.write(dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] + "\n"); file_name.close() </code></pre> <p>With the output in the file looking like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt 95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a jude.txt </code></pre> <p>However, how can i make the output in the dupe.txt file to look like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt, knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt, jude.txt </code></pre>
1
2009-06-25T19:11:36Z
1,045,751
<p>i take it your last question didn't solve your problem?</p> <p>instead of putting each list with repeating ID's and directories in seperate lists, why not make the file element of the list another sub list which contains all the files which have the same id and directory.</p> <p>so dupe would look like this:</p> <pre><code>dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', ['apa.txt','knark.txt']], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', ['apa2.txt','jude.txt']] </code></pre> <p>then your print loop could be similar to:</p> <pre><code>for i in dupe: print i[0], i[1], for j in i[2] print j, print </code></pre>
1
2009-06-25T19:24:01Z
[ "python", "list" ]
Formatting output when writing a list to textfile
1,045,699
<p>i have a list of lists that looks like this:</p> <pre><code>dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt']] </code></pre> <p>I write it to a file using a very basic function():</p> <pre><code>try: file_name = open("dupe.txt", "w") except IOError: pass for a in range (len(dupe)): file_name.write(dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] + "\n"); file_name.close() </code></pre> <p>With the output in the file looking like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt 95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a jude.txt </code></pre> <p>However, how can i make the output in the dupe.txt file to look like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt, knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt, jude.txt </code></pre>
1
2009-06-25T19:11:36Z
1,045,774
<p>First, group the lines by the "key" (the first two elements of each array):</p> <pre><code>dupedict = {} for a, b, c in dupe: dupedict.setdefault((a,b),[]).append(c) </code></pre> <p>Then print it out:</p> <pre><code>for key, values in dupedict.iteritems(): print ' '.join(key), ', '.join(values) </code></pre>
2
2009-06-25T19:28:20Z
[ "python", "list" ]
Formatting output when writing a list to textfile
1,045,699
<p>i have a list of lists that looks like this:</p> <pre><code>dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt']] </code></pre> <p>I write it to a file using a very basic function():</p> <pre><code>try: file_name = open("dupe.txt", "w") except IOError: pass for a in range (len(dupe)): file_name.write(dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] + "\n"); file_name.close() </code></pre> <p>With the output in the file looking like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt 95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a jude.txt </code></pre> <p>However, how can i make the output in the dupe.txt file to look like this:</p> <pre><code>95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt, knark.txt b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt, jude.txt </code></pre>
1
2009-06-25T19:11:36Z
1,045,785
<pre><code>from collections import defaultdict dupe = [ ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt'], ] with open("dupe.txt", "w") as f: data = defaultdict(list) for hash, dir, fn in dupe: data[(hash, dir)].append(fn) for hash_dir, fns in data.items(): f.write("{0[0]} {0[1]} {1}\n".format(hash_dir, ', '.join(fns))) </code></pre>
1
2009-06-25T19:32:10Z
[ "python", "list" ]
HTTPS log in with urllib2
1,045,886
<p>I currently have a little script that downloads a webpage and extracts some data I'm interested in. Nothing fancy.</p> <p>Currently I'm downloading the page like so:</p> <pre><code>import commands command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx' status, text = commands.getstatusoutput(command) </code></pre> <p>Although this works perfectly, I thought it'd make sense to remove the dependency on wget. I thought it should be trivial to convert the above to urllib2, but thus far I've had zero success. The Internet is full urllib2 examples, but I haven't found anything that matches my need for simple username and password HTTP authentication with a HTTPS server.</p>
5
2009-06-25T19:52:48Z
1,045,905
<p><a href="http://mail.python.org/pipermail/python-list/2003-July/213402.html">this</a> says, it should be straight forward</p> <blockquote> <p>[as] long as your local Python has SSL support.</p> </blockquote> <p>If you use just HTTP Basic Authentication, you must set different handler, as described <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml">here</a>.</p> <p>Quoting the example there:</p> <pre><code>import urllib2 theurl = 'http://www.someserver.com/toplevelurl/somepage.htm' username = 'johnny' password = 'XXXXXX' # a great password passman = urllib2.HTTPPasswordMgrWithDefaultRealm() # this creates a password manager passman.add_password(None, theurl, username, password) # because we have put None at the start it will always # use this username/password combination for urls # for which `theurl` is a super-url authhandler = urllib2.HTTPBasicAuthHandler(passman) # create the AuthHandler opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) # All calls to urllib2.urlopen will now use our handler # Make sure not to include the protocol in with the URL, or # HTTPPasswordMgrWithDefaultRealm will be very confused. # You must (of course) use it when fetching the page though. pagehandle = urllib2.urlopen(theurl) # authentication is now handled automatically for us </code></pre> <p>If you do Digest, you'll have to set some additional headers, but they are the same regardless of SSL usage. <a href="http://www.google.com/search?q=python%2Burllib2%2Bhttp%2Bdigest">Google</a> for python+urllib2+http+digest.</p> <p>Cheers,</p>
5
2009-06-25T19:57:16Z
[ "python", "authentication", "https", "urllib2" ]
HTTPS log in with urllib2
1,045,886
<p>I currently have a little script that downloads a webpage and extracts some data I'm interested in. Nothing fancy.</p> <p>Currently I'm downloading the page like so:</p> <pre><code>import commands command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx' status, text = commands.getstatusoutput(command) </code></pre> <p>Although this works perfectly, I thought it'd make sense to remove the dependency on wget. I thought it should be trivial to convert the above to urllib2, but thus far I've had zero success. The Internet is full urllib2 examples, but I haven't found anything that matches my need for simple username and password HTTP authentication with a HTTPS server.</p>
5
2009-06-25T19:52:48Z
1,046,153
<p>The urllib2 documentation has an example of working with Basic Authentication:</p> <p><a href="http://docs.python.org/library/urllib2.html#examples" rel="nofollow">http://docs.python.org/library/urllib2.html#examples</a></p>
1
2009-06-25T20:40:35Z
[ "python", "authentication", "https", "urllib2" ]
HTTPS log in with urllib2
1,045,886
<p>I currently have a little script that downloads a webpage and extracts some data I'm interested in. Nothing fancy.</p> <p>Currently I'm downloading the page like so:</p> <pre><code>import commands command = 'wget --output-document=- --quiet --http-user=USER --http-password=PASSWORD https://www.example.ca/page.aspx' status, text = commands.getstatusoutput(command) </code></pre> <p>Although this works perfectly, I thought it'd make sense to remove the dependency on wget. I thought it should be trivial to convert the above to urllib2, but thus far I've had zero success. The Internet is full urllib2 examples, but I haven't found anything that matches my need for simple username and password HTTP authentication with a HTTPS server.</p>
5
2009-06-25T19:52:48Z
32,503,699
<p>The <a href="http://www.python-requests.org/en/latest/" rel="nofollow">requests</a> module provides a modern API to HTTP/HTTPS capabilities.</p> <pre class="lang-python prettyprint-override"><code>import requests url = 'https://www.someserver.com/toplevelurl/somepage.htm' res = requests.get(url, auth=('USER', 'PASSWORD')) status = res.status_code text = res.text </code></pre>
1
2015-09-10T13:47:25Z
[ "python", "authentication", "https", "urllib2" ]
Install pyCurl in ActivePython-2.6?
1,045,906
<p>I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6. </p> <p>I have had no problems installing any other modules so far, but am getting errors installing pyCurl. The error:</p> <pre><code>Searching for pycurl Reading http://pypi.python.org/simple/pycurl/ Reading http://pycurl.sourceforge.net/ Reading http://pycurl.sourceforge.net/download/ Best match: pycurl 7.19.0 Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz Processing pycurl-7.19.0.tar.gz Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy sh: curl-config: not found Traceback (most recent call last): File "/opt/ActivePython-2.6/bin/easy_install", line 8, in &lt;module&gt; load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in &lt;lambda&gt; File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup dist.run_commands() File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands self.run_command(cmd) File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command cmd_obj.run() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in &lt;lambda&gt; File "setup.py", line 90, in &lt;module&gt; Exception: `curl-config' not found -- please install the libcurl development files </code></pre> <p>My system does have libcurl installed, but ActivePython doesn't seem to find it. </p> <p>Any ideas will help!</p>
5
2009-06-25T19:57:17Z
1,045,951
<p>It looks like <code>curl-config</code> isn't in your path. Try running it from the command line and adjust the <code>PATH</code> environment variable as needed so that Python can find it.</p>
0
2009-06-25T20:04:36Z
[ "python", "libcurl", "pycurl", "activepython" ]
Install pyCurl in ActivePython-2.6?
1,045,906
<p>I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6. </p> <p>I have had no problems installing any other modules so far, but am getting errors installing pyCurl. The error:</p> <pre><code>Searching for pycurl Reading http://pypi.python.org/simple/pycurl/ Reading http://pycurl.sourceforge.net/ Reading http://pycurl.sourceforge.net/download/ Best match: pycurl 7.19.0 Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz Processing pycurl-7.19.0.tar.gz Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy sh: curl-config: not found Traceback (most recent call last): File "/opt/ActivePython-2.6/bin/easy_install", line 8, in &lt;module&gt; load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in &lt;lambda&gt; File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup dist.run_commands() File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands self.run_command(cmd) File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command cmd_obj.run() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in &lt;lambda&gt; File "setup.py", line 90, in &lt;module&gt; Exception: `curl-config' not found -- please install the libcurl development files </code></pre> <p>My system does have libcurl installed, but ActivePython doesn't seem to find it. </p> <p>Any ideas will help!</p>
5
2009-06-25T19:57:17Z
1,046,375
<p>I couldn't find a curl-config to add to the path, which makes sense as it's not a module that can be called (as far as I can tell)</p> <p>The answer ended up being a bit of a hack, but it works. </p> <p>As I had pyCurl working in my native python2.6 install, I simply copied the curl and pycurl items from the native install into the ActivePython install. </p>
1
2009-06-25T21:35:21Z
[ "python", "libcurl", "pycurl", "activepython" ]
Install pyCurl in ActivePython-2.6?
1,045,906
<p>I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6. </p> <p>I have had no problems installing any other modules so far, but am getting errors installing pyCurl. The error:</p> <pre><code>Searching for pycurl Reading http://pypi.python.org/simple/pycurl/ Reading http://pycurl.sourceforge.net/ Reading http://pycurl.sourceforge.net/download/ Best match: pycurl 7.19.0 Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz Processing pycurl-7.19.0.tar.gz Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy sh: curl-config: not found Traceback (most recent call last): File "/opt/ActivePython-2.6/bin/easy_install", line 8, in &lt;module&gt; load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in &lt;lambda&gt; File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup dist.run_commands() File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands self.run_command(cmd) File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command cmd_obj.run() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in &lt;lambda&gt; File "setup.py", line 90, in &lt;module&gt; Exception: `curl-config' not found -- please install the libcurl development files </code></pre> <p>My system does have libcurl installed, but ActivePython doesn't seem to find it. </p> <p>Any ideas will help!</p>
5
2009-06-25T19:57:17Z
1,400,996
<pre><code>$ apt-cache depends python-pycurl python-pycurl Depends: libc6 Depends: libcurl3-gnutls Depends: libgnutls26 Depends: libidn11 Depends: libkrb53 Depends: libldap-2.4-2 Depends: zlib1g Depends: python Depends: python Depends: python-central [...] </code></pre> <p>So first install the dependencies via <code>sudo aptitude install libcurl3-gnutls</code> (or the package manager of your distribution) and then run <code>easy_install pycurl</code>.</p>
2
2009-09-09T17:31:03Z
[ "python", "libcurl", "pycurl", "activepython" ]
Install pyCurl in ActivePython-2.6?
1,045,906
<p>I have worked with pyCurl in the past and have it working with my system default python install. However, I have a project that requires python to be more portable and I am using ActivePython-2.6. </p> <p>I have had no problems installing any other modules so far, but am getting errors installing pyCurl. The error:</p> <pre><code>Searching for pycurl Reading http://pypi.python.org/simple/pycurl/ Reading http://pycurl.sourceforge.net/ Reading http://pycurl.sourceforge.net/download/ Best match: pycurl 7.19.0 Downloading http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz Processing pycurl-7.19.0.tar.gz Running pycurl-7.19.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-tfVLW6/pycurl-7.19.0/egg-dist-tmp-p1WjAy sh: curl-config: not found Traceback (most recent call last): File "/opt/ActivePython-2.6/bin/easy_install", line 8, in &lt;module&gt; load_entry_point('setuptools==0.6c9', 'console_scripts', 'easy_install')() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1671, in main File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1659, in with_ei_usage File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 1675, in &lt;lambda&gt; File "/opt/ActivePython-2.6/lib/python2.6/distutils/core.py", line 152, in setup dist.run_commands() File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 975, in run_commands self.run_command(cmd) File "/opt/ActivePython-2.6/lib/python2.6/distutils/dist.py", line 995, in run_command cmd_obj.run() File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 211, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 446, in easy_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 476, in install_item File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 655, in install_eggs File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 930, in build_and_install File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/command/easy_install.py", line 919, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 27, in run_setup File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 63, in run File "/opt/ActivePython-2.6/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/setuptools/sandbox.py", line 29, in &lt;lambda&gt; File "setup.py", line 90, in &lt;module&gt; Exception: `curl-config' not found -- please install the libcurl development files </code></pre> <p>My system does have libcurl installed, but ActivePython doesn't seem to find it. </p> <p>Any ideas will help!</p>
5
2009-06-25T19:57:17Z
12,514,310
<p>Following dependencies are needed for installing pycurl:</p> <pre><code>apt-cache depends python-pycurl python-pycurl Depends: libc6 Depends: libcurl3-gnutls Depends: libgcrypt11 Depends: python2.7 Depends: python Depends: python Suggests: libcurl4-gnutls-dev Suggests: python-pycurl-dbg Conflicts: &lt;python2.3-pycurl&gt; Conflicts: &lt;python2.3-pycurl:i386&gt; Conflicts: &lt;python2.4-pycurl&gt; Conflicts: &lt;python2.4-pycurl:i386&gt; Replaces: &lt;python2.3-pycurl&gt; Replaces: &lt;python2.3-pycurl:i386&gt; Replaces: &lt;python2.4-pycurl&gt; Replaces: &lt;python2.4-pycurl:i386&gt; Conflicts: python-pycurl:i386 </code></pre> <p>Run this command </p> <pre><code>sudo apt-get install libcurl4-gnutls-dev librtmp-dev </code></pre> <p>Then you can install pycurl using</p> <pre><code>pip install pycurl </code></pre> <p>or</p> <pre><code>easy_install pycurl </code></pre>
5
2012-09-20T14:02:16Z
[ "python", "libcurl", "pycurl", "activepython" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,099
<p><strong>correct for most circumstances</strong></p> <p>The runtime/language/compiler will abstract those details unless you are dealing directly with word sizes or binary at a low level.</p> <p>Even byteorder is abstracted by the NIC/Network stack in the kernel. It is translated for you. When programming sockets in C, you do sometimes have to deal with byte ordering for the network when sending data ... but that doesn't concern 32 or 64 bit differences.</p> <p>When dealing with blobs of binary data, mapping them from one architecture to another (as an overlay to a C struct for example) can cause problems as others have mentioned, but this is why we develop architecture independent protocols based on characters and so on.</p> <p>In-fact things like Java run in a virtual machine that <strong>abstracts the machine</strong> another step!</p> <p><strong>Knowing a bit</strong> about the instruction set of the architecture, and how the syntax is compiled to that can help you understand the platform and write cleaner, tighter code. I know I grimace at some old C code after studying compilers!</p>
15
2009-06-25T20:34:25Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,100
<p>You will need to care about "endian-ness" only if you send and receive raw C structs over the wire like</p> <pre> ret = send(socket, &myStruct, sizeof(myStruct)); </pre> <p>However this is not a recommended practice.</p> <p>It's recommended that you define a protocol between the parties such it doesn't matter the parties' machine architectures.</p>
0
2009-06-25T20:34:35Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,113
<p>In C++, you have to be very careful if you want to write code that works indifferently on 32 or 64 bits. Many people wrongly assume that <code>int</code> can store a pointer, for example.</p>
0
2009-06-25T20:35:52Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,128
<p>Knowing how things work, be it how the virtual machine works, and how it works on your platform, or how certain C++ constructs are transformed into assembly will always make you a better programmer, because you will understand why things should be done the way they are.</p> <p>You need to understand things like memory to know what cache-misses are and why those might affect your program. You should know how certain things are implemented, even though you might only use an interface or high-level way to get to it, knowing how it works will make sure you're doing it in the best way.</p> <p>For packet work, you need to understand how data is stored on platforms and how sending that across the network to a different platform might change how the data is read (endian-ness).</p> <p>Your compiler will make best use of the platform you're compiling on, so as long as you stick to standards and code well, you can ignore most things and assume the compiler will whip out what's best.</p> <p>So in short, no. You don't need to know the low level stuff, but it <strong>never hurts to know</strong>.</p>
14
2009-06-25T20:37:48Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,141
<p>If you are programming in Python or in Java, the interpreter and the virtual machine respectively abstract this layer of the architecture. You then need not to worry if it's running on a 32 or 64 bits architecture.</p> <p>The same cannot be said for C++, in which you'll have to ask yourself sometimes if you are running on a 32 or 64 bits machine</p>
1
2009-06-25T20:39:10Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,149
<p>In Java and Python, architecture details are abstracted away so that it is in fact more or less impossible to write architecture-dependant code.</p> <p>With C++, this is an entirely different matter - you can certainly write code that does not depend on architecture details, but you have be careful to avoid pitfalls, specifically concerning basic data types that are are architecture-dependant, such as <code>int</code>.</p>
3
2009-06-25T20:40:07Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,180
<p><strong>You sometimes must bother.</strong></p> <p>You can be surprised when these low-level details suddenly jump out and bite you. For example, Java standardized <code>double</code> to be 64 bit. However, Linux JVM uses the "extended precision" mode, when the double is 80 bit as long as it's in the CPU register. This means that the following code may fail:</p> <pre><code>double x = fun1(); double y = x; System.out.println(fun2(x)); assert( y == x ); </code></pre> <p>Simply because y is forced out of the register into memory and truncated from 80 to 64 bits.</p>
5
2009-06-25T20:46:39Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,182
<p>As long as you do things correctly, you almost never need to know for most languages. On many, you never need to know, as the language behavior doesn't vary (Java, for example, specifies the runtime behavior precisely).</p> <p>In C++ and C, doing things correctly includes not making assumptions about int. Don't put pointers in int, and when you're doing anything with memory sizes or addresses use size_t and ptrdiff_t. Don't count on the size of data types: int must be at least 16 bits, almost always is 32, and may be 64 on some architectures. Don't assume that floating-point arithmetic will be done in exactly the same way on different machines (the IEEE standards have some leeway in them).</p> <p>Pretty much all OSes that support networking will give you some way to deal with possible endianness problems. Use them. Use language facilities like isalpha() to classify characters, rather than arithmetic operations on characters (which might be something weird like EBCDIC). (Of course, it's now more usual to use wchar_t as character type, and use Unicode internally.)</p>
2
2009-06-25T20:46:48Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,209
<p>The last time I looked at the Java language spec, it contained a ridiculous gotcha in the section on integer boxing.</p> <pre><code>Integer a = 100; Integer b = 100; System.out.println(a == b); </code></pre> <p>That is guaranteed to print <code>true</code>.</p> <pre><code>Integer a = 300; Integer b = 300; System.out.println(a == b); </code></pre> <p>That is not guaranteed to print <code>true</code>. It depends on the runtime. The spec left it completely open. It's because boxing an int between -128 and 127 returns "interned" objects (analogous to the way string literals are interned), but the implementer of the language runtime is encouraged to raise that limit if they wish.</p> <p>I personally regard that as an insane decision, and I hope they've fixed it since (write once, run anywhere?)</p>
6
2009-06-25T20:53:07Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,298
<p>With java and .net you don't really have to bother with it unless you are doing very low level stuff like twiddling bits. If you are using c, c++, fortran you might get by but I would actually recommend using things like "stdint.h" where you use definitive declares like uint64_t and uint32_t so as to be explicit. Also, you will need to build with particularly libraries depending on how you are linking, for example a 64 bit system might use gcc in a default 64 bit compile mode.</p>
0
2009-06-25T21:12:29Z
[ "java", "c++", "python", "64bit", "32-bit" ]
Would one have to know the machine architecture to write code?
1,046,068
<p>Let's say I'm programming in Java or Python or C++ for a simple problem, could be to build an TCP/UDP echo server or computation of factorial. Do I've to bother about the architecture details, i.e., if it is 32 or 64-bit?</p> <p>IMHO, unless I'm programming something to do with fairly low-level stuff then I don't have to bother if its 32 or 64 bit. Where am I going wrong? Or am I correct???</p>
6
2009-06-25T20:30:22Z
1,046,737
<p>A 32 bit machine will allow you to have a maximum of 4 GB of addressable virtual memory. (In practice, it's even less than that, usually 2 GB or 3 GB depending on the OS and various linker options.) On a 64 bit machine, you can have a HUGE virtual address space (in any practical sense, limited only by disk) and a pretty damn big RAM.</p> <p>So if you are expecting 6GB data sets for some computation (let's say something that needs incoherent access and can't just be streamed a bit at a time), on a 64 bit architecture you could just read it into RAM and do your stuff, whereas on a 32 bit architecture you need a fundamentally different way to approach it, since you simply do not have the option of keeping the entire data set resident.</p>
0
2009-06-25T23:43:56Z
[ "java", "c++", "python", "64bit", "32-bit" ]
python classes that refer to each other
1,046,150
<p>I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?</p> <p><strong>EDIT</strong></p> <p>Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is what I've got and I get an 'name Y not defined error'</p> <pre><code>class X(models.Model): creator = Registry() creator.register(Y) class Y(models.Model): a = models.ForeignKey(X) b = models.CharField(max_length=200) </code></pre> <p>Hope this helps clarify. Any suggestions.</p>
3
2009-06-25T20:40:08Z
1,046,174
<p>UPDATE: He changed the question after my answer. The currently accepted solution is better in light of the new question.</p> <p>What are you saying is the problem?</p> <pre><code>class A(object): def __init__(self): super(A, self).__init__() def b(self): return B() class B(object): def __init__(self): super(B, self).__init__() def a(self): return A() </code></pre> <p>This compiles and runs just fine.</p>
1
2009-06-25T20:45:15Z
[ "python", "django", "oop" ]
python classes that refer to each other
1,046,150
<p>I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?</p> <p><strong>EDIT</strong></p> <p>Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is what I've got and I get an 'name Y not defined error'</p> <pre><code>class X(models.Model): creator = Registry() creator.register(Y) class Y(models.Model): a = models.ForeignKey(X) b = models.CharField(max_length=200) </code></pre> <p>Hope this helps clarify. Any suggestions.</p>
3
2009-06-25T20:40:08Z
1,046,366
<p>As long as you are working within a method you can access the class object.</p> <p>Thus the example above has no problems if <code>creator.register(Y)</code> is moved inside <code>__init__</code>. However, you cannot have circular references to classes outside of methods.</p>
3
2009-06-25T21:31:27Z
[ "python", "django", "oop" ]
python classes that refer to each other
1,046,150
<p>I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?</p> <p><strong>EDIT</strong></p> <p>Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is what I've got and I get an 'name Y not defined error'</p> <pre><code>class X(models.Model): creator = Registry() creator.register(Y) class Y(models.Model): a = models.ForeignKey(X) b = models.CharField(max_length=200) </code></pre> <p>Hope this helps clarify. Any suggestions.</p>
3
2009-06-25T20:40:08Z
1,046,418
<p>In python, the code in a class is run when the class is loaded.</p> <p>Now, what the hell does that mean? ;-)</p> <p>Consider the following code:</p> <pre><code>class x: print "hello" def __init__(self): print "hello again" </code></pre> <p>When you load the module that contains the code, python will print <code>hello</code>. Whenever you create an <code>x</code>, python will print <code>hello again</code>.</p> <p>You can think of <code>def __init__(self): ...</code> as equivalent with <code>__init__ = lambda self: ...</code>, except none of the python lambda restrictions apply. That is, <code>def</code> is an assignment, which might explain why code outside methods but not inside methods is run.</p> <p>When your code says</p> <pre><code>class X(models.Model): creator = Registry() creator.register(Y) </code></pre> <p>You refer to <code>Y</code> when the module is loaded, before <code>Y</code> has a value. You can think of <code>class X</code> as an assignment (but I can't remember the syntax for creating anonymous classes off-hand; maybe it's an invocation of <code>type</code>?)</p> <p>What you may want to do is this:</p> <pre><code>class X(models.Model): pass class Y(models.Model): foo = something_that_uses_(X) X.bar = something_which_uses(Y) </code></pre> <p>That is, create the class attributes of <code>X</code> which reference <code>Y</code> after <code>Y</code> is created. Or vice versa: create <code>Y</code> first, then <code>X</code>, then the attributes of <code>Y</code> which depend on <code>X</code>, if that's easier.</p> <p>Hope this helps :)</p>
11
2009-06-25T21:46:20Z
[ "python", "django", "oop" ]
python classes that refer to each other
1,046,150
<p>I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?</p> <p><strong>EDIT</strong></p> <p>Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is what I've got and I get an 'name Y not defined error'</p> <pre><code>class X(models.Model): creator = Registry() creator.register(Y) class Y(models.Model): a = models.ForeignKey(X) b = models.CharField(max_length=200) </code></pre> <p>Hope this helps clarify. Any suggestions.</p>
3
2009-06-25T20:40:08Z
1,046,426
<p>The error is that execution of <code>creator.register(Y)</code> is attempted during the (executable) definition of class X, and at that stage, class Y is not defined. Understand this: <code>class</code> and <code>def</code> are statements that are executed (typically at import time); they are not "declarations". </p> <p>Suggestion: tell us what you are trying to achieve -- perhaps as a new question.</p>
1
2009-06-25T21:48:00Z
[ "python", "django", "oop" ]
python classes that refer to each other
1,046,150
<p>I have two classes that refer to each other, but obviously the compiler complains. Is there any way around this?</p> <p><strong>EDIT</strong></p> <p>Actually my code is slightly different than what Hank Gay uses. So python can definitely deal with some kinds of circular references, but it tosses an error in the following situation. Below is what I've got and I get an 'name Y not defined error'</p> <pre><code>class X(models.Model): creator = Registry() creator.register(Y) class Y(models.Model): a = models.ForeignKey(X) b = models.CharField(max_length=200) </code></pre> <p>Hope this helps clarify. Any suggestions.</p>
3
2009-06-25T20:40:08Z
1,046,653
<p>The problem is most likely not Python. I would think it is an SQL issue. The classes are via an abstraction layer converted to an SQL query to create a table. You are trying to reference from one table another one that at the time does not exist yet.</p> <p>In SQL you would solve this by creating the table first without the references and after that modify them to make those references,</p> <p>However I am not sure about my answer, so take it with lots of seasoning, I would be actually quite surprised if Django's database abstraction layer doesn't deal with cross references nicely.</p>
0
2009-06-25T23:09:59Z
[ "python", "django", "oop" ]
wxpython: How can I redraw something when a window is retored?
1,046,157
<p>In my wx.Frame based wxpython application, I draw some lines on a panel when some events occur by creating wx.ClientDC instances when needed. The only problem is, if the window is minimized and then restored, the lines disappear! Is there some kind of method that I should override or event to bind to that will allow me to call the drawing method I created when the window is restored?</p> <p>Thanks!</p>
1
2009-06-25T20:42:18Z
1,046,259
<p>When the window is restored it is (on some platforms) repainted using EVT_PAINT handler.</p> <p>The solution is e.g. to draw the same lines in OnPaint(). Or buffer what you draw. See the wxBufferedDC class.</p>
0
2009-06-25T21:03:45Z
[ "python", "wxpython" ]
wxpython: How can I redraw something when a window is retored?
1,046,157
<p>In my wx.Frame based wxpython application, I draw some lines on a panel when some events occur by creating wx.ClientDC instances when needed. The only problem is, if the window is minimized and then restored, the lines disappear! Is there some kind of method that I should override or event to bind to that will allow me to call the drawing method I created when the window is restored?</p> <p>Thanks!</p>
1
2009-06-25T20:42:18Z
1,047,603
<p>only place you must be drawing is on wx.EVT_PAINT, so bind to that event in <strong>init</strong> of panel e.g.</p> <pre><code>self.Bind(wx.EVT_PAINT, self._onPaint) </code></pre> <p>in _onPaint, use wx.PaintDC to to draw e.g.</p> <pre><code>dc = wx.PaintDC(self) dc.DrawLine(0,0,100,100) </code></pre>
1
2009-06-26T06:17:42Z
[ "python", "wxpython" ]
python observer pattern
1,046,190
<p>I'm new to python but I've run into a hitch when trying to implement a variation of the observer pattern.</p> <pre><code>class X(models.Model): a = models.ForeignKey(Voter) b = models.CharField(max_length=200) # Register Y.register(X) </code></pre> <p>This doesn't seem to work because it says X is not defined. A couple of things are possible:</p> <p>A) There is a way to refer to the current class (not the instance, but the class object).</p> <p>B) You can't even run code outside a method. (I thought this may work almost like a static constructor - it would just get run once).</p>
3
2009-06-25T20:48:47Z
1,046,226
<p>There is nothing wrong with running (limited) code in the class definition:</p> <pre><code>class X(object): print("Loading X") </code></pre> <p>However, you can not refer to X because it is not yet fully defined.</p>
4
2009-06-25T20:56:36Z
[ "python", "django" ]
python observer pattern
1,046,190
<p>I'm new to python but I've run into a hitch when trying to implement a variation of the observer pattern.</p> <pre><code>class X(models.Model): a = models.ForeignKey(Voter) b = models.CharField(max_length=200) # Register Y.register(X) </code></pre> <p>This doesn't seem to work because it says X is not defined. A couple of things are possible:</p> <p>A) There is a way to refer to the current class (not the instance, but the class object).</p> <p>B) You can't even run code outside a method. (I thought this may work almost like a static constructor - it would just get run once).</p>
3
2009-06-25T20:48:47Z
1,046,229
<p>In python, code defined in a class block is executed and only <strong>then</strong>, depending on various things---like what has been defined in this block---a class is created. So if you want to relate one class with another, you'd write:</p> <pre><code>class X(models.Model): a = models.ForeignKey(Voter) b = models.CharField(max_length=200) # Register Y.register(X) </code></pre> <p>And this behaviour is not related to django.</p>
5
2009-06-25T20:57:25Z
[ "python", "django" ]
Python - Subprocess - How to call a Piped command in Windows?
1,046,474
<p>How do I run this command with subprocess?</p> <p>I tried:</p> <pre><code>proc = subprocess.Popen( '''ECHO bosco|"C:\Program Files\GNU\GnuPG\gpg.exe" --batch --passphrase-fd 0 --output "c:\docume~1\usi\locals~1\temp\tmptlbxka.txt" --decrypt "test.txt.gpg"''', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) stdout_value, stderr_value = proc.communicate() </code></pre> <p>but got:</p> <pre><code>Traceback (most recent call last): ... File "C:\Python24\lib\subprocess.py", line 542, in __init__ errread, errwrite) File "C:\Python24\lib\subprocess.py", line 706, in _execute_child startupinfo) WindowsError: [Errno 2] The system cannot find the file specified </code></pre> <p>Things I've noticed:</p> <ol> <li>Running the command on the windows console works fine. </li> <li>If I remove the ECHO bosco| part, it runs fine the the popen call above. So I think this problem is related to echo or |.</li> </ol>
5
2009-06-25T22:04:16Z
1,046,522
<p>First and foremost, you don't actually need a pipe; you are just sending input. You can use <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate">subprocess.communicate</a> for that.</p> <p>Secondly, don't specify the command as a string; that's messy as soon as filenames with spaces are involved.</p> <p>Thirdly, if you really wanted to execute a piped command, just call the shell. On Windows, I believe it's <code>cmd /c program name arguments | further stuff</code>.</p> <p>Finally, single back slashes can be dangerous: <code>"\p"</code> is <code>'\\p'</code>, but <code>'\n'</code> is a new line. Use <a href="http://docs.python.org/library/os.path.html#os.path.join">os.path.join()</a> or <a href="http://docs.python.org/library/os.html#os.sep">os.sep</a> or, if specified outside python, just a forward slash.</p> <pre><code>proc = subprocess.Popen( ['C:/Program Files/GNU/GnuPG/gpg.exe', '--batch', '--passphrase-fd', '0', '--output ', 'c:/docume~1/usi/locals~1/temp/tmptlbxka.txt', '--decrypt', 'test.txt.gpg',], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) stdout_value, stderr_value = proc.communicate('bosco') </code></pre>
11
2009-06-25T22:18:50Z
[ "python", "subprocess", "pipe", "echo", "popen" ]