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
Add Quotes in url string from file
543,199
<p>I need script to add quotes in url string from url.txt</p> <p>from <code>http://www.site.com/info.xx</code> to <code>"http://www.site.com/info.xx"</code></p>
2
2009-02-12T20:54:42Z
543,445
<p>If '<code>url.txt</code>' contains a list of urls, one url per line then:</p> <ul> <li><p>quote the first non-whitespace character sequence:</p> <pre><code>$ perl -pe"s~\S+~\"$&amp;\"~" url.txt </code></pre></li> <li><p>or trim whitespaces and quote the rest:</p> <pre><code>$ perl -nE"$_=trim; say qq(\"$_\")" url.txt </code></pre></li> </ul>
0
2009-02-12T21:42:06Z
[ "python", "ruby", "perl" ]
Add Quotes in url string from file
543,199
<p>I need script to add quotes in url string from url.txt</p> <p>from <code>http://www.site.com/info.xx</code> to <code>"http://www.site.com/info.xx"</code></p>
2
2009-02-12T20:54:42Z
781,210
<p>A simple Perl script:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; while (my $line = &lt;&gt;) { $line =~ s/\s*(.*)\s*/$1/; print qq/"$line"\n/; } </code></pre>
0
2009-04-23T10:54:29Z
[ "python", "ruby", "perl" ]
Python string formatting
543,399
<p>I see you guys using</p> <pre><code>url = '"%s"' % url # This part &gt;&gt;&gt; url = "http://www.site.com/info.xx" &gt;&gt;&gt; print url http://www.site.com/info.xx &gt;&gt;&gt; url = '"%s"' % url &gt;&gt;&gt; print url "http://www.site.com/info.xx" </code></pre> <p>Is it advanced Python? Is there a tutorial for it? How can I learn about it?</p>
2
2009-02-12T21:34:14Z
543,416
<p>It is not advanced, you can use ' or " to define a string.</p> <p>Check the <a href="http://docs.python.org/reference/lexical_analysis.html#strings" rel="nofollow">documentation</a>.</p>
0
2009-02-12T21:37:33Z
[ "python" ]
Python string formatting
543,399
<p>I see you guys using</p> <pre><code>url = '"%s"' % url # This part &gt;&gt;&gt; url = "http://www.site.com/info.xx" &gt;&gt;&gt; print url http://www.site.com/info.xx &gt;&gt;&gt; url = '"%s"' % url &gt;&gt;&gt; print url "http://www.site.com/info.xx" </code></pre> <p>Is it advanced Python? Is there a tutorial for it? How can I learn about it?</p>
2
2009-02-12T21:34:14Z
543,417
<p>That line of code is using Python string formatting. You can read up more on how to use it here: <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">http://docs.python.org/library/stdtypes.html#string-formatting</a></p>
8
2009-02-12T21:37:36Z
[ "python" ]
Python string formatting
543,399
<p>I see you guys using</p> <pre><code>url = '"%s"' % url # This part &gt;&gt;&gt; url = "http://www.site.com/info.xx" &gt;&gt;&gt; print url http://www.site.com/info.xx &gt;&gt;&gt; url = '"%s"' % url &gt;&gt;&gt; print url "http://www.site.com/info.xx" </code></pre> <p>Is it advanced Python? Is there a tutorial for it? How can I learn about it?</p>
2
2009-02-12T21:34:14Z
543,427
<p>No, but <code>//</code> for comments sure is advanced Python. Try a <code>#</code> prefix for comments.</p>
4
2009-02-12T21:39:37Z
[ "python" ]
Python string formatting
543,399
<p>I see you guys using</p> <pre><code>url = '"%s"' % url # This part &gt;&gt;&gt; url = "http://www.site.com/info.xx" &gt;&gt;&gt; print url http://www.site.com/info.xx &gt;&gt;&gt; url = '"%s"' % url &gt;&gt;&gt; print url "http://www.site.com/info.xx" </code></pre> <p>Is it advanced Python? Is there a tutorial for it? How can I learn about it?</p>
2
2009-02-12T21:34:14Z
543,453
<p>It's common string formatting, and very useful. It's analogous to C-style printf formatting. See <a href="http://docs.python.org/library/stdtypes.html#string-formatting">String Formatting Operations</a> in the Python.org docs. You can use multiple arguments like this:</p> <pre><code>"%3d\t%s" % (42, "the answer to ...") </code></pre>
10
2009-02-12T21:43:26Z
[ "python" ]
Using different versions of python for different projects in Eclipse
543,466
<p>So, I'm slowly working in some Python 3.0, but I still have a lot of things that rely on 2.5. </p> <p>But, in Eclipse, every time I change projects between a 3.0 and a 2.5, I need to go through </p> <p>Project -> Properties -> project type.</p> <p><strong>Issue 1:</strong> if I just switch the interpreter in the drop down box, that doesn't seem to change anything. I need to click "click here to configure an interpreter not listed", and <strong>UP</strong> the interpreter I wish to use. </p> <p><strong>Issue 2:</strong> That would be fine if I was switching to 3.0 for every project for the rest of my life, but I still am doing a lot of switching between projects and I don't see that changing anytime soon. So, I'm just trying to save a few operations. </p> <p>Is there a way to configure Eclipse so that it remembers which interpreter I want associated with which project? </p> <p>What if I created an entirely new workspace? Is "interpreter" a property of a workspace? </p> <p>Also, it doesn't seem to matter what I choose when I create a new project via File -> New -> Pydev Project. Whatever I last selected through "Properties" is what eclipse is using.</p> <p>This is Eclipse 3.4.0, running in Windows XP. </p>
12
2009-02-12T21:45:27Z
545,718
<p>OK --</p> <p>It definitely seems like "interpreter" is a property of your "workspace". I hadn't really considered that too much because I always thought of the workspace as "a folder in which I keep whatever" instead of a consistent unified environment for one kind of development. </p> <p>Also, you can't switch between workspaces in one instance of Eclipse (it shuts down and restarts), but you can run two instances of Eclipse at once, one for each workspace. </p> <p>Now, I guess I like the fact that Eclipse handles it that way. It has a more "modular" feel, and what originally bothered me I now think it sensible. I don't need to worry about having two interpreters to choose from, or choosing the default or moving one up. I just need to worry about which workspace I'm in. </p> <p>Hope this helps someone. . .</p> <p><em>EDIT: as noted by <strong>Kiv</strong>, "interpreter" is not a property of your "workspace" (as I stated above). Instead, for any project, there is a "run configuration" (incidentally, there is also a debug configuration). The run config allows the user to set the executable, and the path, and a number of other options.</em></p> <p>*I'm sure these things are known to long-time users, but I never had to deal with this until I changed python versions.**</p>
1
2009-02-13T12:14:14Z
[ "python", "eclipse" ]
Using different versions of python for different projects in Eclipse
543,466
<p>So, I'm slowly working in some Python 3.0, but I still have a lot of things that rely on 2.5. </p> <p>But, in Eclipse, every time I change projects between a 3.0 and a 2.5, I need to go through </p> <p>Project -> Properties -> project type.</p> <p><strong>Issue 1:</strong> if I just switch the interpreter in the drop down box, that doesn't seem to change anything. I need to click "click here to configure an interpreter not listed", and <strong>UP</strong> the interpreter I wish to use. </p> <p><strong>Issue 2:</strong> That would be fine if I was switching to 3.0 for every project for the rest of my life, but I still am doing a lot of switching between projects and I don't see that changing anytime soon. So, I'm just trying to save a few operations. </p> <p>Is there a way to configure Eclipse so that it remembers which interpreter I want associated with which project? </p> <p>What if I created an entirely new workspace? Is "interpreter" a property of a workspace? </p> <p>Also, it doesn't seem to matter what I choose when I create a new project via File -> New -> Pydev Project. Whatever I last selected through "Properties" is what eclipse is using.</p> <p>This is Eclipse 3.4.0, running in Windows XP. </p>
12
2009-02-12T21:45:27Z
545,880
<p>You can set the interpreter version on a per-script basis through the Run Configurations menu.</p> <p>To do this go to Run -> Run Configurations, and then make a new entry under Python Run. Fill in your project name and the main script, and then go to the Interpeter tab and you can pick which interpreter you want to use for that script.</p> <p>I've used this to have Python 2.2, 2.5, and 3.0 projects in the same workspace.</p>
7
2009-02-13T13:16:16Z
[ "python", "eclipse" ]
Struct with a pointer to its own type in ctypes
543,483
<p>I'm trying to map a struct definition using ctypes:</p> <pre><code>struct attrl { struct attrl *next; char *name; char *resource; char *value; }; </code></pre> <p>I'm unsure what to do with the "next" field of the struct in the ctypes mapping. A definition like:</p> <pre><code>class attrl(Structure): _fields_ = [ ("next", attrl), ("name", c_char_p), ("resource", c_char_p), ("value", c_char_p) ] </code></pre> <p>results in:</p> <pre><code>NameError: name 'attrl' is not defined </code></pre>
3
2009-02-12T21:47:04Z
543,539
<p>You need the equivalent of a forward declaration, <a href="http://python.net/crew/theller/ctypes/tutorial.html#incomplete-types" rel="nofollow">as described here</a>.</p>
3
2009-02-12T21:54:01Z
[ "python", "ctypes" ]
Why is KeyboardInterrupt not working in python?
543,534
<p>Why doesn't code like the following catch CTRL-C?</p> <pre><code>MAXVAL = 10000 STEP_INTERVAL = 10 for i in range(1, MAXVAL, STEP_INTERVAL): try: print str(i) except KeyboardInterrupt: break print "done" </code></pre> <p>My expectation is -- if CTRL-C is pressed while program is running, <code>KeyboardInterrupt</code> is supposed to leave the loop. It does not.</p> <p>Any help on what I'm doing wrong?</p>
3
2009-02-12T21:53:42Z
543,598
<p>It does break out of the loop and print "done". </p>
0
2009-02-12T22:00:13Z
[ "python" ]
Why is KeyboardInterrupt not working in python?
543,534
<p>Why doesn't code like the following catch CTRL-C?</p> <pre><code>MAXVAL = 10000 STEP_INTERVAL = 10 for i in range(1, MAXVAL, STEP_INTERVAL): try: print str(i) except KeyboardInterrupt: break print "done" </code></pre> <p>My expectation is -- if CTRL-C is pressed while program is running, <code>KeyboardInterrupt</code> is supposed to leave the loop. It does not.</p> <p>Any help on what I'm doing wrong?</p>
3
2009-02-12T21:53:42Z
543,605
<p>It works.</p> <p>I'm using Ubuntu Linux, and you? Test it again using something like MaxVal = 10000000</p>
1
2009-02-12T22:01:18Z
[ "python" ]
Why is KeyboardInterrupt not working in python?
543,534
<p>Why doesn't code like the following catch CTRL-C?</p> <pre><code>MAXVAL = 10000 STEP_INTERVAL = 10 for i in range(1, MAXVAL, STEP_INTERVAL): try: print str(i) except KeyboardInterrupt: break print "done" </code></pre> <p>My expectation is -- if CTRL-C is pressed while program is running, <code>KeyboardInterrupt</code> is supposed to leave the loop. It does not.</p> <p>Any help on what I'm doing wrong?</p>
3
2009-02-12T21:53:42Z
543,628
<p>Sounds like the program is done by the time control-c has been hit, but your operating system hasn't finished showing you all the output. .</p>
14
2009-02-12T22:04:34Z
[ "python" ]
Why is KeyboardInterrupt not working in python?
543,534
<p>Why doesn't code like the following catch CTRL-C?</p> <pre><code>MAXVAL = 10000 STEP_INTERVAL = 10 for i in range(1, MAXVAL, STEP_INTERVAL): try: print str(i) except KeyboardInterrupt: break print "done" </code></pre> <p>My expectation is -- if CTRL-C is pressed while program is running, <code>KeyboardInterrupt</code> is supposed to leave the loop. It does not.</p> <p>Any help on what I'm doing wrong?</p>
3
2009-02-12T21:53:42Z
543,912
<p>code flow is as follows:</p> <ol> <li><code>for</code> grabs new object from list (generated by <code>range</code>) and sets <code>i</code> to it</li> <li><code>try</code></li> <li><code>print</code></li> <li>go back to <code>1</code></li> </ol> <p>If you hit CTRL-C in the part 1 it is outside the <code>try</code>/<code>except</code>, so it won't catch the exception.</p> <p>Try this instead:</p> <pre><code>MaxVal = 10000 StepInterval = 10 try: for i in range(1, MaxVal, StepInterval): print i except KeyboardInterrupt: pass print "done" </code></pre>
11
2009-02-12T23:01:11Z
[ "python" ]
Mapping a global variable from a shared library with ctypes
544,173
<p>I'd like to map an int value <code>pbs_errno</code> declared as a global in the library <code>libtorque.so</code> using ctypes.</p> <p>Currently I can load the library like so:</p> <pre><code>from ctypes import * libtorque = CDLL("libtorque.so") </code></pre> <p>and have successfully mapped a bunch of the functions. However, for error checking purposes many of them set the <code>pbs_errno</code> variable so I need access to that as well. However if I try to access it I get:</p> <pre><code>&gt;&gt;&gt; pytorque.libtorque.pbs_errno &lt;_FuncPtr object at 0x9fc690&gt; </code></pre> <p>Of course, it's not a function pointer and attempting to call it results in a seg fault.</p> <p>It's declared as <code>int pbs_errno;</code> in the main header and <code>extern int pbs_errno;</code> in the API header files.</p> <p>Objdump shows the symbol as:</p> <pre><code>00000000001294f8 g DO .bss 0000000000000004 Base pbs_errno </code></pre>
12
2009-02-13T00:11:38Z
546,128
<p>There's a section in the ctypes docs about accessing values exported in dlls:</p> <p><a href="http://docs.python.org/library/ctypes.html#accessing-values-exported-from-dlls">http://docs.python.org/library/ctypes.html#accessing-values-exported-from-dlls</a></p> <p>e.g.</p> <pre> def pbs_errno(): return c_int.in_dll(libtorque, "pbs_errno") </pre>
15
2009-02-13T14:30:16Z
[ "python", "ctypes" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
544,487
<p>Maybe this isn't the answer you're looking for, but if all you need is to turn the key into bits, it looks like it's Base64 encoded. Look at the <code>codecs</code> module (I think) in the standard Python library.</p>
1
2009-02-13T02:13:10Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
544,625
<p>A public key contains both a modulus(very long number, can be 1024bit, 2058bit, 4096bit) and a public key exponent(much smaller number, usually equals one more than a two to some power). You need to find out how to split up that public key into the two components before you can do anything with it. </p> <p>I don't know much about pycrypto but to verify a signature, take the hash of the string. Now we must decrypt the signature. Read up on <a href="http://en.wikipedia.org/wiki/Modular_exponentiation" rel="nofollow">modular exponentiation</a>; the formula to decrypt a signature is <code>message^public exponent % modulus</code>. The last step is to check if the hash you made and the decrypted signature you got are the same.</p>
2
2009-02-13T03:44:34Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
545,237
<p>The data between the markers is the base64 encoding of the ASN.1 DER-encoding of a PKCS#8 PublicKeyInfo containing an PKCS#1 RSAPublicKey.</p> <p>That is a lot of standards, and you will be best served with using a crypto-library to decode it (such as M2Crypto as <a href="http://stackoverflow.com/questions/544433/how-do-you-verify-an-rsa-sha1-signature-in-python/546043#546043">suggested by joeforker</a>). Treat the following as some fun info about the format:</p> <p>If you want to, you can decode it like this:</p> <p>Base64-decode the string:</p> <pre><code>30819f300d06092a864886f70d010101050003818d0030818902818100df1b822e14eda1fcb74336 6a27c06370e6cad69d4116ce806b3d117534cf0baa938c0f8e4500fb59d4d98fb471a8d01012d54b 32244197c7434f27c1b0d73fa1b8bae55e70155f907879ce9c25f28a9a92ff97de1684fdaff05dce 196ae76845f598b328c5ed76e0f71f6a6b7448f08691e6a556f5f0d773cb20d13f629b6391020301 0001 </code></pre> <p>This is the DER-encoding of:</p> <pre><code> 0 30 159: SEQUENCE { 3 30 13: SEQUENCE { 5 06 9: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1) 16 05 0: NULL : } 18 03 141: BIT STRING 0 unused bits, encapsulates { 22 30 137: SEQUENCE { 25 02 129: INTEGER : 00 DF 1B 82 2E 14 ED A1 FC B7 43 36 6A 27 C0 63 : 70 E6 CA D6 9D 41 16 CE 80 6B 3D 11 75 34 CF 0B : AA 93 8C 0F 8E 45 00 FB 59 D4 D9 8F B4 71 A8 D0 : 10 12 D5 4B 32 24 41 97 C7 43 4F 27 C1 B0 D7 3F : A1 B8 BA E5 5E 70 15 5F 90 78 79 CE 9C 25 F2 8A : 9A 92 FF 97 DE 16 84 FD AF F0 5D CE 19 6A E7 68 : 45 F5 98 B3 28 C5 ED 76 E0 F7 1F 6A 6B 74 48 F0 : 86 91 E6 A5 56 F5 F0 D7 73 CB 20 D1 3F 62 9B 63 : 91 157 02 3: INTEGER 65537 : } : } : } </code></pre> <p>For a 1024 bit RSA key, you can treat <code>"30819f300d06092a864886f70d010101050003818d00308189028181"</code> as a constant header, followed by a 00-byte, followed by the 128 bytes of the RSA modulus. After that 95% of the time you will get <code>0203010001</code>, which signifies a RSA public exponent of 0x10001 = 65537.</p> <p>You can use those two values as <code>n</code> and <code>e</code> in a tuple to construct a RSAobj.</p>
23
2009-02-13T08:54:06Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
545,249
<p><del>I think <a href="http://www.freenet.org.nz/ezPyCrypto" rel="nofollow">ezPyCrypto</a> might make this a little easier. The high-level methods of the <strong>key</strong> class includes these two methods which I hope will solve your problem:</del> </p> <ul> <li><del><a href="http://www.freenet.org.nz/ezPyCrypto/detail/public/ezPyCrypto.key-class.html#verifyString" rel="nofollow">verifyString</a> - verify a string against a signature</del></li> <li><del><a href="http://www.freenet.org.nz/ezPyCrypto/detail/public/ezPyCrypto.key-class.html#importKey" rel="nofollow">importKey</a> - import public key (and possibly private key too)</del></li> </ul> <p><a href="http://stackoverflow.com/users/5542/rasmus-faber">Rasmus</a> points out in the comments that <code>verifyString</code> is hard-coded to use MD5, in which case ezPyCryto can't help Andrew unless he wades into its code. I defer to <a href="http://stackoverflow.com/questions/544433/how-do-you-verify-an-rsa-sha1-signature-in-python/546476#546476">joeforker's answer</a>: consider <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.X509-module.html" rel="nofollow">M2Crypto</a>.</p>
1
2009-02-13T09:01:22Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
546,476
<p>Use <a href="http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.X509-module.html">M2Crypto</a>. Here's how to verify for RSA and any other algorithm supported by OpenSSL:</p> <pre><code>pem = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY-----""" # your example key from M2Crypto import BIO, RSA, EVP bio = BIO.MemoryBuffer(pem) rsa = RSA.load_pub_key_bio(bio) pubkey = EVP.PKey() pubkey.assign_rsa(rsa) # if you need a different digest than the default 'sha1': pubkey.reset_context(md='sha1') pubkey.verify_init() pubkey.verify_update('test message') assert pubkey.verify_final(signature) == 1 </code></pre>
27
2009-02-13T15:59:41Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
25,032,181
<p>More on the DER decoding. </p> <p>DER encoding always follows a TLV triplet format: (Tag, Length, Value) </p> <ul> <li>Tag specifies the type (i.e. data structure) of the value </li> <li>Length specifies the number of byte this value field occupies</li> <li>Value is the actual value which could be another triplet</li> </ul> <p>Tag basically tells how to interpret the bytes data in the Value field. ANS.1 does have a type system, e.g. 0x02 means integer, 0x30 means sequence (an ordered collection of one or more other type instances) </p> <p>Length presentation has a special logic: </p> <ul> <li>If the length &lt; 127, the L field only uses one byte and coded as the length number value directly</li> <li>If the length > 127, then in the first byte of L field, the first bit must be 1, and the rest 7 bits represents the number of following bytes used to specifies the length of the Value field. Value, the actually bytes of the value itself.</li> </ul> <p>For example, say I want to encode a number of 256 bytes long, then it would be like this </p> <pre><code>02 82 01 00 1F 2F 3F 4F … DE AD BE EF </code></pre> <ul> <li>Tag, 0x02 means it's a number</li> <li>Length, 0x82, bit presentation of it is 1000 0010, meaning the following two bytes specifies the actually length of the value, which his 0x0100 meaning the value field is 256 bytes long</li> <li>Value, from 1F to EF, the actual 256 bytes.</li> </ul> <p>Now looking at your example </p> <pre><code>30819f300d06092a864886f70d010101050003818d0030818902818100df1b822e14eda1fcb74336 6a27c06370e6cad69d4116ce806b3d117534cf0baa938c0f8e4500fb59d4d98fb471a8d01012d54b 32244197c7434f27c1b0d73fa1b8bae55e70155f907879ce9c25f28a9a92ff97de1684fdaff05dce 196ae76845f598b328c5ed76e0f71f6a6b7448f08691e6a556f5f0d773cb20d13f629b6391020301 0001 </code></pre> <p>It interprets as just what Rasmus Faber put in his reply</p>
1
2014-07-30T08:34:34Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
25,195,849
<p>I try the code given by joeforker but it does not work. Here is my example code and it works fine.</p> <pre><code>from Crypto.Signature import PKCS1_v1_5 from Crypto.PublicKey import RSA from Crypto.Hash import SHA pem = """-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY-----""" # your example key key = RSA.importKey(pem) h = SHA.new(self.populateSignStr(params)) verifier = PKCS1_v1_5.new(key) if verifier.verify(h, signature): print "verified" else: print "not verified" </code></pre>
-1
2014-08-08T03:59:08Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
How do you verify an RSA SHA1 signature in Python?
544,433
<p>I've got a string, a signature, and a public key, and I want to verify the signature on the string. The key looks like this:</p> <pre><code>-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDfG4IuFO2h/LdDNmonwGNw5srW nUEWzoBrPRF1NM8LqpOMD45FAPtZ1NmPtHGo0BAS1UsyJEGXx0NPJ8Gw1z+huLrl XnAVX5B4ec6cJfKKmpL/l94WhP2v8F3OGWrnaEX1mLMoxe124Pcfamt0SPCGkeal VvXw13PLINE/YptjkQIDAQAB -----END PUBLIC KEY----- </code></pre> <p>I've been reading the pycrypto docs for a while, but I can't figure out how to make an RSAobj with this kind of key. If you know PHP, I'm trying to do the following:</p> <pre><code>openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA1); </code></pre> <p>Also, if I'm confused about any terminology, please let me know.</p>
27
2009-02-13T01:50:48Z
29,301,357
<p>Using M2Crypto, the above answers does not work. Here is a tested example.</p> <pre><code>import base64 import hashlib import M2Crypto as m2 # detach the signature from the message if it's required in it (useful for url encoded data) message_without_sign = message.split("&amp;SIGN=")[0] # decode base64 the signature binary_signature = base64.b64decode(signature) # create a pubkey object with the public key stored in a separate file pubkey = m2.RSA.load_pub_key(os.path.join(os.path.dirname(__file__), 'pubkey.pem')) # verify the key assert pubkey.check_key(), 'Key Verification Failed' # digest the message sha1_hash = hashlib.sha1(message_without_sign).digest() # and verify the signature assert pubkey.verify(data=sha1_hash, signature=binary_signature), 'Certificate Verification Failed' </code></pre> <p>And that's about it</p>
0
2015-03-27T13:03:19Z
[ "python", "cryptography", "rsa", "sha1", "signature" ]
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?
544,542
<p>I am trying to plot a bunch of data points (many thousands) in Python using <a href="http://matplotlib.sourceforge.net/index.html">matplotlib</a> so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:</p> <pre><code> matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black') </code></pre> <p>Then I can look at it either with <code>pl.show()</code> and then save it. Or directly use <code>plt.savefig('filename.ps')</code> in the code to save it. The problem is this: when I use <code>pl.show()</code> to view the file in the GUI it looks great with small tiny black marks, however when I save from the <code>show()</code> GUI to a file or use directly <code>savefig</code> and then view the <code>ps</code> I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like <a href="http://linil.wordpress.com/2008/09/16/cairoplot-11/">CairoPlot</a>, but I want to keep using matplotlib for now.</p> <p><strong>Update:</strong> It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a <code>.ps</code> later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting?</p>
8
2009-02-13T02:41:45Z
544,610
<p>If you haven't, you should try saving in a rasterizing engine -- save it to a PNG file and see if that fixes it. If you need a vector plot, try saving to PDF and converting with an external utility. I've also had problems before with the PS engine that were resolved by saving with the Agg or PDF engines and converting externally.</p>
2
2009-02-13T03:32:39Z
[ "python", "coding-style", "matplotlib" ]
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?
544,542
<p>I am trying to plot a bunch of data points (many thousands) in Python using <a href="http://matplotlib.sourceforge.net/index.html">matplotlib</a> so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:</p> <pre><code> matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black') </code></pre> <p>Then I can look at it either with <code>pl.show()</code> and then save it. Or directly use <code>plt.savefig('filename.ps')</code> in the code to save it. The problem is this: when I use <code>pl.show()</code> to view the file in the GUI it looks great with small tiny black marks, however when I save from the <code>show()</code> GUI to a file or use directly <code>savefig</code> and then view the <code>ps</code> I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like <a href="http://linil.wordpress.com/2008/09/16/cairoplot-11/">CairoPlot</a>, but I want to keep using matplotlib for now.</p> <p><strong>Update:</strong> It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a <code>.ps</code> later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting?</p>
8
2009-02-13T02:41:45Z
638,511
<p>For nice-looking vectorized output, don't use the <code>'.'</code> marker style. Use e.g. <code>'o'</code> (circle) or <code>'s'</code> (square) (see <code>help(plot)</code> for the options) and set the <code>markersize</code> keyword argument to something suitably small, e.g.:</p> <pre><code>plot(x, y, 'ko', markersize=2) savefig('foo.ps') </code></pre> <p>That <code>'.'</code> (point) produces less nice results could be construed as a bug in matplotlib, but then, what <em>should</em> "point" mean in a vector graphic format?</p>
10
2009-03-12T12:58:58Z
[ "python", "coding-style", "matplotlib" ]
Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?
544,542
<p>I am trying to plot a bunch of data points (many thousands) in Python using <a href="http://matplotlib.sourceforge.net/index.html">matplotlib</a> so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:</p> <pre><code> matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black') </code></pre> <p>Then I can look at it either with <code>pl.show()</code> and then save it. Or directly use <code>plt.savefig('filename.ps')</code> in the code to save it. The problem is this: when I use <code>pl.show()</code> to view the file in the GUI it looks great with small tiny black marks, however when I save from the <code>show()</code> GUI to a file or use directly <code>savefig</code> and then view the <code>ps</code> I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like <a href="http://linil.wordpress.com/2008/09/16/cairoplot-11/">CairoPlot</a>, but I want to keep using matplotlib for now.</p> <p><strong>Update:</strong> It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a <code>.ps</code> later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting?</p>
8
2009-02-13T02:41:45Z
1,248,476
<p>Have you tried the ',' point shape? Maybe you can play with markersize as well, with this shape?</p>
4
2009-08-08T09:57:43Z
[ "python", "coding-style", "matplotlib" ]
problem ordering by votes with django-voting
544,597
<p>I have a model Post, and a model Vote. Vote (form django-voting) is essentially just a pointer to a Post and -1, 0, or 1. </p> <p>There is also Tourn, which is a start date and an end date. A Post made between the start and end of a Tourn is submitted to that tournament.</p> <p>For the sake of rep calculation, I'm trying to find the top 3 winners of a tournament. This is what I have:</p> <pre><code> posts = Post.objects.filter(status=2, created_at__range=(tourn.start_date, tourn.end_date)) start = tourn.start_date - timedelta(days=1) end = tourn.end_date + timedelta(days=1) qn = connection.ops.quote_name ctype = ContentType.objects.get_for_model(Post) posts.extra(select={'score': """ SELECT SUM(vote) FROM %s WHERE content_type_id = %s AND object_id = %s.id AND voted_at &gt; DATE(%s) AND voted_at &lt; DATE(%s) """ % (qn(Vote._meta.db_table), ctype.id, qn(Post._meta.db_table), start, end)}, order_by=['-score']) if tourn.limit_to_category: posts.filter(category=tourn.category) if len(posts) &gt;= 1: tourn_winners_1.append(posts[0].author) resp += " 1: " + posts[0].author.username + "\n" if len(posts) &gt;= 2: tourn_winners_2.append(posts[1].author) resp += " 2: " + posts[1].author.username + "\n" if len(posts) &gt;= 3: tourn_winners_3.append(posts[2].author) resp += " 3: " + posts[2].author.username + "\n" </code></pre> <p>It seems simple enough, but for some reason the results are wrong.</p> <p>The query that gets made is thus:</p> <pre><code>SELECT "blog_post"."id", "blog_post"."title", "blog_post"."slug", "blog_post"."a uthor_id", "blog_post"."creator_ip", "blog_post"."body", "blog_post"."tease", "b log_post"."status", "blog_post"."allow_comments", "blog_post"."publish", "blog_p ost"."created_at", "blog_post"."updated_at", "blog_post"."markup", "blog_post"." tags", "blog_post"."category_id" FROM "blog_post" WHERE ("blog_post"."status" = 2 AND "blog_post"."created_at" BETWEEN 2008-12-21 00:00:00 and 2009-01-04 00:00 :00) ORDER BY "blog_post"."publish" DESC </code></pre> <p>It seems that posts.extra() isn't getting applied to the query at all...</p>
1
2009-02-13T03:25:23Z
547,787
<p>I think you need to assign <code>posts</code> to the return value of <code>posts.extra()</code>:</p> <pre><code>posts = posts.extra(select={'score': """ SELECT SUM(vote) FROM %s WHERE content_type_id = %s AND object_id = %s.id AND voted_at &gt; DATE(%s) AND voted_at &lt; DATE(%s) """ % (qn(Vote._meta.db_table), ctype.id, qn(Post._meta.db_table), start, end)}, order_by=['-score']) </code></pre>
3
2009-02-13T21:34:47Z
[ "python", "django", "django-voting" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
544,944
<p>Short answer: no. </p> <p>Long answer: this is possible with some ugly hacks using traceback, inspect and the like, but it's generally probably not recommended for production code. For example see: </p> <ul> <li><a href="http://groups.google.com/group/comp.lang.python/msg/237dc92f3629dd9a?pli=1">http://groups.google.com/group/comp.lang.python/msg/237dc92f3629dd9a?pli=1</a></li> <li><a href="http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/330294">http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/330294</a></li> </ul> <p>Perhaps you can use a workaround to translate the value back to a name/representational string. If you post some more sample code and details about what you're wanting this for maybe we can provide more in-depth assistance.</p>
23
2009-02-13T06:38:01Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
544,954
<p>As far as I know, that will require some introspection. You can try using the inspect module.</p> <p>There are a few simple things you may want to try before that:</p> <ol> <li> This is not the exact code that should be used. You will have to retrieve the variable name from __dict__ before printing. <pre> print myEnum.__dict__ </pre> </li> <li> If you want to print the variable name from inside the function, you can try the functions - vars(), locals() and globals(). <br/><strong>Edit</strong>: <br/> I just noticed that this is not what you want. In that case adding a dict and a function may work </li> <li> You may want to print the __dict__ of the class of your enums. </li> </ol> <p>All that said, there aren't standard enumerations in Python. It would help to know how you are creating them.</p> <p>On second thoughts, you can maintain your variables as a dictionary in the enum, keyed by variable name and provide a method of the enumeration to find the right variable and print its name. This solution (keeping a dict) is bad because variable values aren't necessarily unique.</p> <p><strong>Edit</strong>: <br/> The problem is not trivial, so you may want to use a tried and tested solution. IMHO, you would be better off avoiding the situation if you can.</p>
1
2009-02-13T06:43:23Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
544,957
<p>You could store the canonical name as an attribute of the instance, and then assign it to a variable with the same name. This might work:</p> <pre><code>class MyEnum(object): def __new__(cls, name): try: return getattr(MyEnum, name) except AttributeError: e = super(MyEnum, cls).__new__(cls) e.name = name setattr(MyEnum, name, e) return e </code></pre> <p>Regardless, it's not a particularly "Pythonic" thing to do.</p>
3
2009-02-13T06:43:56Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
544,966
<p>To add to <a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/544944#544944">@Jay's answer</a>, some concepts...</p> <p>Python "variables" are simply references to values. Each value occupies a given memory location (see <code>id()</code>) </p> <pre><code>&gt;&gt;&gt; id(1) 10052552 &gt;&gt;&gt; sys.getrefcount(1) 569 </code></pre> <p>From the above, you may notice that the value "1" is present at the memory location 10052552. It is referred to 569 times in this instance of the interpreter. </p> <pre><code>&gt;&gt;&gt; MYVAR = 1 &gt;&gt;&gt; sys.getrefcount(1) 570 </code></pre> <p>Now, see that because yet another name is bound to this value, the reference count went up by one.</p> <p>Based on these facts, it is not realistic/possible to tell what single variable name is pointing to a value.</p> <p>I think the best way to address your issue is to add a mapping and function to your enum reference back to a string name.</p> <pre><code>myEnum.get_name(myEnum.SomeNameA) </code></pre> <p>Please comment if you would like sample code.</p>
21
2009-02-13T06:45:43Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
544,968
<p>Erlang has a concept called "atoms" -- they are similar to string constants or enumerations. Consider using a string constant as the value of your enum -- the same as the name of the enum.</p>
0
2009-02-13T06:46:47Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
545,089
<p>Just use the text you want to print as the value of the enum, as in</p> <pre><code>class MyEnum (object): valueA = "valueA" valueB = "valueB" </code></pre> <p>comparing strings for identity is almost as efficient in Python as is comparing integer values (this is due to the fact the strings are immutable as have a hash value)</p> <p>Of course there are easier ways to create the enum in the first place:</p> <pre><code>class Enum (object): def __init__(self, *values): for v in values: self.__dict__[v] = v </code></pre> <p>Then, create you enumeration like this:</p> <pre><code>MyEnum = Enum("valueA", "valueB") </code></pre> <p>ans access the same way as above:</p> <pre><code>MyEnum.valueA </code></pre>
5
2009-02-13T07:47:56Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
545,663
<p>There is no such thing as a unique or original variable name <a href="http://www.amk.ca/quotations/python-quotes/page-8">http://www.amk.ca/quotations/python-quotes/page-8</a></p> <blockquote> <p>The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object)...</p> <p>....and don't be surprised if you'll find that it's known by many names, or no name at all!</p> <p><strong>Fredrik Lundh, 3 Nov 2000, in answer to the question "How can I get the name of a variable from C++ when I have the PyObject*?"</strong></p> </blockquote>
17
2009-02-13T11:50:19Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
545,742
<p>On second thought:</p> <p>Since Python does not provide native Enum types, you should not ask for one, but instead use other, more powerful construct to build your program. Otherwise, the next step will invariably be "Why does Python not have a <code>switch ...:</code> statement, and how do I best emulate it?"</p> <p>Since Enums are often used to define some kind of state, a much better approach is this: Create a base class that define all the abstract properties, attributes and methods belonging to a state. Then, for each state, derive a sub class that implements the specific behavior of this state. You can then pass around these classes (or maybe instances thereof) to handle the state and its behaviour.</p> <p>If you use classes instead of instances (the Python way of a "singleton"), you can simply check for any given state (not that it should be necessary) by <code>if current_state is StateA:</code> (note the <code>is</code> instead of <code>==</code>) with no performance penalty over comparing integer values.</p> <p>And of course, you can define a <code>name</code> attribute and a <code>__str__()</code> method to access and print the state's name.</p>
3
2009-02-13T12:28:17Z
[ "python", "variables" ]
Can I print original variable's name in Python?
544,919
<p>I have enum and use the variables like <code>myEnum.SomeNameA</code>, <code>myEnum.SomeNameB</code>, etc. When I return one of these variables from a function, can I print their names (such as <code>myEnum.SomeNameA</code>) instead of the value they returned?</p>
31
2009-02-13T06:30:06Z
593,251
<p>There are two answers to this question: <em>Yes</em> and <em>No</em>.</p> <pre> Can you do it? -- Yes (in most cases) Is it worth it? -- No (in most cases) </pre> <h3>How to do it:</h3> <p>It depends on an implementation of enums. For example:</p> <pre><code>class Enum: A = 1 B = 2 </code></pre> <p>It doesn't matter whether there are 100 names refers to an integer whose name you'd like to find <em>if you know enums class object and all they're names (or at least a unique prefix) in that class</em>.</p> <p>For the example above <a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/544954#544954">as @batbrat suggested</a> you can inspect '<code>Enum.__dict__</code>' using <a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python/592891#592891"><code>namestr()</code></a>:</p> <pre><code> &gt;&gt;&gt; getEnum = lambda: Enum.A &gt;&gt;&gt; namestr(getEnum(), Enum.__dict__) &gt;&gt;&gt; ['A'] </code></pre> <p>In this case you even don't have to know all enum names. If enums implemented differently then you might need to use a different hack. There will be some solution in most cases e.g., see <a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/544944#544944">@Jay's answer</a>. But it doesn't matter because..</p> <h3>Is it worth it?</h3> <ul> <li><p>Some enum implementations may require ugly, complex and in the end unreliable hacks to implement <code>namestr()</code>.</p></li> <li><p>Enum class can return answer by itself (see <a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/544957#544957">@David's</a>, <a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/545089#545089">@Ber's</a>, <a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/544966#544966">@gahooa's</a> answers).</p></li> <li><p>As <a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name/545742#545742">@Ber pointed out</a> there is no builtin Enum and switch statement in Python (see <a href="http://www.python.org/dev/peps/pep-0275/" rel="nofollow">PEP-0275</a>, <a href="http://www.python.org/dev/peps/pep-3103/" rel="nofollow">PEP-3103</a>). It is worth investigating solutions without enums.</p></li> </ul>
4
2009-02-27T01:51:36Z
[ "python", "variables" ]
Best method for reading newline delimited files in Python and discarding the newlines?
544,921
<p>I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.</p> <p>What I've come up with is the following code, include throwaway code to test.</p> <pre><code>import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x </code></pre> <p>Suggestions?</p>
68
2009-02-13T06:31:11Z
544,932
<pre><code>lines = open(filename).read().splitlines() </code></pre>
169
2009-02-13T06:35:50Z
[ "python", "file", "readline" ]
Best method for reading newline delimited files in Python and discarding the newlines?
544,921
<p>I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.</p> <p>What I've come up with is the following code, include throwaway code to test.</p> <pre><code>import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x </code></pre> <p>Suggestions?</p>
68
2009-02-13T06:31:11Z
544,935
<pre><code>for line in file('/tmp/foo'): print line.strip('\n') </code></pre>
7
2009-02-13T06:36:08Z
[ "python", "file", "readline" ]
Best method for reading newline delimited files in Python and discarding the newlines?
544,921
<p>I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.</p> <p>What I've come up with is the following code, include throwaway code to test.</p> <pre><code>import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x </code></pre> <p>Suggestions?</p>
68
2009-02-13T06:31:11Z
544,958
<p>I'd do it like this:</p> <pre><code>f = open('test.txt') l = [l for l in f.readlines() if l.strip()] f.close() print l </code></pre>
2
2009-02-13T06:43:59Z
[ "python", "file", "readline" ]
Best method for reading newline delimited files in Python and discarding the newlines?
544,921
<p>I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.</p> <p>What I've come up with is the following code, include throwaway code to test.</p> <pre><code>import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x </code></pre> <p>Suggestions?</p>
68
2009-02-13T06:31:11Z
545,188
<p>Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip.</p> <pre><code>lines = (line.rstrip('\n') for line in open(filename)) </code></pre> <p>However, you'll most likely want to use this to get rid of trailing whitespaces too.</p> <pre><code>lines = (line.rstrip() for line in open(filename)) </code></pre>
19
2009-02-13T08:35:46Z
[ "python", "file", "readline" ]
Best method for reading newline delimited files in Python and discarding the newlines?
544,921
<p>I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.</p> <p>What I've come up with is the following code, include throwaway code to test.</p> <pre><code>import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x </code></pre> <p>Suggestions?</p>
68
2009-02-13T06:31:11Z
545,574
<p>I use this</p> <pre><code>def cleaned( aFile ): for line in aFile: yield line.strip() </code></pre> <p>Then I can do things like this.</p> <pre><code>lines = list( cleaned( open("file","r") ) ) </code></pre> <p>Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.</p>
3
2009-02-13T11:07:27Z
[ "python", "file", "readline" ]
Best method for reading newline delimited files in Python and discarding the newlines?
544,921
<p>I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.</p> <p>What I've come up with is the following code, include throwaway code to test.</p> <pre><code>import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x </code></pre> <p>Suggestions?</p>
68
2009-02-13T06:31:11Z
548,697
<p>Just use generator expressions:</p> <pre><code>blahblah = (l.rstrip() for l in open(filename)) for x in blahblah: print x </code></pre> <p>Also I want to advise you against reading whole file in memory -- looping over generators is much more efficient on big datasets.</p>
4
2009-02-14T07:43:58Z
[ "python", "file", "readline" ]
Best method for reading newline delimited files in Python and discarding the newlines?
544,921
<p>I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.</p> <p>What I've come up with is the following code, include throwaway code to test.</p> <pre><code>import os def getfile(filename,results): f = open(filename) filecontents = f.readlines() for line in filecontents: foo = line.strip('\n') results.append(foo) return results blahblah = [] getfile('/tmp/foo',blahblah) for x in blahblah: print x </code></pre> <p>Suggestions?</p>
68
2009-02-13T06:31:11Z
6,978,940
<p>What do you think about this approach?</p> <pre><code>with open(filename) as data: datalines = (line.rstrip('\r\n') for line in data) for line in datalines: ...do something awesome... </code></pre> <p>Generator expression avoids loading whole file into memory and <code>with</code> ensures closing the file</p>
8
2011-08-08T07:26:31Z
[ "python", "file", "readline" ]
Switching Printer Trays
544,923
<p>I know this question has been asked before, but there was no clear answer. </p> <p>How do I change the printer tray programmatically?</p> <p>I am trying to use python to batch print some PDFs. I need to print different pages from different trays. The printer is a Ricoh 2232C. Is there a way to do it through and Acrobat Reader command line parameter? I am able to use the Win32 api to find out which bins correspond to which binnames, but that is about it. Any advice/shortcuts/etc?</p>
5
2009-02-13T06:32:56Z
544,963
<p>There is no easy way to do this, since you indicate you want to choose specific pages from the pdf and print them to specific bins using Acrobat Reader </p> <p>Example: Print page 1 on letterhead bin 1, page 2 on stock bin 2</p> <p>Acrobat Reader only allows printing of the whole document from the command line:</p> <p>You could alter the freeware <a href="http://pages.cs.wisc.edu/~ghost/doc/GPL/index.htm" rel="nofollow">Ghostscript</a> and do what you want.</p> <p>or this commercial product should do the job. <a href="http://www.globalpdf.com/pdfprint/pdf-print-cmd.html" rel="nofollow">PDFPrint</a></p> <p><hr /></p> <p>See the Acrobat Reader <a href="http://www.adobe.com/devnet/acrobat/pdfs/Acrobat_SDK_developer_faq.pdf" rel="nofollow">developer FAQ</a> on page 24 for more details</p> <p><strong>AcroRd32.exe /t path "printername" "drivername" "portname"</strong> — Start Adobe Reader and print a file while suppressing the Print dialog box. The path must be fully specified.</p> <p>The four parameters of the /t option evaluate to path, printername, drivername, and portname (all strings).</p> <p><strong>printername</strong> — The name of your printer.</p> <p><strong>drivername</strong> — Your printer driver’s name, as it appears in your printer’s properties.</p> <p><strong>portname</strong> — The printer’s port. portname cannot contain — Your printer driver’s name, as it appears in your printer’s properties.</p> <p><strong>portname</strong> — The printer’s port. portname cannot contain</p>
1
2009-02-13T06:45:28Z
[ "python", "winapi" ]
Switching Printer Trays
544,923
<p>I know this question has been asked before, but there was no clear answer. </p> <p>How do I change the printer tray programmatically?</p> <p>I am trying to use python to batch print some PDFs. I need to print different pages from different trays. The printer is a Ricoh 2232C. Is there a way to do it through and Acrobat Reader command line parameter? I am able to use the Win32 api to find out which bins correspond to which binnames, but that is about it. Any advice/shortcuts/etc?</p>
5
2009-02-13T06:32:56Z
545,183
<p>That's not possible using plain PDF, as you have create new <em>print job</em> for any particular bin and tray combination (and not all printers allow you to do that, Xerox 4x and DP Series allows you to do such things).</p> <p>My best bet would be juggling with PostScript: convert PDF to PostScript, where you have access to individual pages, then extract the pages you need and for each such page (or pages) create new print job (eg. using Windows program <code>lpr</code>). To ease the task, I'd create print queue for any combination of bin and tray you have to print to, then use these queues as printers.</p>
1
2009-02-13T08:33:27Z
[ "python", "winapi" ]
Switching Printer Trays
544,923
<p>I know this question has been asked before, but there was no clear answer. </p> <p>How do I change the printer tray programmatically?</p> <p>I am trying to use python to batch print some PDFs. I need to print different pages from different trays. The printer is a Ricoh 2232C. Is there a way to do it through and Acrobat Reader command line parameter? I am able to use the Win32 api to find out which bins correspond to which binnames, but that is about it. Any advice/shortcuts/etc?</p>
5
2009-02-13T06:32:56Z
551,704
<p>Ok, I figured this out. The answer is: <br/> <br/> 1. you need a local printer (if you need to print to a network printer, download the drivers and add it as a local printer)<br/> 2. use win32print to get and set default printer<br/> 3. also using win32print, use the following code:<br/> <br/></p> <pre><code>import win32print PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter('RICOH-LOCAL', PRINTER_DEFAULTS) properties = win32print.GetPrinter(pHandle, 2) #get the properties pDevModeObj = properties["pDevMode"] #get the devmode automaticTray = 7 tray_one = 1 tray_two = 3 tray_three = 2 printer_tray = [] pDevModeObj.DefaultSource = tray_three #set the tray properties["pDevMode"]=pDevModeObj #write the devmode back to properties win32print.SetPrinter(pHandle,2,properties,0) #save the properties to the printer </code></pre> <ol> <li>that's it, the tray has been changed<br/></li> <li><p>printing is accomplished using internet explorer (from Graham King's blog)<br/></p> <pre><code>from win32com import client import time ie = client.Dispatch("InternetExplorer.Application") def printPDFDocument(filename): ie.Navigate(filename) if ie.Busy: time.sleep(1) ie.Document.printAll() ie.Quit() </code></pre></li> </ol> <p>Done</p>
5
2009-02-15T22:09:30Z
[ "python", "winapi" ]
Switching Printer Trays
544,923
<p>I know this question has been asked before, but there was no clear answer. </p> <p>How do I change the printer tray programmatically?</p> <p>I am trying to use python to batch print some PDFs. I need to print different pages from different trays. The printer is a Ricoh 2232C. Is there a way to do it through and Acrobat Reader command line parameter? I am able to use the Win32 api to find out which bins correspond to which binnames, but that is about it. Any advice/shortcuts/etc?</p>
5
2009-02-13T06:32:56Z
14,751,866
<p>You already have a Ricoh machine, just get yourself the Ricoh Print&amp;Share software and there you can define what trays you want to use!</p> <p>These videos show you how to set up the Ricoh Print&amp;Share software:</p> <ul> <li><a href="http://www.youtube.com/watch?v=6iXuU4b5mh4" rel="nofollow">http://www.youtube.com/watch?v=6iXuU4b5mh4</a></li> <li><a href="http://www.youtube.com/watch?v=cZg0byBj_w0" rel="nofollow">http://www.youtube.com/watch?v=cZg0byBj_w0</a></li> <li><a href="http://www.youtube.com/watch?v=Hf5sndsWr6I" rel="nofollow">http://www.youtube.com/watch?v=Hf5sndsWr6I</a></li> </ul>
0
2013-02-07T13:08:33Z
[ "python", "winapi" ]
Kerberos authentication with python
545,294
<p>I need to write a script in python to check a webpage, which is protected by kerberos. Is there any possibility to do this from within python and how? The script is going to be deployed on a linux environment with python 2.4.something installed.</p> <p>dertoni</p>
10
2009-02-13T09:15:43Z
545,499
<p>I think that <code>python-krbV</code> and most Linux distributions also have a <code>python-kerberos</code> package. For example, Debian has one of the same name. Here's the documentation on <a href="http://packages.debian.org/testing/python/python-kerberos" rel="nofollow">it</a></p> <p>Extract from link:</p> <blockquote> <p>"This Python package is a high-level wrapper for Kerberos (GSSAPI) operations. The goal is to avoid having to build a module that wraps the entire Kerberos.framework, and instead offer a limited set of functions that do what is needed for client/server Kerberos authentication based on <a href="http://www.ietf.org/rfc/rfc4559.txt" rel="nofollow">http://www.ietf.org/rfc/rfc4559.txt</a>. "</p> </blockquote>
11
2009-02-13T10:33:42Z
[ "python", "security", "kerberos" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
545,398
<p>If you just want to hash the contents of the files, ignoring the filenames then you can use</p> <pre><code>cat $FILES | md5sum </code></pre> <p>Make sure you have the files in the same order when computing the hash:</p> <pre><code>cat $(echo $FILES | sort) | md5sum </code></pre> <p>But you can't have directories in your list of files.</p>
3
2009-02-13T09:54:41Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
545,403
<p>Try to make it in two steps:</p> <ol> <li>create a file with hashes for all files in a folder</li> <li>hash this file</li> </ol> <p>Like so:</p> <pre><code># for FILE in `find /folder/of/stuff -type f | sort`; do sha1sum $FILE &gt;&gt; hashes; done # sha1sum hashes </code></pre> <p>Or do it all at once:</p> <pre><code># cat `find /folder/of/stuff -type f | sort` | sha1sum </code></pre>
0
2009-02-13T09:57:08Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
545,404
<p>You could <code>sha1sum</code> to generate the list of hash values and then <code>sha1sum</code> that list again, it depends on what exactly it is you want to accomplish.</p>
0
2009-02-13T09:57:21Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
545,410
<p>I would pipe the results for individual files through <code>sort</code> (to prevent a mere reordering of files to change the hash) into <code>md5sum</code> or <code>sha1sum</code>, whichever you choose.</p>
1
2009-02-13T09:58:39Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
545,413
<p>One possible way would be:<pre> sha1sum path/to/folder/* | sha1sum </pre></p> <p>If there is a whole directory tree, you're probably better off using find and xargs. One possible command would be <pre> find path/to/folder -type f -print0 | xargs -0 sha1sum | sha1sum </pre></p> <p><b>Edit</b>: Good point, it's probably a good thing to sort the list of files, so:<pre> find path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum </pre></p> <p>And, finally, if you also need to take account of permissions and empty directories:</p> <pre><code>(find path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum; find path/to/folder \( -type f -o -type d \) -print0 | sort -z | \ xargs -0 stat -c '%n %a') \ | sha1sum </code></pre> <p>The arguments to <code>stat</code> will cause it to print the name of the file, followed by its octal permissions. The two finds will run one after the other, causing double the amount of disk IO, the first finding all file names and checksumming the contents, the second finding all file and directory names, printing name and mode. The list of "file names and checksums", followed by "names and directories, with permissions" will then be checksummed, for a smaller checksum.</p>
48
2009-02-13T09:59:36Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
545,420
<ul> <li><p>Commit the directory to git, use the commit hash. See <a href="http://david.hardeman.nu/software.php#metastore">metastore</a> for a way to also control permissions.</p></li> <li><p>Use a file system intrusion detection tool like <a href="http://sourceforge.net/projects/aide/">aide</a>.</p></li> <li><p>hash a tar ball of the directory:</p> <p>tar cvf - /path/to/folder | sha1sum</p></li> <li><p>Code something yourself, like <a href="http://stackoverflow.com/questions/545387/linux-compute-a-single-hash-for-a-given-folder-contents/545413#545413">vatine's oneliner</a>:</p> <p>find /path/to/folder -type f -print0 | sort -z | xargs -0 sha1sum | sha1sum</p></li> </ul>
11
2009-02-13T10:04:00Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
545,567
<p>What's wrong with a <code>tar -c /path/to/folder | sha1sum</code>?</p>
5
2009-02-13T11:04:56Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
4,796,653
<p>There is a python script for that:</p> <p><a href="http://code.activestate.com/recipes/576973-getting-the-sha-1-or-md5-hash-of-a-directory/" rel="nofollow">http://code.activestate.com/recipes/576973-getting-the-sha-1-or-md5-hash-of-a-directory/</a></p> <p>If you change the names of a file without changing their alphabetical order, the hash script will not detect it. But, if you change the order of the files or the contents of any file, running the script will give you a different hash than before.</p>
2
2011-01-25T17:12:41Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
31,702,032
<p>Another tool to achieve this:</p> <p><a href="http://md5deep.sourceforge.net/" rel="nofollow">http://md5deep.sourceforge.net/</a></p> <p>As is sounds: like md5sum but also recursive, plus other features.</p>
1
2015-07-29T13:35:42Z
[ "python", "linux", "bash", "hash" ]
Linux: compute a single hash for a given folder & contents?
545,387
<p>Surely there must be a way to do this easily! </p> <p>I've tried the linux command-line apps sha1sum &amp; md5sum but they seem only to be able to compute hashes of individual files and output a list of hash values, one for each file. </p> <p>I need to generate a single hash for the entire contents of a folder (not just the filenames).</p> <p>I'd like to do something like</p> <pre><code>sha1sum /folder/of/stuff &gt; singlehashvalue </code></pre> <p><strong>Edit:</strong> to clarify, my files are at multiple levels in a directory tree, they're not all sitting in the same root folder.</p>
33
2009-02-13T09:51:40Z
36,270,989
<p>I've written a Groovy script to do this:</p> <pre><code>import java.security.MessageDigest public static String generateDigest(File file, String digest, int paddedLength){ MessageDigest md = MessageDigest.getInstance(digest) md.reset() def files = [] def directories = [] if(file.isDirectory()){ file.eachFileRecurse(){sf -&gt; if(sf.isFile()){ files.add(sf) } else{ directories.add(file.toURI().relativize(sf.toURI()).toString()) } } } else if(file.isFile()){ files.add(file) } files.sort({a, b -&gt; return a.getAbsolutePath() &lt;=&gt; b.getAbsolutePath()}) directories.sort() files.each(){f -&gt; println file.toURI().relativize(f.toURI()).toString() f.withInputStream(){is -&gt; byte[] buffer = new byte[8192] int read = 0 while((read = is.read(buffer)) &gt; 0){ md.update(buffer, 0, read) } } } directories.each(){d -&gt; println d md.update(d.getBytes()) } byte[] digestBytes = md.digest() BigInteger bigInt = new BigInteger(1, digestBytes) return bigInt.toString(16).padLeft(paddedLength, '0') } println "\n${generateDigest(new File(args[0]), 'SHA-256', 64)}" </code></pre> <p>You can customize the usage to avoid printing each file, change the message digest, take out directory hashing, etc. I've tested it against the NIST test data and it works as expected. <a href="http://www.nsrl.nist.gov/testdata/" rel="nofollow">http://www.nsrl.nist.gov/testdata/</a></p> <pre><code>gary-macbook:Scripts garypaduana$ groovy dirHash.groovy /Users/garypaduana/.config .DS_Store configstore/bower-github.yml configstore/insight-bower.json configstore/update-notifier-bower.json filezilla/filezilla.xml filezilla/layout.xml filezilla/lockfile filezilla/queue.sqlite3 filezilla/recentservers.xml filezilla/sitemanager.xml gtk-2.0/gtkfilechooser.ini a/ configstore/ filezilla/ gtk-2.0/ lftp/ menus/ menus/applications-merged/ 79de5e583734ca40ff651a3d9a54d106b52e94f1f8c2cd7133ca3bbddc0c6758 </code></pre>
1
2016-03-28T20:53:26Z
[ "python", "linux", "bash", "hash" ]
Using base class constructor as factory in Python?
545,419
<p>I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways? </p> <p>I've tried to read help about metaclasses but without big success.</p> <p>Here example of what I'm doing.</p> <pre><code>class Project(object): "Base class and factory." def __init__(self, url): if is_url_local(url): self.__class__ = ProjectLocal else: self.__class__ = ProjectRemote self.url = url class ProjectLocal(Project): def do_something(self): # do the stuff locally in the dir pointed by self.url class ProjectRemote(Project): def do_something(self): # do the stuff communicating with remote server pointed by self.url </code></pre> <p>Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:</p> <pre><code>project = Project('http://example.com') project.do_something() </code></pre> <p>I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:</p> <pre><code>def project_factory(url): if is_url_local(url): return ProjectLocal(url) else: return ProjectRemote(url) project = project_factory(url) project.do_something() </code></pre> <p>Is my first approach just matter of taste or it has some hidden pitfalls?</p>
5
2009-02-13T10:03:19Z
545,444
<p>I think the second approach using a factory function is a lot cleaner than making the implementation of your base class depend on its subclasses.</p>
0
2009-02-13T10:14:23Z
[ "python", "factory" ]
Using base class constructor as factory in Python?
545,419
<p>I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways? </p> <p>I've tried to read help about metaclasses but without big success.</p> <p>Here example of what I'm doing.</p> <pre><code>class Project(object): "Base class and factory." def __init__(self, url): if is_url_local(url): self.__class__ = ProjectLocal else: self.__class__ = ProjectRemote self.url = url class ProjectLocal(Project): def do_something(self): # do the stuff locally in the dir pointed by self.url class ProjectRemote(Project): def do_something(self): # do the stuff communicating with remote server pointed by self.url </code></pre> <p>Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:</p> <pre><code>project = Project('http://example.com') project.do_something() </code></pre> <p>I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:</p> <pre><code>def project_factory(url): if is_url_local(url): return ProjectLocal(url) else: return ProjectRemote(url) project = project_factory(url) project.do_something() </code></pre> <p>Is my first approach just matter of taste or it has some hidden pitfalls?</p>
5
2009-02-13T10:03:19Z
545,446
<p>I would stick with the factory function approach. It's very standard python and easy to read and understand. You could make it more generic to handle more options in several ways such as by passing in the discriminator function and a map of results to classes. </p> <p>If the first example works it's more by luck than by design. What if you wanted to have an <code>__init__</code> defined in your subclass? </p>
12
2009-02-13T10:15:37Z
[ "python", "factory" ]
Using base class constructor as factory in Python?
545,419
<p>I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways? </p> <p>I've tried to read help about metaclasses but without big success.</p> <p>Here example of what I'm doing.</p> <pre><code>class Project(object): "Base class and factory." def __init__(self, url): if is_url_local(url): self.__class__ = ProjectLocal else: self.__class__ = ProjectRemote self.url = url class ProjectLocal(Project): def do_something(self): # do the stuff locally in the dir pointed by self.url class ProjectRemote(Project): def do_something(self): # do the stuff communicating with remote server pointed by self.url </code></pre> <p>Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:</p> <pre><code>project = Project('http://example.com') project.do_something() </code></pre> <p>I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:</p> <pre><code>def project_factory(url): if is_url_local(url): return ProjectLocal(url) else: return ProjectRemote(url) project = project_factory(url) project.do_something() </code></pre> <p>Is my first approach just matter of taste or it has some hidden pitfalls?</p>
5
2009-02-13T10:03:19Z
545,456
<p>I usually have a seperate factory class to do this. This way you don't have to use meta classes or assignments to <code>self.__class__</code></p> <p>I also try to avoid to put the knowledge about which classes are available for creation into the factory. Rather, I have all the available classes register themselves withe the factory during module import. The give there class and some information about when to select this class to the factory (this could be a name, a regex or a callable (e.g. a class method of the registering class)).</p> <p>Works very well for me and also implements such things like encapsulation and information hiding.</p>
1
2009-02-13T10:19:40Z
[ "python", "factory" ]
Using base class constructor as factory in Python?
545,419
<p>I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways? </p> <p>I've tried to read help about metaclasses but without big success.</p> <p>Here example of what I'm doing.</p> <pre><code>class Project(object): "Base class and factory." def __init__(self, url): if is_url_local(url): self.__class__ = ProjectLocal else: self.__class__ = ProjectRemote self.url = url class ProjectLocal(Project): def do_something(self): # do the stuff locally in the dir pointed by self.url class ProjectRemote(Project): def do_something(self): # do the stuff communicating with remote server pointed by self.url </code></pre> <p>Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:</p> <pre><code>project = Project('http://example.com') project.do_something() </code></pre> <p>I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:</p> <pre><code>def project_factory(url): if is_url_local(url): return ProjectLocal(url) else: return ProjectRemote(url) project = project_factory(url) project.do_something() </code></pre> <p>Is my first approach just matter of taste or it has some hidden pitfalls?</p>
5
2009-02-13T10:03:19Z
545,480
<p>The following links may be helpful: <a href="http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#factory" rel="nofollow">http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#factory</a> <a href="http://code.activestate.com/recipes/86900/" rel="nofollow">http://code.activestate.com/recipes/86900/</a></p> <p>In addition, as you are using new style classes, using __new__ as the factory function (and not in a base class, a separate class is better) is what is usually done (as far as I know).</p> <p>A factory function is generally simpler (as other people have already posted)</p> <p>In addition, it isn't a good idea to set the __class__ attribute the way you have done.</p> <p>I hope you find the answer and the links helpful.</p> <p>All the best.</p>
3
2009-02-13T10:26:50Z
[ "python", "factory" ]
Using base class constructor as factory in Python?
545,419
<p>I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways? </p> <p>I've tried to read help about metaclasses but without big success.</p> <p>Here example of what I'm doing.</p> <pre><code>class Project(object): "Base class and factory." def __init__(self, url): if is_url_local(url): self.__class__ = ProjectLocal else: self.__class__ = ProjectRemote self.url = url class ProjectLocal(Project): def do_something(self): # do the stuff locally in the dir pointed by self.url class ProjectRemote(Project): def do_something(self): # do the stuff communicating with remote server pointed by self.url </code></pre> <p>Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:</p> <pre><code>project = Project('http://example.com') project.do_something() </code></pre> <p>I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:</p> <pre><code>def project_factory(url): if is_url_local(url): return ProjectLocal(url) else: return ProjectRemote(url) project = project_factory(url) project.do_something() </code></pre> <p>Is my first approach just matter of taste or it has some hidden pitfalls?</p>
5
2009-02-13T10:03:19Z
545,786
<p>You shouldn't need metaclasses for this. Take a look at the <a href="http://docs.python.org/reference/datamodel.html#object.__new__"><code>__new__</code></a> method. This will allow you to take control of the creation of the object, rather than just the initialisation, and so return an object of your choosing.</p> <pre><code>class Project(object): "Base class and factory." def __new__(cls, url): if is_url_local(url): return super(Project, cls).__new__(ProjectLocal, url) else: return super(Project, cls).__new__(ProjectRemote, url) def __init__(self, url): self.url = url </code></pre>
11
2009-02-13T12:49:18Z
[ "python", "factory" ]
Using base class constructor as factory in Python?
545,419
<p>I'm using base class constructor as factory and changing class in this constructor/factory to select appropriate class -- is this approach is good python practice or there are more elegant ways? </p> <p>I've tried to read help about metaclasses but without big success.</p> <p>Here example of what I'm doing.</p> <pre><code>class Project(object): "Base class and factory." def __init__(self, url): if is_url_local(url): self.__class__ = ProjectLocal else: self.__class__ = ProjectRemote self.url = url class ProjectLocal(Project): def do_something(self): # do the stuff locally in the dir pointed by self.url class ProjectRemote(Project): def do_something(self): # do the stuff communicating with remote server pointed by self.url </code></pre> <p>Having this code I can create the instance of ProjectLocal/ProjectRemote via base class Project:</p> <pre><code>project = Project('http://example.com') project.do_something() </code></pre> <p>I know that alternate way is to using fabric function that will return the class object based on url, then code will looks similar:</p> <pre><code>def project_factory(url): if is_url_local(url): return ProjectLocal(url) else: return ProjectRemote(url) project = project_factory(url) project.do_something() </code></pre> <p>Is my first approach just matter of taste or it has some hidden pitfalls?</p>
5
2009-02-13T10:03:19Z
3,100,217
<p>Yeah, as mentioned by @scooterXL, factory function is the best approach in that case, but I like to note a case for factories as classmethods.</p> <p>Consider the following class hierarchy:</p> <pre><code>class Base(object): def __init__(self, config): """ Initialize Base object with config as dict.""" self.config = config @classmethod def from_file(cls, filename): config = read_and_parse_file_with_config(filename) return cls(filename) class ExtendedBase(Base): def behaviour(self): pass # do something specific to ExtendedBase </code></pre> <p>Now you can create Base objects from config dict and from config file:</p> <pre><code>&gt;&gt;&gt; Base({"k": "v"}) &gt;&gt;&gt; Base.from_file("/etc/base/base.conf") </code></pre> <p>But also, you can do the same with ExtendedBase for free:</p> <pre><code>&gt;&gt;&gt; ExtendedBase({"k": "v"}) &gt;&gt;&gt; ExtendedBase.from_file("/etc/extended/extended.conf") </code></pre> <p>So, this classmethod factory can be also considered as auxiliary constructor.</p>
2
2010-06-23T08:53:37Z
[ "python", "factory" ]
Tool (or combination of tools) for reproducible environments in Python
545,730
<p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p> <p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
9
2009-02-13T12:20:56Z
545,743
<p>Other than <a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="nofollow">easy_install</a>?</p> <p>For our Linux servers, we use easy_install and yum.</p> <p>For our Windows development laptops, we use easy_install and a few MSI's for some projects.</p> <p>Most of the Python libraries we use are source-only, so we can use the same distribution on all boxes. If we could have a network shared device, we'd put them all there. Sadly, our infrastructure is kind of scattered, so we have to either move .TAR files around or redo the installs to rebuild the environments.</p> <p>In a few cases (e.g., PIL), we have to recompile and check the version numbers.</p>
2
2009-02-13T12:28:45Z
[ "python", "continuous-integration", "installation", "development-environment", "automated-deploy" ]
Tool (or combination of tools) for reproducible environments in Python
545,730
<p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p> <p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
9
2009-02-13T12:20:56Z
545,746
<p>I also work with both java and python. For python development the maven equivalent is setuptools (<a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">http://peak.telecommunity.com/DevCenter/setuptools</a>). For web application development I use this in combination with paster (<a href="http://pythonpaste.org/" rel="nofollow">http://pythonpaste.org/</a>) for the deployment process</p>
3
2009-02-13T12:29:30Z
[ "python", "continuous-integration", "installation", "development-environment", "automated-deploy" ]
Tool (or combination of tools) for reproducible environments in Python
545,730
<p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p> <p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
9
2009-02-13T12:20:56Z
545,747
<p>You will want <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">easy_setup</a> to get the eggs (roughly what Maven calls an artifact).</p> <p>For setting up your environment, have a look at <a href="http://blog.ianbicking.org/working-env.html" rel="nofollow">working-env.py</a></p> <p>Python is not compiled but you can put all files for a project in an egg. This is done with <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">setuptools</a></p> <p>For CI, check <a href="http://stackoverflow.com/questions/535/continuous-integration-system-for-a-python-codebase">this answer</a>.</p>
2
2009-02-13T12:30:18Z
[ "python", "continuous-integration", "installation", "development-environment", "automated-deploy" ]
Tool (or combination of tools) for reproducible environments in Python
545,730
<p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p> <p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
9
2009-02-13T12:20:56Z
545,839
<p>I do exactly this with a combination of setuptools and Hudson. I know Hudson is a java app, but it can run Python stuff just fine.</p>
0
2009-02-13T13:06:36Z
[ "python", "continuous-integration", "installation", "development-environment", "automated-deploy" ]
Tool (or combination of tools) for reproducible environments in Python
545,730
<p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p> <p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
9
2009-02-13T12:20:56Z
545,912
<ol> <li><p><a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron.</p></li> <li><p><a href="http://pypi.python.org/pypi/pip">pip</a> to install packages inside a virtualenv. The traditional is easy_install as answered by S. Lott, but pip works better with virtualenv. easy_install still has features not found in pip though.</p></li> <li><p><a href="http://www.scons.org/">scons</a> as a build tool, although you won't need this if you stay purely Python.</p></li> <li><p><a href="http://pypi.python.org/pypi/Fabric/0.0.3">Fabric</a> paste, or <a href="http://www.blueskyonmars.com/projects/paver/">paver</a> for deployment.</p></li> <li><p><a href="http://buildbot.net/trac">buildbot</a> for continuous integration.</p></li> <li><p>Bazaar, mercurial, or git for version control.</p></li> <li><p><a href="http://somethingaboutorange.com/mrl/projects/nose/">Nose</a> as an extension for unit testing.</p></li> <li><p><a href="http://pypi.python.org/pypi/PyFIT/0.8a2">PyFit</a> for <a href="http://fit.c2.com">FIT</a> testing.</p></li> </ol>
18
2009-02-13T13:24:24Z
[ "python", "continuous-integration", "installation", "development-environment", "automated-deploy" ]
Tool (or combination of tools) for reproducible environments in Python
545,730
<p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p> <p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
9
2009-02-13T12:20:56Z
546,992
<p>We would be remiss not to also mention <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">Paver</a>, which was created by Kevin Dangoor of <a href="http://www.turbogears.org/" rel="nofollow">TurboGears</a> fame. The project is still in alpha, but it appears very promising. A snippet from the project page:</p> <blockquote> <p>Paver is a Python-based build/distribution/deployment scripting tool along the lines of Make or Rake. What makes Paver unique is its integration with commonly used Python libraries. Common tasks that were easy before remain easy. More importantly, dealing with your applications specific needs and requirements is now much easier.</p> </blockquote>
2
2009-02-13T18:00:31Z
[ "python", "continuous-integration", "installation", "development-environment", "automated-deploy" ]
Tool (or combination of tools) for reproducible environments in Python
545,730
<p>I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. </p> <p>I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.</p>
9
2009-02-13T12:20:56Z
2,831,204
<p>You might want to check our <a href="http://www.viewtier.com/products/devenv/index.htm" rel="nofollow"><strong>Devenv</strong></a>. It allows you to standardize the build environments for development, QA and UAT. It's free as in "free beer".</p> <p>HTH</p>
0
2010-05-14T00:53:17Z
[ "python", "continuous-integration", "installation", "development-environment", "automated-deploy" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
546,331
<p>Use the python datetime module to add a timedelta of six months to datetime.today() .</p> <p><a href="http://docs.python.org/library/datetime.html" rel="nofollow">http://docs.python.org/library/datetime.html</a></p> <p>You will of course have to solve the issue raised by Johannes Weiß-- what <em>do</em> you mean by 6 months?</p>
0
2009-02-13T15:20:59Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
546,332
<p>What do you mean by '6 months'. Is 2009-02-13 + 6 months == 2009-08-13 or is it 2009-02-13 + 6*30 days?</p> <pre><code>import mx.DateTime as dt #6 Months dt.now()+dt.RelativeDateTime(months=6) #result is '2009-08-13 16:28:00.84' #6*30 days dt.now()+dt.RelativeDateTime(days=30*6) #result is '2009-08-12 16:30:03.35' </code></pre> <p>More info about <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/">mx.DateTime</a></p>
10
2009-02-13T15:21:07Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
546,339
<p>Just use the <em>timetuple</em> method to extract the months, add your months and build a new dateobject. If there is a already existing method for this I do not know it.</p> <pre><code>import datetime def in_the_future(months=1): year, month, day = datetime.date.today().timetuple()[:3] new_month = month + months return datetime.date(year + (new_month / 12), new_month % 12, day) </code></pre> <p>The API is a bit clumsy, but works as an example. Will also obviously not work on corner-cases like 2008-01-31 + 1 month. :)</p>
6
2009-02-13T15:23:42Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
546,347
<p><a href="http://labix.org/python-dateutil">Dateutil package</a> has implementation of such functionality. But be aware, that this will be <em>naive</em>, as others pointed already.</p>
7
2009-02-13T15:26:05Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
546,353
<p>There's no direct way to do it with Python's datetime.</p> <p>Check out the relativedelta type at <a href="http://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454">python-dateutil</a>. It allows you to specify a time delta in months.</p>
6
2009-02-13T15:29:05Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
546,354
<p>Well, that depends what you mean by 6 months from the current date.</p> <ol> <li><p>Using natural months:</p> <pre><code>(day, month, year) = (day, (month+6)%12, year+(month+6)/12) </code></pre></li> <li><p>Using a banker's definition, 6*30:</p> <pre><code>date += datetime.timedelta(6*30) </code></pre></li> </ol>
36
2009-02-13T15:29:24Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
546,356
<pre><code>import datetime print (datetime.date.today() + datetime.timedelta(6*365/12)).isoformat() </code></pre>
57
2009-02-13T15:29:46Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
1,750,124
<p>The QDate class of PyQt4 has an addmonths function.</p> <pre><code>&gt;&gt;&gt;from PyQt4.QtCore import QDate &gt;&gt;&gt;dt = QDate(2009,12,31) &gt;&gt;&gt;required = dt.addMonths(6) &gt;&gt;&gt;required PyQt4.QtCore.QDate(2010, 6, 30) &gt;&gt;&gt;required.toPyDate() datetime.date(2010, 6, 30) </code></pre>
2
2009-11-17T16:37:16Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
2,075,926
<p>Modified Johannes Wei's answer in the case 1new_month = 121. This works perfectly for me. The months could be positive or negative.</p> <pre><code>def addMonth(d,months=1): year, month, day = d.timetuple()[:3] new_month = month + months return datetime.date(year + ((new_month-1) / 12), (new_month-1) % 12 +1, day) </code></pre>
0
2010-01-16T02:02:04Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
2,366,759
<p>This is what I came up with. It moves the correct number of months and years but ignores days (which was what I needed in my situation).</p> <pre><code>import datetime month_dt = 4 today = datetime.date.today() y,m = today.year, today.month m += month_dt-1 year_dt = m//12 new_month = m%12 new_date = datetime.date(y+year_dt, new_month+1, 1) </code></pre>
0
2010-03-02T21:06:05Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
2,560,837
<p>I use this function to change year and month but keep day:</p> <pre><code>def replace_month_year(date1, year2, month2): try: date2 = date1.replace(month = month2, year = year2) except: date2 = datetime.date(year2, month2 + 1, 1) - datetime.timedelta(days=1) return date2 </code></pre> <p>You should write:</p> <pre><code>new_year = my_date.year + (my_date.month + 6) / 12 new_month = (my_date.month + 6) % 12 new_date = replace_month_year(my_date, new_year, new_month) </code></pre>
0
2010-04-01T13:55:51Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
3,197,505
<p>So, here is an example of the <code>dateutil.relativedelta</code> which I found useful for iterating through the past year, skipping a month each time to the present date:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; from dateutil.relativedelta import relativedelta &gt;&gt;&gt; today = datetime.datetime.today() &gt;&gt;&gt; month_count = 0 &gt;&gt;&gt; while month_count &lt; 12: ... day = today - relativedelta(months=month_count) ... print day ... month_count += 1 ... 2010-07-07 10:51:45.187968 2010-06-07 10:51:45.187968 2010-05-07 10:51:45.187968 2010-04-07 10:51:45.187968 2010-03-07 10:51:45.187968 2010-02-07 10:51:45.187968 2010-01-07 10:51:45.187968 2009-12-07 10:51:45.187968 2009-11-07 10:51:45.187968 2009-10-07 10:51:45.187968 2009-09-07 10:51:45.187968 2009-08-07 10:51:45.187968 </code></pre> <p>As with the other answers, you have to figure out what you actually mean by "6 months from now." If you mean "today's day of the month in the month six years in the future" then this would do:</p> <pre><code>datetime.datetime.now() + relativedelta(months=6) </code></pre>
6
2010-07-07T17:59:32Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
3,463,303
<p>This solution works correctly for December, which most of the answers on this page do not. You need to first shift the months from base 1 (ie Jan = 1) to base 0 (ie Jan = 0) before using modulus ( % ) or integer division ( // ), otherwise November (11) plus 1 month gives you 12, which when finding the remainder ( 12 % 12 ) gives 0.</p> <p>(And dont suggest "(month % 12) + 1" or Oct + 1 = december!)</p> <pre><code>def AddMonths(d,x): newmonth = ((( d.month - 1) + x ) % 12 ) + 1 newyear = d.year + ((( d.month - 1) + x ) / 12 ) return datetime.date( newyear, newmonth, d.day) </code></pre> <p>However ... This doesnt account for problem like Jan 31 + one month. So we go back to the OP - what do you mean by adding a month? One soln is to backtrack until you get to a valid day, given that most people would presume the last day of jan, plus one month, equals the last day of Feb. This will work on negative numbers of months too. Proof:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),1) datetime.date(2010, 9, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),4) datetime.date(2010, 12, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),5) datetime.date(2011, 1, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),13) datetime.date(2011, 9, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),24) datetime.date(2012, 8, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),-1) datetime.date(2010, 7, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),0) datetime.date(2010, 8, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),-12) datetime.date(2009, 8, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),-8) datetime.date(2009, 12, 25) &gt;&gt;&gt; AddMonths(datetime.datetime(2010,8,25),-7) datetime.date(2010, 1, 25)&gt;&gt;&gt; </code></pre>
9
2010-08-11T22:18:29Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
4,406,260
<p>I found this solution to be good. (This uses the <a href="https://dateutil.readthedocs.org/en/latest/">python-dateutil extension</a>)</p> <pre><code>from datetime import date from dateutil.relativedelta import relativedelta six_months = date.today() + relativedelta(months=+6) </code></pre> <p>The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)</p> <pre><code>$ date(2010,12,31)+relativedelta(months=+1) datetime.date(2011, 1, 31) $ date(2010,12,31)+relativedelta(months=+2) datetime.date(2011, 2, 28) </code></pre>
410
2010-12-10T06:22:36Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
4,873,454
<p>I think it would be safer to do something like this instead of manually adding days:</p> <pre><code>import datetime today = datetime.date.today() def addMonths(dt, months = 0): new_month = months + dt.month year_inc = 0 if new_month&gt;12: year_inc +=1 new_month -=12 return dt.replace(month = new_month, year = dt.year+year_inc) newdate = addMonths(today, 6) </code></pre>
0
2011-02-02T10:45:33Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
4,875,773
<p>I solved this problem like this:</p> <pre><code>import calendar from datetime import datetime moths2add = 6 now = datetime.now() current_year = now.year current_month = now.month #count days in months you want to add using calendar module days = sum( [calendar.monthrange(current_year, elem)[1] for elem in range(current_month, current_month + moths)] ) print now + days </code></pre>
1
2011-02-02T14:44:44Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
5,254,091
<pre><code>import datetime ''' Created on 2011-03-09 @author: tonydiep ''' def add_business_months(start_date, months_to_add): """ Add months in the way business people think of months. Jan 31, 2011 + 1 month = Feb 28, 2011 to business people Method: Add the number of months, roll back the date until it becomes a valid date """ # determine year years_change = months_to_add / 12 # determine if there is carryover from adding months if (start_date.month + (months_to_add % 12) &gt; 12 ): years_change = years_change + 1 new_year = start_date.year + years_change # determine month work = months_to_add % 12 if 0 == work: new_month = start_date.month else: new_month = (start_date.month + (work % 12)) % 12 if 0 == new_month: new_month = 12 # determine day of the month new_day = start_date.day if(new_day in [31, 30, 29, 28]): #user means end of the month new_day = 31 new_date = None while (None == new_date and 27 &lt; new_day): try: new_date = start_date.replace(year=new_year, month=new_month, day=new_day) except: new_day = new_day - 1 #wind down until we get to a valid date return new_date if __name__ == '__main__': #tests dates = [datetime.date(2011, 1, 31), datetime.date(2011, 2, 28), datetime.date(2011, 3, 28), datetime.date(2011, 4, 28), datetime.date(2011, 5, 28), datetime.date(2011, 6, 28), datetime.date(2011, 7, 28), datetime.date(2011, 8, 28), datetime.date(2011, 9, 28), datetime.date(2011, 10, 28), datetime.date(2011, 11, 28), datetime.date(2011, 12, 28), ] months = range(1, 24) for start_date in dates: for m in months: end_date = add_business_months(start_date, m) print("%s\t%s\t%s" %(start_date, end_date, m)) </code></pre>
1
2011-03-10T00:29:32Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
5,643,283
<p>I know this was for 6 months, however the answer shows in google for "adding months in python" if you are adding one month:</p> <pre><code>import calendar date = datetime.date.today() //Or your date datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1]) </code></pre> <p>this would count the days in the current month and add them to the current date, using 365/12 would ad 1/12 of a year can causes issues for short / long months if your iterating over the date.</p>
7
2011-04-13T00:54:07Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
5,954,712
<p>my modification to tony diep's answer, possibly marginally more elegant:</p> <pre><code>def add_months(date, months): month = date.month + months - 1 year = date.year + (month / 12) month = (month % 12) + 1 day = date.day while (day &gt; 0): try: new_date = date.replace(year=year, month=month, day=day) break except: day = day - 1 return new_date </code></pre> <p>adds months according to a business needs interpretation</p>
0
2011-05-10T18:33:26Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
6,123,390
<p>I have a better way to solve the 'February 31st' problem:</p> <pre><code>def add_months(start_date, months): import calendar year = start_date.year + (months / 12) month = start_date.month + (months % 12) day = start_date.day if month &gt; 12: month = month % 12 year = year + 1 days_next = calendar.monthrange(year, month)[1] if day &gt; days_next: day = days_next return start_date.replace(year, month, day) </code></pre> <p>I think that it also works with negative numbers (to subtract months), but I haven't tested this very much.</p>
2
2011-05-25T11:00:03Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
6,251,949
<p>Modified the AddMonths() for use in Zope and handling invalid day numbers:</p> <pre><code>def AddMonths(d,x): days_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] newmonth = ((( d.month() - 1) + x ) % 12 ) + 1 newyear = d.year() + ((( d.month() - 1) + x ) // 12 ) if d.day() &gt; days_of_month[newmonth-1]: newday = days_of_month[newmonth-1] else: newday = d.day() return DateTime( newyear, newmonth, newday) </code></pre>
2
2011-06-06T12:25:22Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
7,020,175
<pre><code>import time def add_month(start_time, months): ret = time.strptime(start_time, '%Y-%m-%d') t = list(ret) t[1] += months if t[1] &gt; 12: t[0] += 1 + int(months / 12) t[1] %= 12 return int(time.mktime(tuple(t))) </code></pre>
2
2011-08-11T02:28:22Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
8,689,734
<p>Rework of an earlier answer by user417751. Maybe not so pythonic way, but it takes care of different month lengths and leap years. In this case 31 January 2012 + 1 month = 29 February 2012. </p> <pre><code>import datetime import calendar def add_mths(d, x): newday = d.day newmonth = (((d.month - 1) + x) % 12) + 1 newyear = d.year + (((d.month - 1) + x) // 12) if newday &gt; calendar.mdays[newmonth]: newday = calendar.mdays[newmonth] if newyear % 4 == 0 and newmonth == 2: newday += 1 return datetime.date(newyear, newmonth, newday) </code></pre>
0
2011-12-31T18:10:56Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
10,750,881
<p>In this function, n can be positive or negative.</p> <pre><code>def addmonth(d, n): n += 1 dd = datetime.date(d.year + n/12, d.month + n%12, 1)-datetime.timedelta(1) return datetime.date(dd.year, dd.month, min(d.day, dd.day)) </code></pre>
0
2012-05-25T08:15:20Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
16,792,632
<p>We probably should use dateutil.relativedelta</p> <p>however for academic interest I will just add that before I discovered it I was goint to use this:</p> <p>try:<br> &nbsp;&nbsp;&nbsp;vexpDt = K.today.replace(K.today.year + (K.today.month+6)//12, (K.today.month+5)%12+1, K.today.day)<br> except:<br> &nbsp;&nbsp;&nbsp;vexpDt = K.today.replace(K.today.year + (K.today.month+6)//12, (K.today.month+6)%12+1, 1) - timedelta(days = 1)<br></p> <p>it seems quite simple but still catches all the issues like 29,30,31</p> <p>it also works for - 6 mths by doing -timedelta</p> <p>nb - don't be confused by K.today its just a variable in my program</p>
-1
2013-05-28T12:53:59Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
19,269,236
<pre><code> def addDay(date, number): for i in range(number) #try to add a day try: date = date.replace(day = date.day + 1) #in case it's impossible ex:january 32nd add a month and restart at day 1 except: #add month part try: date = date.replace(month = date.month +1, day = 1) except: date = date.replace(year = date.year +1, month = 1, day = 1) </code></pre> <p>For everyone still reading this post. I think this code is way clearer, especially compared to code using modulo(%).</p> <p>Sorry for any grammatical error, english is so not my main language</p>
-1
2013-10-09T10:17:35Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
19,677,636
<p>Yet another solution - hope someone will like it:</p> <pre><code>def add_months(d, months): return d.replace(year=d.year+months//12).replace(month=(d.month+months)%12) </code></pre> <p>This solution doesn't work for days 29,30,31 for all cases, so more robust solution is needed (which is not so nice anymore :) ):</p> <pre><code>def add_months(d, months): for i in range(4): day = d.day - i try: return d.replace(day=day).replace(year=d.year+int(months)//12).replace(month=(d.month+int(months))%12) except: pass raise Exception("should not happen") </code></pre>
0
2013-10-30T08:51:09Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
30,224,798
<p>From <a href="http://stackoverflow.com/a/1495548/605356">this answer</a>, see <a href="https://github.com/bear/parsedatetime" rel="nofollow">parsedatetime</a>. Code example follows. More details: <a href="https://gist.github.com/johnnyutahh/24f9a48a331fd36a4e97#file-parsedatetime_unittest-py" rel="nofollow">unit test with many natural-language -> YYYY-MM-DD conversion examples</a>, and apparent <a href="https://github.com/bear/parsedatetime/issues/88" rel="nofollow">parsedatetime conversion challenges/bugs</a>.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import time, calendar from datetime import date # from https://github.com/bear/parsedatetime import parsedatetime as pdt def print_todays_date(): todays_day_of_week = calendar.day_name[date.today().weekday()] print "today's date = " + todays_day_of_week + ', ' + \ time.strftime('%Y-%m-%d') def convert_date(natural_language_date): cal = pdt.Calendar() (struct_time_date, success) = cal.parse(natural_language_date) if success: formal_date = time.strftime('%Y-%m-%d', struct_time_date) else: formal_date = '(conversion failed)' print '{0:12s} -&gt; {1:10s}'.format(natural_language_date, formal_date) print_todays_date() convert_date('6 months') </code></pre> <p>The above code generates the following from a MacOSX machine:</p> <pre><code>$ ./parsedatetime_simple.py today's date = Wednesday, 2015-05-13 6 months -&gt; 2015-11-13 $ </code></pre>
1
2015-05-13T20:40:56Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
32,493,325
<p>How about this? Not using another library (<code>dateutil</code>) or <code>timedelta</code>? building on <a href="http://stackoverflow.com/users/60711/vartec">vartec</a>'s answer I did this and I believe it works:</p> <pre><code>import datetime today = datetime.date.today() six_months_from_today = datetime.date(today.year + (today.month + 6)/12, (today.month + 6) % 12, today.day) </code></pre> <p>I tried using <code>timedelta</code>, but because it is counting the days, <code>365/2</code> or <code>6*356/12</code> does not always translate to 6 months, but rather 182 days. e.g.</p> <pre><code>day = datetime.date(2015, 3, 10) print day &gt;&gt;&gt; 2015-03-10 print (day + datetime.timedelta(6*365/12)) &gt;&gt;&gt; 2015-09-08 </code></pre> <p>I believe that we usually assume that 6 month's from a certain day will land on the same day of the month but 6 months later (i.e. <code>2015-03-10</code> --> <code>2015-09-10</code>, Not <code>2015-09-08</code>)</p> <p>I hope you find this helpful.</p>
2
2015-09-10T04:44:56Z
[ "python", "datetime" ]
How do I calculate the date six months from the current date using the datetime Python module?
546,321
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p> <p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
143
2009-02-13T15:16:25Z
34,831,191
<p>This is what I do when I need to add months or years and don't want to import more libraries.</p> <pre><code>import datetime __author__ = 'Daniel Margarido' # Check if the int given year is a leap year # return true if leap year or false otherwise def is_leap_year(year): if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: return True else: return False else: return True else: return False THIRTY_DAYS_MONTHS = [4, 6, 9, 11] THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12] # Inputs -&gt; month, year Booth integers # Return the number of days of the given month def get_month_days(month, year): if month in THIRTY_DAYS_MONTHS: # April, June, September, November return 30 elif month in THIRTYONE_DAYS_MONTHS: # January, March, May, July, August, October, December return 31 else: # February if is_leap_year(year): return 29 else: return 28 # Checks the month of the given date # Selects the number of days it needs to add one month # return the date with one month added def add_month(date): current_month_days = get_month_days(date.month, date.year) next_month_days = get_month_days(date.month + 1, date.year) delta = datetime.timedelta(days=current_month_days) if date.day &gt; next_month_days: delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1) return date + delta def add_year(date): if is_leap_year(date.year): delta = datetime.timedelta(days=366) else: delta = datetime.timedelta(days=365) return date + delta # Validates if the expected_value is equal to the given value def test_equal(expected_value, value): if expected_value == value: print "Test Passed" return True print "Test Failed : " + str(expected_value) + " is not equal to " str(value) return False # Test leap year print "---------- Test leap year ----------" test_equal(True, is_leap_year(2012)) test_equal(True, is_leap_year(2000)) test_equal(False, is_leap_year(1900)) test_equal(False, is_leap_year(2002)) test_equal(False, is_leap_year(2100)) test_equal(True, is_leap_year(2400)) test_equal(True, is_leap_year(2016)) # Test add month print "---------- Test add month ----------" test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1))) test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16))) test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15))) test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12))) test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31))) test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31))) test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30))) test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30))) test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31))) # Test add year print "---------- Test add year ----------" test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2))) test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2))) test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2))) test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2))) test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2))) </code></pre> <p>Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.</p>
-1
2016-01-16T19:30:27Z
[ "python", "datetime" ]