title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How can I get the created date of a file on the web (with Python)?
428,895
<p>I have a python application that relies on a file that is downloaded by a client from a website.</p> <p>The website is not under my control and has no API to check for a "latest version" of the file.</p> <p>Is there a simple way to access the file (in python) via a URL and check it's date (or size) without having to download it to the clients machine each time?</p> <p><strong>update:</strong> Thanks to those who mentioned the"last-modified" date. This is the correct parameter to look at.</p> <p>I guess I didn't state the question well enough. How do I do this from a python script? I want to application to check the file and then download it if (last-modified date &lt; current file date).</p>
1
2009-01-09T17:11:15Z
431,411
<p>Take into account that 'last-modified' may not be present:</p> <pre> >>> from urllib import urlopen >>> f=urlopen('http://google.com/') >>> i=f.info() >>> i.keys() ['set-cookie', 'expires', 'server', 'connection', 'cache-control', 'date', 'content-type'] >>> i.getdate('date') (2009, 1, 10, 16, 17, 8, 0, 1, 0) >>> i.getheader('date') 'Sat, 10 Jan 2009 16:17:08 GMT' >>> i.getdate('last-modified') >>> </pre> <p>Now you can compare:</p> <pre> if (i.getdate('last-modified') or i.getheader('date')) > current_file_date: open('file', 'w').write(f.read()) </pre>
3
2009-01-10T17:44:31Z
[ "python", "http" ]
How to process a YAML stream in Python
429,162
<p>I have a command line app the continuously outputs YAML data in the form:</p> <pre> - col0: datum0 col1: datum1 col2: datum2 - col0: datum0 col1: datum1 col2: datum2 ... </pre> <p>It does this for all of eternity. I would like to write a Python script that continuously reads each of these records.</p> <p>The PyYAML library seems best at taking fully loaded strings and interpreting those as a complete YAML document. Is there a way to put PyYAML into a "streaming" mode?</p> <p>Or is my only option to chunk the data myself and feed it bit by bit into PyYAML?</p>
3
2009-01-09T18:29:48Z
429,305
<p>All of the references to stream in the the documentation seem to be referring to a stream of documents... I've never tried to use it in the way you describe, but it seems like chunking the data into such a stream of documents is a reasonable approach.</p>
2
2009-01-09T19:12:47Z
[ "python", "command-line", "streaming", "yaml" ]
How to process a YAML stream in Python
429,162
<p>I have a command line app the continuously outputs YAML data in the form:</p> <pre> - col0: datum0 col1: datum1 col2: datum2 - col0: datum0 col1: datum1 col2: datum2 ... </pre> <p>It does this for all of eternity. I would like to write a Python script that continuously reads each of these records.</p> <p>The PyYAML library seems best at taking fully loaded strings and interpreting those as a complete YAML document. Is there a way to put PyYAML into a "streaming" mode?</p> <p>Or is my only option to chunk the data myself and feed it bit by bit into PyYAML?</p>
3
2009-01-09T18:29:48Z
431,387
<p>Here is what I've ended up using since there does not seem to be a built-in method for accomplishing what I want. This function should be generic enough that it can read in a stream of YAML and return top-level objects as they are encountered.</p> <pre><code>def streamInYAML(stream): y = stream.readline() cont = 1 while cont: l = stream.readline() if len(l) == 0: cont = 0 else: if l.startswith(' '): y = y + l else: yield yaml.load(y) y = l </code></pre> <p>Can anyone do better?</p>
3
2009-01-10T17:33:00Z
[ "python", "command-line", "streaming", "yaml" ]
Can I use urllib to submit a SOAP request?
429,164
<p>I have a SOAP request that is known to work using a tool like, say, SoapUI, but I am trying to get it to work using urllib.</p> <p>This is what I have tried so far and it did not work:</p> <pre><code>import urllib f = "".join(open("ws_request_that_works_in_soapui", "r").readlines()) urllib.urlopen('http://url.com/to/Router?wsdl', f) </code></pre> <p>I haven't been able to find the spec on how the document should be posted to the SOAP Server.</p> <p>urllib is not a necessary requirement.</p>
3
2009-01-09T18:30:09Z
429,349
<p>Well, I answered my own question</p> <pre><code>import httplib f = "".join(open('ws_request', 'r')) webservice = httplib.HTTP('localhost', 8083) webservice.putrequest("POST", "Router?wsdl") webservice.putheader("User-Agent", "Python post") webservice.putheader("Content-length", "%d" % len(f)) webservice.putheader("SOAPAction", "\"\"") webservice.endheaders() webservice.send(f) </code></pre>
7
2009-01-09T19:23:51Z
[ "python", "soap" ]
Can I use urllib to submit a SOAP request?
429,164
<p>I have a SOAP request that is known to work using a tool like, say, SoapUI, but I am trying to get it to work using urllib.</p> <p>This is what I have tried so far and it did not work:</p> <pre><code>import urllib f = "".join(open("ws_request_that_works_in_soapui", "r").readlines()) urllib.urlopen('http://url.com/to/Router?wsdl', f) </code></pre> <p>I haven't been able to find the spec on how the document should be posted to the SOAP Server.</p> <p>urllib is not a necessary requirement.</p>
3
2009-01-09T18:30:09Z
429,353
<p>Short answer: yes you can.</p> <p>Long answer:</p> <p>Take a look at this <a href="http://users.skynet.be/pascalbotte/rcx-ws-doc/postxmlpython.htm" rel="nofollow">example</a> it doesn't use urllib but will give you the idea of how to prepare SOAP request.</p> <p>As far as urllib, I suggest using <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a>, and yes you can submit a SOAP request using it, follow the same steps to prepare the request as in previous example.</p>
3
2009-01-09T19:25:15Z
[ "python", "soap" ]
what's the pythonic way to count the occurrence of an element in a list?
429,414
<p>this is what I did. is there a better way in python?</p> <pre> for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 </pre> <p>Thanks</p>
9
2009-01-09T19:42:32Z
429,442
<p>Single element:</p> <pre><code>a_list.count(k) </code></pre> <p>All elements:</p> <pre><code>counts = dict((k, a_list.count(k)) for k in set(a_list)) </code></pre>
9
2009-01-09T19:49:50Z
[ "python" ]
what's the pythonic way to count the occurrence of an element in a list?
429,414
<p>this is what I did. is there a better way in python?</p> <pre> for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 </pre> <p>Thanks</p>
9
2009-01-09T19:42:32Z
429,469
<p>I dunno, it basically looks fine to me. Your code is simple and easy to read which is an important part of what I consider pythonic. </p> <p>You could trim it up a bit like so:</p> <pre><code>for k in a_list: kvMap[k] = 1 + kvMap.get(k,0) </code></pre>
7
2009-01-09T19:55:59Z
[ "python" ]
what's the pythonic way to count the occurrence of an element in a list?
429,414
<p>this is what I did. is there a better way in python?</p> <pre> for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 </pre> <p>Thanks</p>
9
2009-01-09T19:42:32Z
429,491
<p>Use defaultdict</p> <pre><code>from collections import defaultdict kvmap= defaultdict(int) for k in a_list: kvmap[k] += 1 </code></pre>
14
2009-01-09T20:01:37Z
[ "python" ]
what's the pythonic way to count the occurrence of an element in a list?
429,414
<p>this is what I did. is there a better way in python?</p> <pre> for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 </pre> <p>Thanks</p>
9
2009-01-09T19:42:32Z
429,720
<p>Another solution exploits setdefault():</p> <pre><code>for k in a_list: kvMap[k] = kvMap.setdefault(k, 0) + 1 </code></pre>
3
2009-01-09T21:00:17Z
[ "python" ]
what's the pythonic way to count the occurrence of an element in a list?
429,414
<p>this is what I did. is there a better way in python?</p> <pre> for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 </pre> <p>Thanks</p>
9
2009-01-09T19:42:32Z
430,982
<p>If your list is sorted, an alternative way would be to use <a href="http://docs.python.org/library/itertools.html?highlight=groupby#itertools.groupby" rel="nofollow">itertools.groupby</a>. This might not be the most effective way, but it's interesting nonetheless. It retuns a dict of item > count :</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; l = [1,1,2,3,4,4,4,5,5,6,6,6,7] &gt;&gt;&gt; dict([(key, len([e for e in group])) for (key, group) in itertools.groupby(l)]) {1: 2, 2: 1, 3: 1, 4: 3, 5: 2, 6: 3, 7: 1} </code></pre>
1
2009-01-10T13:56:17Z
[ "python" ]
what's the pythonic way to count the occurrence of an element in a list?
429,414
<p>this is what I did. is there a better way in python?</p> <pre> for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 </pre> <p>Thanks</p>
9
2009-01-09T19:42:32Z
8,641,161
<p>Such an old question, but considering that adding to a <code>defaultdict(int)</code> is such a common use, It should come as no surprise that <code>collections</code> has a special name for that (since Python 2.7)</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; Counter([1, 2, 1, 1, 3, 2, 3, 4]) Counter({1: 3, 2: 2, 3: 2, 4: 1}) &gt;&gt;&gt; Counter("banana") Counter({'a': 3, 'n': 2, 'b': 1}) </code></pre>
4
2011-12-27T04:29:36Z
[ "python" ]
extracting stream from pdf in python
429,437
<p>How can I extract the part of this stream (the one named BLABLABLA) from the pdf file which contains it??</p> <pre><code>&lt;&lt;/Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources&lt;&lt;/ColorSpace&lt;&lt;/CS0 563 0 R&gt;&gt;/ExtGState&lt;&lt;/GS0 568 0 R&gt;&gt;/Font&lt;&lt;/TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R&gt;&gt;/ProcSet[/PDF/Text/ImageC]/Properties&lt;&lt;/MC0&lt;&lt;/BLABLABLA 584 0 R&gt;&gt;/MC1&lt;&lt;/SubKey 582 0 R&gt;&gt;&gt;&gt;/XObject&lt;&lt;/Im0 578 0 R&gt;&gt;&gt;&gt;/Rotate 0/StructParents 0/Type/Page&gt;&gt; </code></pre> <p>Or, in other worlds, how can I extract a subkey from a pdf stream?</p> <p>I would like to use some python's library (like pyPdf or ReportLab), but even some C/C++ lib should go well for me.</p> <p>Can anyone help me?</p>
1
2009-01-09T19:47:57Z
430,153
<p>I haven't use this myself, but maybe <a href="http://www.swftools.org/gfx_tutorial.html" rel="nofollow">the gfx module in swftool</a> can help you.</p>
0
2009-01-09T23:41:20Z
[ "python", "pdf", "stream", "reportlab", "pypdf" ]
extracting stream from pdf in python
429,437
<p>How can I extract the part of this stream (the one named BLABLABLA) from the pdf file which contains it??</p> <pre><code>&lt;&lt;/Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources&lt;&lt;/ColorSpace&lt;&lt;/CS0 563 0 R&gt;&gt;/ExtGState&lt;&lt;/GS0 568 0 R&gt;&gt;/Font&lt;&lt;/TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R&gt;&gt;/ProcSet[/PDF/Text/ImageC]/Properties&lt;&lt;/MC0&lt;&lt;/BLABLABLA 584 0 R&gt;&gt;/MC1&lt;&lt;/SubKey 582 0 R&gt;&gt;&gt;&gt;/XObject&lt;&lt;/Im0 578 0 R&gt;&gt;&gt;&gt;/Rotate 0/StructParents 0/Type/Page&gt;&gt; </code></pre> <p>Or, in other worlds, how can I extract a subkey from a pdf stream?</p> <p>I would like to use some python's library (like pyPdf or ReportLab), but even some C/C++ lib should go well for me.</p> <p>Can anyone help me?</p>
1
2009-01-09T19:47:57Z
430,918
<p>Google code has a python text-extraction tool called <a href="http://code.google.com/p/pdfminerr/source/browse/trunk/pdfminer" rel="nofollow">pdf miner</a>. I don't know if it will do what you want, but it might be worth a look.</p>
3
2009-01-10T12:43:35Z
[ "python", "pdf", "stream", "reportlab", "pypdf" ]
extracting stream from pdf in python
429,437
<p>How can I extract the part of this stream (the one named BLABLABLA) from the pdf file which contains it??</p> <pre><code>&lt;&lt;/Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources&lt;&lt;/ColorSpace&lt;&lt;/CS0 563 0 R&gt;&gt;/ExtGState&lt;&lt;/GS0 568 0 R&gt;&gt;/Font&lt;&lt;/TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R&gt;&gt;/ProcSet[/PDF/Text/ImageC]/Properties&lt;&lt;/MC0&lt;&lt;/BLABLABLA 584 0 R&gt;&gt;/MC1&lt;&lt;/SubKey 582 0 R&gt;&gt;&gt;&gt;/XObject&lt;&lt;/Im0 578 0 R&gt;&gt;&gt;&gt;/Rotate 0/StructParents 0/Type/Page&gt;&gt; </code></pre> <p>Or, in other worlds, how can I extract a subkey from a pdf stream?</p> <p>I would like to use some python's library (like pyPdf or ReportLab), but even some C/C++ lib should go well for me.</p> <p>Can anyone help me?</p>
1
2009-01-09T19:47:57Z
433,826
<p>IIUC, a stream in a PDF is just a sequence of binary data. I think you are wanting to extract part of an object. Are you wanting a standard object, like an image or text? It would be a lot easier to give you example code if there was a real example.</p> <p>This might help get you started:</p> <pre><code>import pyPdf pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) list(pdf.pages) # Process all the objects. print pdf.resolvedObjects </code></pre>
1
2009-01-11T22:06:59Z
[ "python", "pdf", "stream", "reportlab", "pypdf" ]
Syncing Django users with Google Apps without monkeypatching
429,443
<p>I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally.</p> <p>I would solely use signals, but since I would like the passwords to be synchronized across sites, I have monkeypatched <code>User.objects.create_user</code> and <code>User.set_password</code> using wrappers to create Google accounts and update passwords respectively.</p> <p>Monkeypatching seems to be frowned upon, so I would to know, is there a better way to accomplish this?</p>
1
2009-01-09T19:49:53Z
605,174
<p>Have you considered subclassing the User model? This may create a different set of problems, and is only available with newer releases (not sure when the change went in, I'm on trunk).</p>
1
2009-03-03T05:08:58Z
[ "python", "django", "google-apps", "monkeypatching" ]
Syncing Django users with Google Apps without monkeypatching
429,443
<p>I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally.</p> <p>I would solely use signals, but since I would like the passwords to be synchronized across sites, I have monkeypatched <code>User.objects.create_user</code> and <code>User.set_password</code> using wrappers to create Google accounts and update passwords respectively.</p> <p>Monkeypatching seems to be frowned upon, so I would to know, is there a better way to accomplish this?</p>
1
2009-01-09T19:49:53Z
749,860
<p>Subclassing seems the best route, as long as you can change all of your code to use the new class. I think that's supported in the latest release of Django. </p>
0
2009-04-15T00:28:07Z
[ "python", "django", "google-apps", "monkeypatching" ]
Syncing Django users with Google Apps without monkeypatching
429,443
<p>I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally.</p> <p>I would solely use signals, but since I would like the passwords to be synchronized across sites, I have monkeypatched <code>User.objects.create_user</code> and <code>User.set_password</code> using wrappers to create Google accounts and update passwords respectively.</p> <p>Monkeypatching seems to be frowned upon, so I would to know, is there a better way to accomplish this?</p>
1
2009-01-09T19:49:53Z
959,044
<p>Monkeypatching is definitely bad. Hard to say anything since you've given so little code/information. But I assume you have the password in cleartext at some point (in a view, in a form) so why not sync manually then?</p>
0
2009-06-06T05:02:04Z
[ "python", "django", "google-apps", "monkeypatching" ]
Syncing Django users with Google Apps without monkeypatching
429,443
<p>I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally.</p> <p>I would solely use signals, but since I would like the passwords to be synchronized across sites, I have monkeypatched <code>User.objects.create_user</code> and <code>User.set_password</code> using wrappers to create Google accounts and update passwords respectively.</p> <p>Monkeypatching seems to be frowned upon, so I would to know, is there a better way to accomplish this?</p>
1
2009-01-09T19:49:53Z
1,157,826
<p>I subclass User with Django 1.0.2. You basically makes another table that links to the user_id. </p> <pre><code>class User(MyBaseModel): user = models.OneToOneField(User, help_text="The django created User object") </code></pre> <p>and then at runtime</p> <pre><code>@login_required def add(request) : u = request.user.get_profile() </code></pre> <p>You can then easily overwrite the needed methods.</p> <p>And for those that hadn't heard of monkeypatching : <a href="http://en.wikipedia.org/wiki/Monkey_patch" rel="nofollow">http://en.wikipedia.org/wiki/Monkey_patch</a>. It is a derivation from <strong>guerrilla patch</strong>. </p>
0
2009-07-21T07:56:22Z
[ "python", "django", "google-apps", "monkeypatching" ]
How to do pretty OSD in Python
429,648
<p>Is there a library to do pretty on screen display with Python (mainly on Linux but preferably available on other OS too) ? I know there is python-osd but it uses <a href="http://sourceforge.net/projects/libxosd" rel="nofollow">libxosd</a> which looks quite old. I would not call it <em>pretty</em>.</p> <p>Maybe a Python binding for <a href="http://cia.vc/stats/project/libaosd" rel="nofollow">libaosd</a>. But I did not find any.</p>
3
2009-01-09T20:41:12Z
429,842
<p>Actually, xosd isn't all that old; I went to university with the original author (Andre Renaud, who is a superlative programmer). It is quite low level, but pretty simple - xosd.c is only 1365 lines long. It wouldn't be hard to tweak it to display pretty much anything you want. </p>
2
2009-01-09T21:36:28Z
[ "python", "wxwidgets", "pyqt", "pygtk" ]
How to do pretty OSD in Python
429,648
<p>Is there a library to do pretty on screen display with Python (mainly on Linux but preferably available on other OS too) ? I know there is python-osd but it uses <a href="http://sourceforge.net/projects/libxosd" rel="nofollow">libxosd</a> which looks quite old. I would not call it <em>pretty</em>.</p> <p>Maybe a Python binding for <a href="http://cia.vc/stats/project/libaosd" rel="nofollow">libaosd</a>. But I did not find any.</p>
3
2009-01-09T20:41:12Z
661,102
<p>Using PyGTK on X it's possible to scrape the screen background and composite the image with a standard Pango layout.</p> <p>I have some code that does this at <a href="http://svn.sacredchao.net/svn/quodlibet/trunk/plugins/events/animosd.py" rel="nofollow">http://svn.sacredchao.net/svn/quodlibet/trunk/plugins/events/animosd.py</a>. It's a bit ugly and long, but mostly straightforward.</p>
0
2009-03-19T04:54:23Z
[ "python", "wxwidgets", "pyqt", "pygtk" ]
Regular expression: replace the suffix of a string ending in '.js' but not 'min.js'
430,047
<p>Assume infile is a variable holding the name of an input file, and similarly outfile for output file. If infile ends in <strong>.js</strong>, I'd like to replace with <strong>.min.js</strong> and that's easy enough (I think).</p> <p><strong>outfile = re.sub(r'\b.js$', '.min.js', infile)</strong></p> <p>But my question is if infile ends in <strong>.min.js</strong>, then I do not want the substitution to take place. (Otherwise, I'll end up with <strong>.min.min.js</strong>) How can I accomplish this by using regular expression?</p> <p>PS: This is not homework. If you're curious what this is for: this is for a small python script to do mass compress of JavaScript files in a directory.</p>
3
2009-01-09T22:47:16Z
430,064
<p>You want to do a negative lookbehind assertion. For instance,</p> <pre><code>outfile = re.sub(r"(?&lt;!\.min)\.js$", ".min.js", infile) </code></pre> <p>You can find more about this here: <a href="http://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow">http://docs.python.org/library/re.html#regular-expression-syntax</a></p>
9
2009-01-09T22:53:16Z
[ "python", "regex" ]
Regular expression: replace the suffix of a string ending in '.js' but not 'min.js'
430,047
<p>Assume infile is a variable holding the name of an input file, and similarly outfile for output file. If infile ends in <strong>.js</strong>, I'd like to replace with <strong>.min.js</strong> and that's easy enough (I think).</p> <p><strong>outfile = re.sub(r'\b.js$', '.min.js', infile)</strong></p> <p>But my question is if infile ends in <strong>.min.js</strong>, then I do not want the substitution to take place. (Otherwise, I'll end up with <strong>.min.min.js</strong>) How can I accomplish this by using regular expression?</p> <p>PS: This is not homework. If you're curious what this is for: this is for a small python script to do mass compress of JavaScript files in a directory.</p>
3
2009-01-09T22:47:16Z
430,940
<p>For tasks this simple, there's no need for regexps. String methods can be more readable, eg.:</p> <pre><code>if filename.endswith('.js') and not filename.endswith('.min.js'): filename= filename[:-3]+'.min.js' </code></pre>
3
2009-01-10T13:14:08Z
[ "python", "regex" ]
How to split strings into text and number?
430,079
<p>I'd like to split strings like these</p> <p>'foofo21' 'bar432' 'foobar12345'</p> <p>into</p> <p>['foofo', '21'] ['bar', '432'] ['foobar', '12345']</p> <p>Does somebody know an easy and simple way to do this in python?</p>
17
2009-01-09T23:02:16Z
430,102
<p>I would approach this by using <code>re.match</code> in the following way:</p> <pre><code>match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I) if match: items = match.groups() # items is ("foo", "21") </code></pre>
25
2009-01-09T23:12:01Z
[ "python", "string", "split" ]
How to split strings into text and number?
430,079
<p>I'd like to split strings like these</p> <p>'foofo21' 'bar432' 'foobar12345'</p> <p>into</p> <p>['foofo', '21'] ['bar', '432'] ['foobar', '12345']</p> <p>Does somebody know an easy and simple way to do this in python?</p>
17
2009-01-09T23:02:16Z
430,105
<pre><code>&gt;&gt;&gt; r = re.compile("([a-zA-Z]+)([0-9]+)") &gt;&gt;&gt; m = r.match("foobar12345") &gt;&gt;&gt; m.group(1) 'foobar' &gt;&gt;&gt; m.group(2) '12345' </code></pre> <p>So, if you have a list of strings with that format:</p> <pre><code>import re r = re.compile("([a-zA-Z]+)([0-9]+)") strings = ['foofo21', 'bar432', 'foobar12345'] print [r.match(string).groups() for string in strings] </code></pre> <p>Output:</p> <pre><code>[('foofo', '21'), ('bar', '432'), ('foobar', '12345')] </code></pre>
8
2009-01-09T23:12:16Z
[ "python", "string", "split" ]
How to split strings into text and number?
430,079
<p>I'd like to split strings like these</p> <p>'foofo21' 'bar432' 'foobar12345'</p> <p>into</p> <p>['foofo', '21'] ['bar', '432'] ['foobar', '12345']</p> <p>Does somebody know an easy and simple way to do this in python?</p>
17
2009-01-09T23:02:16Z
430,151
<p>I'm always the one to bring up findall() =)</p> <pre><code>&gt;&gt;&gt; strings = ['foofo21', 'bar432', 'foobar12345'] &gt;&gt;&gt; [re.findall(r'(\w+?)(\d+)', s)[0] for s in strings] [('foofo', '21'), ('bar', '432'), ('foobar', '12345')] </code></pre> <p>Note that I'm using a simpler (less to type) regex than most of the previous answers.</p>
4
2009-01-09T23:40:54Z
[ "python", "string", "split" ]
How to split strings into text and number?
430,079
<p>I'd like to split strings like these</p> <p>'foofo21' 'bar432' 'foobar12345'</p> <p>into</p> <p>['foofo', '21'] ['bar', '432'] ['foobar', '12345']</p> <p>Does somebody know an easy and simple way to do this in python?</p>
17
2009-01-09T23:02:16Z
430,296
<p>Yet Another Option:</p> <pre><code>&gt;&gt;&gt; [re.split(r'(\d+)', s) for s in ('foofo21', 'bar432', 'foobar12345')] [['foofo', '21', ''], ['bar', '432', ''], ['foobar', '12345', '']] </code></pre>
6
2009-01-10T00:54:09Z
[ "python", "string", "split" ]
How to split strings into text and number?
430,079
<p>I'd like to split strings like these</p> <p>'foofo21' 'bar432' 'foobar12345'</p> <p>into</p> <p>['foofo', '21'] ['bar', '432'] ['foobar', '12345']</p> <p>Does somebody know an easy and simple way to do this in python?</p>
17
2009-01-09T23:02:16Z
430,665
<pre> >>> def mysplit(s): ... head = s.rstrip('0123456789') ... tail = s[len(head):] ... return head, tail ... >>> [mysplit(s) for s in ['foofo21', 'bar432', 'foobar12345']] [('foofo', '21'), ('bar', '432'), ('foobar', '12345')] >>> </pre>
10
2009-01-10T06:17:25Z
[ "python", "string", "split" ]
How to split strings into text and number?
430,079
<p>I'd like to split strings like these</p> <p>'foofo21' 'bar432' 'foobar12345'</p> <p>into</p> <p>['foofo', '21'] ['bar', '432'] ['foobar', '12345']</p> <p>Does somebody know an easy and simple way to do this in python?</p>
17
2009-01-09T23:02:16Z
33,812,727
<pre><code>import re s = raw_input() m = re.match(r"([a-zA-Z]+)([0-9]+)",s) print m.group(0) print m.group(1) print m.group(2) </code></pre>
0
2015-11-19T19:28:53Z
[ "python", "string", "split" ]
Best way to poll a web service (eg, for a twitter app)
430,226
<p>I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past.</p> <p>A couple scenarios I've come up with:</p> <ol> <li><p>The querying process starts every X seconds, eg a cron job runs a python script</p></li> <li><p>A process continually loops and queries at each iteration, eg ... well, here is where I enter unfamiliar territory. Do I just run a python script that doesn't end?</p></li> </ol> <p>Thanks for your advice.</p> <p>ps - regarding the particulars of twitter: I know that it sends emails for following and direct messages, but sometimes one might want the flexibility of parsing @replies. In those cases, I believe polling is as good as it gets.</p> <p>pps - twitter limits bots to 100 requests per 60 minutes. I don't know if this also limits web scraping or rss feed reading. Anyone know how easy or hard it is to be whitelisted?</p> <p>Thanks again.</p>
4
2009-01-10T00:10:56Z
430,245
<p>You should have a page that is like a Ping or Heartbeat page. The you have another process that "tickles" or hits that page, usually you can do this in your Control Panel of your web host, or use a cron if you have a local access. Then this script can keep statistics of how often it has polled in a database or some data store and then you poll the service as often as you really need to, of course limiting it to whatever the providers limit is. You definitely don't want to (and certainly don't want to rely) on a python scrip that "doesn't end." :)</p>
0
2009-01-10T00:22:11Z
[ "python", "twitter", "polling" ]
Best way to poll a web service (eg, for a twitter app)
430,226
<p>I need to poll a web service, in this case twitter's API, and I'm wondering what the conventional wisdom is on this topic. I'm not sure whether this is important, but I've always found feedback useful in the past.</p> <p>A couple scenarios I've come up with:</p> <ol> <li><p>The querying process starts every X seconds, eg a cron job runs a python script</p></li> <li><p>A process continually loops and queries at each iteration, eg ... well, here is where I enter unfamiliar territory. Do I just run a python script that doesn't end?</p></li> </ol> <p>Thanks for your advice.</p> <p>ps - regarding the particulars of twitter: I know that it sends emails for following and direct messages, but sometimes one might want the flexibility of parsing @replies. In those cases, I believe polling is as good as it gets.</p> <p>pps - twitter limits bots to 100 requests per 60 minutes. I don't know if this also limits web scraping or rss feed reading. Anyone know how easy or hard it is to be whitelisted?</p> <p>Thanks again.</p>
4
2009-01-10T00:10:56Z
430,258
<p>"Do I just run a python script that doesn't end?"</p> <p>How is this unfamiliar territory?</p> <pre><code>import time polling_interval = 36.0 # (100 requests in 3600 seconds) running= True while running: start= time.clock() poll_twitter() anything_else_that_seems_important() work_duration = time.clock() - start time.sleep( polling_interval - work_duration ) </code></pre> <p>It's just a loop.</p>
5
2009-01-10T00:31:53Z
[ "python", "twitter", "polling" ]
Draw rounded corners on photo with PIL
430,379
<p>My site is full of rounded corners on every box and picture, except for the thumbnails of user uploaded photos.</p> <p>How can I use the Python Imaging Library to 'draw' white or transparent rounded corners onto each thumbnail?</p>
0
2009-01-10T02:00:31Z
430,407
<p>From Fredrik Lundh:</p> <p>create a mask image with round corners (either with your favourite image editor or using ImageDraw/aggdraw or some such).</p> <p>in your program, load the mask image, and cut out the four corners using "crop".</p> <p>then, for each image, create a thumbnail as usual, and use the corner masks on the corners of the thumbnail.</p> <ul> <li><p>if you want transparent corners, create an "L" image with the same size as the thumbnail, use "paste" to add the corner masks in that image, and then use "putalpha" to attach the alpha layer it to the thumbnail.</p></li> <li><p>if you want solid corners, use "paste" on the thumbnail instead, using a solid color as the source.</p></li> </ul> <p></p> <p><a href="http://mail.python.org/pipermail/python-list/2008-January/472508.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2008-January/472508.html</a></p>
5
2009-01-10T02:17:46Z
[ "python", "python-imaging-library", "rounded-corners" ]
Draw rounded corners on photo with PIL
430,379
<p>My site is full of rounded corners on every box and picture, except for the thumbnails of user uploaded photos.</p> <p>How can I use the Python Imaging Library to 'draw' white or transparent rounded corners onto each thumbnail?</p>
0
2009-01-10T02:00:31Z
430,410
<p>Might it not be a better idea (assuming HTML is the output) to use HTML and CSS to put some rounded borders on those pictures? That way, if you want to change the look of your site, you don't have to do any image reprocessing, and you don't have to do any image processing in the first place.</p>
1
2009-01-10T02:21:03Z
[ "python", "python-imaging-library", "rounded-corners" ]
Regex for managing escaped characters for items like string literals
430,759
<p>I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:</p> <pre><code>import re regexc = re.compile(r"\'(.*?)(?&lt;!\\)\'") match = regexc.search(r""" Example: 'Foo \' Bar' End. """) print match.groups() # I want ("Foo \' Bar") to be printed above </code></pre> <p>After looking at this, there is a simple problem that the escape character being used, "<code>\</code>", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:</p> <pre><code># ... re.compile(r"\'(.*?)(?&lt;!\\(\\\\)*)\'") # ... </code></pre> <p>Any regex gurus able to tackle this problem? Thanks.</p>
9
2009-01-10T08:45:09Z
430,763
<p>If I understand what you're saying (and I'm not sure I do) you want to find the quoted string within your string ignoring escaped quotes. Is that right? If so, try this:</p> <pre><code>/(?&lt;!\\)'((?:\\'|[^'])*)(?&lt;!\\)'/ </code></pre> <p>Basically:</p> <ul> <li>Start with a single quote that isn't preceded by a backslash;</li> <li>Match zero or more occurrences of: backslash then quote or any character other than a quote;</li> <li>End in a quote;</li> <li>Don't group the middle parentheses (the ?: operator); and</li> <li>The closing quote can't be preceded by a backslash.</li> </ul> <p>Ok, I've tested this in Java (sorry that's more my schtick than Python but the principle is the same):</p> <pre><code>private final static String TESTS[] = { "'testing 123'", "'testing 123\\'", "'testing 123", "blah 'testing 123", "blah 'testing 123'", "blah 'testing 123' foo", "this 'is a \\' test'", "another \\' test 'testing \\' 123' \\' blah" }; public static void main(String args[]) { Pattern p = Pattern.compile("(?&lt;!\\\\)'((?:\\\\'|[^'])*)(?&lt;!\\\\)'"); for (String test : TESTS) { Matcher m = p.matcher(test); if (m.find()) { System.out.printf("%s =&gt; %s%n", test, m.group(1)); } else { System.out.printf("%s doesn't match%n", test); } } } </code></pre> <p>results:</p> <pre><code>'testing 123' =&gt; testing 123 'testing 123\' doesn't match 'testing 123 doesn't match blah 'testing 123 doesn't match blah 'testing 123' =&gt; testing 123 blah 'testing 123' foo =&gt; testing 123 this 'is a \' test' =&gt; is a \' test another \' test 'testing \' 123' \' blah =&gt; testing \' 123 </code></pre> <p>which seems correct.</p>
1
2009-01-10T08:56:48Z
[ "python", "regex" ]
Regex for managing escaped characters for items like string literals
430,759
<p>I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:</p> <pre><code>import re regexc = re.compile(r"\'(.*?)(?&lt;!\\)\'") match = regexc.search(r""" Example: 'Foo \' Bar' End. """) print match.groups() # I want ("Foo \' Bar") to be printed above </code></pre> <p>After looking at this, there is a simple problem that the escape character being used, "<code>\</code>", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:</p> <pre><code># ... re.compile(r"\'(.*?)(?&lt;!\\(\\\\)*)\'") # ... </code></pre> <p>Any regex gurus able to tackle this problem? Thanks.</p>
9
2009-01-10T08:45:09Z
430,781
<p>I think this will work:</p> <pre><code>import re regexc = re.compile(r"(?:^|[^\\])'(([^\\']|\\'|\\\\)*)'") def check(test, base, target): match = regexc.search(base) assert match is not None, test+": regex didn't match for "+base assert match.group(1) == target, test+": "+target+" not found in "+base print "test %s passed"%test check("Empty","''","") check("single escape1", r""" Example: 'Foo \' Bar' End. """,r"Foo \' Bar") check("single escape2", r"""'\''""",r"\'") check("double escape",r""" Example2: 'Foo \\' End. """,r"Foo \\") check("First quote escaped",r"not matched\''a'","a") check("First quote escaped beginning",r"\''a'","a") </code></pre> <p>The regular expression <code>r"(?:^|[^\\])'(([^\\']|\\'|\\\\)*)'"</code> is forward matching only the things that we want inside the string:</p> <ol> <li>Chars that aren't backslash or quote.</li> <li>Escaped quote</li> <li>Escaped backslash</li> </ol> <p>EDIT:</p> <p>Add extra regex at front to check for first quote escaped.</p>
5
2009-01-10T09:18:39Z
[ "python", "regex" ]
Regex for managing escaped characters for items like string literals
430,759
<p>I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:</p> <pre><code>import re regexc = re.compile(r"\'(.*?)(?&lt;!\\)\'") match = regexc.search(r""" Example: 'Foo \' Bar' End. """) print match.groups() # I want ("Foo \' Bar") to be printed above </code></pre> <p>After looking at this, there is a simple problem that the escape character being used, "<code>\</code>", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:</p> <pre><code># ... re.compile(r"\'(.*?)(?&lt;!\\(\\\\)*)\'") # ... </code></pre> <p>Any regex gurus able to tackle this problem? Thanks.</p>
9
2009-01-10T08:45:09Z
430,860
<p>Using <a href="http://stackoverflow.com/users/18393/cletus">cletus</a>' expression with Python's re.findall():</p> <pre><code>re.findall(r"(?&lt;!\\)'((?:\\'|[^'])*)(?&lt;!\\)'", s) </code></pre> <p>A test finding several matches in a string:</p> <pre><code>&gt;&gt;&gt; re.findall(r"(?&lt;!\\)'((?:\\'|[^'])*)(?&lt;!\\)'", r"\''foo bar gazonk' foo 'bar' gazonk 'foo \'bar\' gazonk' 'gazonk bar foo\'") ['foo bar gazonk', 'bar', "foo \\'bar\\' gazonk"] &gt;&gt;&gt; </code></pre> <p>Using cletus' TESTS array of strings:</p> <pre><code>["%s =&gt; %s" % (s, re.findall(r"(?&lt;!\\)'((?:\\'|[^'])*)(?&lt;!\\)'", s)) for s in TESTS] </code></pre> <p>Works like a charm. (Test it yourself or take my word for it.)</p>
0
2009-01-10T11:10:10Z
[ "python", "regex" ]
Regex for managing escaped characters for items like string literals
430,759
<p>I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:</p> <pre><code>import re regexc = re.compile(r"\'(.*?)(?&lt;!\\)\'") match = regexc.search(r""" Example: 'Foo \' Bar' End. """) print match.groups() # I want ("Foo \' Bar") to be printed above </code></pre> <p>After looking at this, there is a simple problem that the escape character being used, "<code>\</code>", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:</p> <pre><code># ... re.compile(r"\'(.*?)(?&lt;!\\(\\\\)*)\'") # ... </code></pre> <p>Any regex gurus able to tackle this problem? Thanks.</p>
9
2009-01-10T08:45:09Z
431,637
<p>Douglas Leeder's pattern (<code>(?:^|[^\\])'(([^\\']|\\'|\\\\)*)'</code>) will fail to match <code>"test 'test \x3F test' test"</code> and <code>"test \\'test' test"</code>. (String containing an escape other than quote and backslash, and string preceded by an escaped backslash.)</p> <p>cletus' pattern (<code>(?&lt;!\\)'((?:\\'|[^'])*)(?&lt;!\\)'</code>) will fail to match <code>"test 'test\\' test"</code>. (String ending with an escaped backslash.)</p> <p>My proposal for single-quoted strings is this:</p> <pre><code>(?&lt;!\\)(?:\\\\)*'((?:\\.|[^\\'])*)' </code></pre> <p>For both single-quoted or double-quoted stings, you could use this:</p> <pre><code>(?&lt;!\\)(?:\\\\)*("|')((?:\\.|(?!\1)[^\\])*)\1 </code></pre> <p>Test run using Python:</p> <pre><code>Doublas Leeder´s test cases: "''" matched successfully: "" " Example: 'Foo \' Bar' End. " matched successfully: "Foo \' Bar" "'\''" matched successfully: "\'" " Example2: 'Foo \\' End. " matched successfully: "Foo \\" "not matched\''a'" matched successfully: "a" "\''a'" matched successfully: "a" cletus´ test cases: "'testing 123'" matched successfully: "testing 123" "'testing 123\\'" matched successfully: "testing 123\\" "'testing 123" didn´t match, as exected. "blah 'testing 123" didn´t match, as exected. "blah 'testing 123'" matched successfully: "testing 123" "blah 'testing 123' foo" matched successfully: "testing 123" "this 'is a \' test'" matched successfully: "is a \' test" "another \' test 'testing \' 123' \' blah" matched successfully: "testing \' 123" MizardX´s test cases: "test 'test \x3F test' test" matched successfully: "test \x3F test" "test \\'test' test" matched successfully: "test" "test 'test\\' test" matched successfully: "test\\" </code></pre>
3
2009-01-10T20:01:43Z
[ "python", "regex" ]
Regex for managing escaped characters for items like string literals
430,759
<p>I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:</p> <pre><code>import re regexc = re.compile(r"\'(.*?)(?&lt;!\\)\'") match = regexc.search(r""" Example: 'Foo \' Bar' End. """) print match.groups() # I want ("Foo \' Bar") to be printed above </code></pre> <p>After looking at this, there is a simple problem that the escape character being used, "<code>\</code>", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:</p> <pre><code># ... re.compile(r"\'(.*?)(?&lt;!\\(\\\\)*)\'") # ... </code></pre> <p>Any regex gurus able to tackle this problem? Thanks.</p>
9
2009-01-10T08:45:09Z
5,455,705
<h2>re_single_quote = r"<code>'[^'\\]*(?:\\.[^'\\]*)*'"</code></h2> <p>First note that MizardX's answer is 100% accurate. I'd just like to add some additional recommendations regarding efficiency. Secondly, I'd like to note that this problem was solved and optimized long ago - See: <a href="http://rads.stackoverflow.com/amzn/click/0596528124" title="By Jeffrey Friedl. Best book on Regex - ever!">Mastering Regular Expressions (3rd Edition)</a>, (which covers this specific problem in great detail - <em>highly</em> recommended).</p> <p>First let's look at the sub-expression to match a single quoted string which may contain escaped single quotes. If you are going to allow escaped single quotes, you had better at least allow escaped-escapes as well (which is what Douglas Leeder's answer does). But as long as you're at it, its just as easy to allow escaped-anything-else. With these requirements. MizardX is the only one who got the expression right. Here it is in both short and long format (and I've taken the liberty to write this in <code>VERBOSE</code> mode, with lots of descriptive comments - which you should <em>always</em> do for non-trivial regexes):</p> <pre class="lang-py prettyprint-override"><code># MizardX's correct regex to match single quoted string: re_sq_short = r"'((?:\\.|[^\\'])*)'" re_sq_long = r""" ' # Literal opening quote ( # Capture group $1: Contents. (?: # Group for contents alternatives \\. # Either escaped anything | [^\\'] # or one non-quote, non-escape. )* # Zero or more contents alternatives. ) # End $1: Contents. ' """ </code></pre> <p>This works and correctly matches all the following string test cases:</p> <pre class="lang-py prettyprint-override"><code>text01 = r"out1 'escaped-escape: \\ ' out2" test02 = r"out1 'escaped-quote: \' ' out2" test03 = r"out1 'escaped-anything: \X ' out2" test04 = r"out1 'two escaped escapes: \\\\ ' out2" test05 = r"out1 'escaped-quote at end: \'' out2" test06 = r"out1 'escaped-escape at end: \\' out2" </code></pre> <p>Ok, now lets begin to improve on this. First, the order of the alternatives makes a difference and one should always put the most likely alternative first. In this case, non escaped characters are more likely than escaped ones, so reversing the order will improve the regex's efficiency slightly like so:</p> <pre class="lang-py prettyprint-override"><code># Better regex to match single quoted string: re_sq_short = r"'((?:[^\\']|\\.)*)'" re_sq_long = r""" ' # Literal opening quote ( # $1: Contents. (?: # Group for contents alternatives [^\\'] # Either a non-quote, non-escape, | \\. # or an escaped anything. )* # Zero or more contents alternatives. ) # End $1: Contents. ' """ </code></pre> <h2>"Unrolling-the-Loop":</h2> <p>This is a little better, but can be further improved (significantly) by applying Jeffrey Friedl's <em>"unrolling-the-loop"</em> efficiency technique (from <a href="http://rads.stackoverflow.com/amzn/click/0596528124" title="Mastering Regular Expressions (3rd Edition)">MRE3</a>). The above regex is not optimal because it must painstakingly apply the star quantifier to the non-capture group of two alternatives, each of which consume only one or two characters at a time. This alternation can be eliminated entirely by recognizing that a similar pattern is repeated over and over, and that an equivalent expression can be crafted to do the same thing without alternation. Here is an optimized expression to match a single quoted string and capture its contents into group <code>$1</code>:</p> <pre class="lang-py prettyprint-override"><code># Better regex to match single quoted string: re_sq_short = r"'([^'\\]*(?:\\.[^'\\]*)*)'" re_sq_long = r""" ' # Literal opening quote ( # $1: Contents. [^'\\]* # {normal*} Zero or more non-', non-escapes. (?: # Group for {(special normal*)*} construct. \\. # {special} Escaped anything. [^'\\]* # More {normal*}. )* # Finish up {(special normal*)*} construct. ) # End $1: Contents. ' """ </code></pre> <p>This expression gobbles up all non-quote, non-backslashes (the vast majority of most strings), in one "gulp", which drastically reduces the amount of work that the regex engine must perform. How much better you ask? Well, I entered each of the regexes presented from this question into <a href="http://www.regexbuddy.com/" title="An excellent tool for crafting and debugging regular expressions">RegexBuddy</a> and measured how many steps it took the regex engine to complete a match on the following string (which all solutions correctly match):</p> <p><code>'This is an example string which contains one \'internally quoted\' string.'</code></p> <p>Here are the benchmark results on the above test string:</p> <pre class="lang-py prettyprint-override"><code>r""" AUTHOR SINGLE-QUOTE REGEX STEPS TO: MATCH NON-MATCH Evan Fosmark '(.*?)(?&lt;!\\)' 374 376 Douglas Leeder '(([^\\']|\\'|\\\\)*)' 154 444 cletus/PEZ '((?:\\'|[^'])*)(?&lt;!\\)' 223 527 MizardX '((?:\\.|[^\\'])*)' 221 369 MizardX(improved) '((?:[^\\']|\\.)*)' 153 369 Jeffrey Friedl '([^\\']*(?:\\.[^\\']*)*)' 13 19 """ </code></pre> <p>These steps are the number of steps required to match the test string using the RegexBuddy debugger function. The "NON-MATCH" column is the number of steps required to declare match failure when the closing quote is removed from the test string. As you can see, the difference is significant for both the matching and non-matching cases. Note also that these efficiency improvements are only applicable to a NFA engine which uses backtracking (i.e. Perl, PHP, Java, Python, Javascript, .NET, Ruby and most others.) A DFA engine will not see any performance boost by this technique (See: <a href="http://swtch.com/~rsc/regexp/regexp1.html">Regular Expression Matching Can Be Simple And Fast</a>).</p> <h2>On to the complete solution:</h2> <p>The goal of the original question (my interpretation), is to pick out single quoted sub-strings (which may contain escaped quotes) from a larger string. If it is known that the text outside the quoted sub-strings will never contain escaped-single-quotes, the regex above will do the job. However, to correctly match single-quoted sub-strings within a sea of text swimming with escaped-quotes and escaped-escapes and escaped-anything-elses, (which is my interpretation of what the author is after), <strike>requires parsing from the beginning of the string</strike> No, (this is what I originally thought), but it doesn't - this can be achieved using MizardX's very clever <code>(?&lt;!\\)(?:\\\\)*</code> expression. Here are some test strings to exercise the various solutions:</p> <pre class="lang-py prettyprint-override"><code>text01 = r"out1 'escaped-escape: \\ ' out2" test02 = r"out1 'escaped-quote: \' ' out2" test03 = r"out1 'escaped-anything: \X ' out2" test04 = r"out1 'two escaped escapes: \\\\ ' out2" test05 = r"out1 'escaped-quote at end: \'' out2" test06 = r"out1 'escaped-escape at end: \\' out2" test07 = r"out1 'str1' out2 'str2' out2" test08 = r"out1 \' 'str1' out2 'str2' out2" test09 = r"out1 \\\' 'str1' out2 'str2' out2" test10 = r"out1 \\ 'str1' out2 'str2' out2" test11 = r"out1 \\\\ 'str1' out2 'str2' out2" test12 = r"out1 \\'str1' out2 'str2' out2" test13 = r"out1 \\\\'str1' out2 'str2' out2" test14 = r"out1 'str1''str2''str3' out2" </code></pre> <p>Given this test data let's see how the various solutions fare ('p'==pass, 'XX'==fail):</p> <pre class="lang-py prettyprint-override"><code>r""" AUTHOR/REGEX 01 02 03 04 05 06 07 08 09 10 11 12 13 14 Douglas Leeder p p XX p p p p p p p p XX XX XX r"(?:^|[^\\])'(([^\\']|\\'|\\\\)*)'" cletus/PEZ p p p p p XX p p p p p XX XX XX r"(?&lt;!\\)'((?:\\'|[^'])*)(?&lt;!\\)'" MizardX p p p p p p p p p p p p p p r"(?&lt;!\\)(?:\\\\)*'((?:\\.|[^\\'])*)'" ridgerunner p p p p p p p p p p p p p p r"(?&lt;!\\)(?:\\\\)*'([^'\\]*(?:\\.[^'\\]*)*)'" """ </code></pre> <h2>A working test script:</h2> <pre class="lang-py prettyprint-override"><code>import re data_list = [ r"out1 'escaped-escape: \\ ' out2", r"out1 'escaped-quote: \' ' out2", r"out1 'escaped-anything: \X ' out2", r"out1 'two escaped escapes: \\\\ ' out2", r"out1 'escaped-quote at end: \'' out2", r"out1 'escaped-escape at end: \\' out2", r"out1 'str1' out2 'str2' out2", r"out1 \' 'str1' out2 'str2' out2", r"out1 \\\' 'str1' out2 'str2' out2", r"out1 \\ 'str1' out2 'str2' out2", r"out1 \\\\ 'str1' out2 'str2' out2", r"out1 \\'str1' out2 'str2' out2", r"out1 \\\\'str1' out2 'str2' out2", r"out1 'str1''str2''str3' out2", ] regex = re.compile( r"""(?&lt;!\\)(?:\\\\)*'([^'\\]*(?:\\.[^'\\]*)*)'""", re.DOTALL) data_cnt = 0 for data in data_list: data_cnt += 1 print ("\nData string %d" % (data_cnt)) m_cnt = 0 for match in regex.finditer(data): m_cnt += 1 if (match.group(1)): print(" quoted sub-string%3d = \"%s\"" % (m_cnt, match.group(1))) </code></pre> <h1>Phew!</h1> <p>p.s. Thanks to MizardX for the very cool <code>(?&lt;!\\)(?:\\\\)*</code> expression. Learn something new every day!</p>
15
2011-03-28T07:10:00Z
[ "python", "regex" ]
Regex for managing escaped characters for items like string literals
430,759
<p>I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following:</p> <pre><code>import re regexc = re.compile(r"\'(.*?)(?&lt;!\\)\'") match = regexc.search(r""" Example: 'Foo \' Bar' End. """) print match.groups() # I want ("Foo \' Bar") to be printed above </code></pre> <p>After looking at this, there is a simple problem that the escape character being used, "<code>\</code>", can't be escaped itself. I can't figure out how to do that. I wanted a solution like the following, but negative lookbehind assertions need to be fixed length:</p> <pre><code># ... re.compile(r"\'(.*?)(?&lt;!\\(\\\\)*)\'") # ... </code></pre> <p>Any regex gurus able to tackle this problem? Thanks.</p>
9
2009-01-10T08:45:09Z
19,041,124
<pre><code>&gt;&gt;&gt; print re.findall(r"('([^'\\]|\\'|\\\\)*')",r""" Example: 'Foo \' Bar' End. """)[0][0] </code></pre> <p>'Foo \' Bar'</p>
0
2013-09-27T01:02:14Z
[ "python", "regex" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
430,976
<p>Regexes with HTML get messy. Just use a DOM parser like Beautiful Soup.</p>
16
2009-01-10T13:52:47Z
[ "python", "html", "regex", "hyperlink", "href" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
430,977
<p>No there isn't.</p> <p>You can consider using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>. You can call it the standard for parsing html files.</p>
5
2009-01-10T13:53:19Z
[ "python", "html", "regex", "hyperlink", "href" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
431,006
<p>It depends a bit on how the HTML is produced. If it's somewhat controlled you can get away with:</p> <pre><code>re.findall(r'''&lt;link\s+.*?href=['"](.*?)['"].*?(?:&lt;/link|/)&gt;''', html, re.I) </code></pre>
1
2009-01-10T14:19:18Z
[ "python", "html", "regex", "hyperlink", "href" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
431,018
<p>Answering your two subquestions there.</p> <ol> <li>I've sometimes subclassed SGMLParser (included in the core Python distribution) and must say it's straight forward.</li> <li>I don't think HTML lends itself to "well defined" regular expressions since it's not a regular language.</li> </ol>
1
2009-01-10T14:24:30Z
[ "python", "html", "regex", "hyperlink", "href" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
431,087
<blockquote> <p>Shoudln't a link be a well-defined regex?</p> </blockquote> <p>No, [X]HTML is not in the general case parseable with regex. Consider examples like:</p> <pre><code>&lt;link title='hello"&gt;world' href="x"&gt;link&lt;/link&gt; &lt;!-- &lt;link href="x"&gt;not a link&lt;/link&gt; --&gt; &lt;![CDATA[ &gt;&lt;link href="x"&gt;not a link&lt;/link&gt; ]]&gt; &lt;script&gt;document.write('&lt;link href="x"&gt;not a link&lt;/link&gt;')&lt;/script&gt; </code></pre> <p>and that's just a few random valid examples; if you have to cope with real-world tag-soup HTML there are a million malformed possibilities.</p> <p>If you know and can rely on the exact output format of the target page you can get away with regex. Otherwise it is completely the wrong choice for scraping web pages.</p>
4
2009-01-10T15:10:23Z
[ "python", "html", "regex", "hyperlink", "href" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
431,160
<p>In response to question #2 (shouldn't a link be a well defined regular expression) the answer is ... no. </p> <p>An HTML link structure is a recursive much like parens and braces in programming languages. There must be an equal number of start and end constructs and the "link" expression can be nested within itself. </p> <p>To properly match a "link" expression a regex would be required to count the start and end tags. Regular expressions are a class of Finite Automata. By definition a Finite Automata cannot "count" constructs within a pattern. A grammar is required to describe a recursive data structure such as this. The inability for a regex to "count" is why you see programming languages described with Grammars as opposed to regular expressions.</p> <p>So it is not possible to create a regex that will positively match 100% of all "link" expressions. There are certainly regex's that will match a good deal of "link"'s with a high degree of accuracy but they won't ever be perfect. </p> <p>I wrote a blog article about this problem recently. <a href="http://blogs.msdn.com/jaredpar/archive/2008/10/15/regular-expression-limitations.aspx" rel="nofollow">Regular Expression Limitations</a></p>
0
2009-01-10T15:48:48Z
[ "python", "html", "regex", "hyperlink", "href" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
431,162
<blockquote> <p>Shoudln't a link be a well-defined regex? This is a rather theoretical question,</p> </blockquote> <p>I second PEZ's answer:</p> <blockquote> <p>I don't think HTML lends itself to "well defined" regular expressions since it's not a regular language.</p> </blockquote> <p>As far as I know, any HTML tag may contain any number of nested tags. For example:</p> <pre><code>&lt;a href="http://stackoverflow.com"&gt;stackoverflow&lt;/a&gt; &lt;a href="http://stackoverflow.com"&gt;&lt;i&gt;stackoverflow&lt;/i&gt;&lt;/a&gt; &lt;a href="http://stackoverflow.com"&gt;&lt;b&gt;&lt;i&gt;stackoverflow&lt;/i&gt;&lt;/b&gt;&lt;/a&gt; ... </code></pre> <p>Thus, in principle, to match a tag properly you must be able at least to match strings of the form:</p> <pre><code>BE BBEE BBBEEE ... BBBBBBBBBBEEEEEEEEEE ... </code></pre> <p>where B means the beginning of a tag and E means the end. That is, you must be able to match strings formed by any number of B's followed by the <em>same</em> number of E's. To do that, your matcher must be able to "count", and regular expressions (i.e. finite state automata) simply cannot do that (in order to count, an automaton needs at least a stack). Referring to PEZ's answer, HTML is a context-free grammar, not a regular language.</p>
3
2009-01-10T15:50:51Z
[ "python", "html", "regex", "hyperlink", "href" ]
Regex for links in html text
430,966
<p>I hope this question is not a RTFM one. I am trying to write a Python script that extracts links from a standard HTML webpage (the <code>&lt;link href...</code> tags). I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?</p> <p>Adam</p> <p><strong>UPDATE:</strong> I am actually looking for two different answers: </p> <ol> <li>What's the library solution for parsing HTML links. <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> seems to be a good solution (thanks, <code>Igal Serban</code> and <code>cletus</code>!) </li> <li>Can a link be defined using a regex?</li> </ol>
7
2009-01-10T13:45:28Z
431,425
<p>As others have suggested, if real-time-like performance isn't necessary, BeautifulSoup is a good solution:</p> <pre><code>import urllib2 from BeautifulSoup import BeautifulSoup html = urllib2.urlopen("http://www.google.com").read() soup = BeautifulSoup(html) all_links = soup.findAll("a") </code></pre> <p>As for the second question, yes, HTML links ought to be well-defined, but the HTML you actually encounter is very unlikely to be standard. The beauty of BeautifulSoup is that it uses browser-like heuristics to try to parse the non-standard, malformed HTML that you are likely to actually come across. </p> <p>If you are certain to be working on standard XHTML, you can use (much) faster XML parsers like expat.</p> <p>Regex, for the reasons above (the parser must maintain state, and regex can't do that) will never be a general solution.</p>
8
2009-01-10T17:53:02Z
[ "python", "html", "regex", "hyperlink", "href" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
431,273
<p>You can call "defaults write com.apple.Desktop Background ..." as described in this article: <a href="http://thingsthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-and-launchd/" rel="nofollow">http://thingsthatwork.net/index.php/2008/02/07/fun-with-os-x-defaults-and-launchd/</a></p> <p>The article also goes into scripting this to run automatically, but the first little bit should get you started.</p> <p>You might also be interested in the defaults man pages: <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html" rel="nofollow">http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/defaults.1.html</a> </p>
4
2009-01-10T16:34:51Z
[ "python", "image", "osx" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
431,279
<p>From python, if you have <a href="http://appscript.sourceforge.net/">appscript</a> installed (<code>sudo easy_install appscript</code>), you can simply do</p> <pre><code>from appscript import app, mactypes app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg')) </code></pre> <p>Otherwise, this applescript will change the desktop background</p> <pre><code>tell application "Finder" set desktop picture to POSIX file "/your/filename.jpg" end tell </code></pre> <p>You can run it from the command line using <a href="http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/ManPages/man1/osascript.1.html"><code>osascript</code></a>, or from Python using something like</p> <pre><code>import subprocess SCRIPT = """/usr/bin/osascript&lt;&lt;END tell application "Finder" set desktop picture to POSIX file "%s" end tell END""" def set_desktop_background(filename): subprocess.Popen(SCRIPT%filename, shell=True) </code></pre>
34
2009-01-10T16:38:06Z
[ "python", "image", "osx" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
431,286
<p>To add to <a href="http://stackoverflow.com/questions/431205/how-can-i-programatically-change-the-background-in-mac-os-x#431273">Matt Miller's response</a>: you can use <a href="http://docs.python.org/library/subprocess.html#subprocess.call" rel="nofollow">subprocess.call()</a> to execute a shell command as so:</p> <pre><code>import subprocess subprocess.call(["defaults", "write", "com.apple.Desktop", "background", ...]) </code></pre>
1
2009-01-10T16:41:05Z
[ "python", "image", "osx" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
431,384
<p>You could also use <a href="http://sourceforge.net/projects/appscript" rel="nofollow">py-appscript</a> instead of Popening osascript or use <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/RubyPythonCocoa/Articles/UsingScriptingBridge.html" rel="nofollow">ScriptingBridge</a> with pyobjc which is included in 10.5 but a bit more cumbersome to use.</p>
0
2009-01-10T17:31:43Z
[ "python", "image", "osx" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
2,119,076
<p>If you are doing this for the current user, you can run, from a shell:</p> <pre><code>defaults write com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black &amp; White/Lightning.jpg"; };}' </code></pre> <p>Or, as root, for another user:</p> <pre><code>/usr/bin/defaults write /Users/joeuser/Library/Preferences/com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black &amp; White/Lightning.jpg"; };}' chown joeuser /Users/joeuser/Library/Preferences/com.apple.desktop.plist </code></pre> <p>You will of course want to replace the image filename and user name.</p> <p>The new setting will take effect when the Dock starts up -- either at login, or, when you</p> <pre><code>killall Dock </code></pre> <p>[Based on <a href="http://forums.macrumors.com/showpost.php?p=7237192&amp;postcount=18">a posting elsewhere</a>, and based on information from <a href="http://stackoverflow.com/questions/431205/how-can-i-programatically-change-the-background-in-mac-os-x/431273#431273">Matt Miller's answer</a>.]</p>
21
2010-01-22T17:18:27Z
[ "python", "image", "osx" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
6,738,885
<p>I had this same question, <em>except</em> that I wanted to change the wallpaper on <em>all attached monitors.</em> Here's a Python script using <code>appscript</code> (mentioned above; <code>sudo easy_install appscript</code>) which does just that.</p> <pre><code>#!/usr/bin/python from appscript import * import argparse def __main__(): parser = argparse.ArgumentParser(description='Set desktop wallpaper.') parser.add_argument('file', type=file, help='File to use as wallpaper.') args = parser.parse_args() f = args.file se = app('System Events') desktops = se.desktops.display_name.get() for d in desktops: desk = se.desktops[its.display_name == d] desk.picture.set(mactypes.File(f.name)) __main__() </code></pre>
11
2011-07-18T20:17:05Z
[ "python", "image", "osx" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
14,861,053
<p>Another way to programmatically change the desktop wallpaper is to simply point the wallpaper setting at a file. Use your program to overwrite the file with the new design, then restart the dock: <code>killall Dock</code>. </p> <p>The following depends on Xcode, lynx and wget, but here's how I automatically download and install a monthly wallpaper on Mountain Lion (shamelessly stolen and adapted from <a href="http://ubuntuforums.org/showthread.php?t=1409827" rel="nofollow">http://ubuntuforums.org/showthread.php?t=1409827</a>) :</p> <pre><code>#!/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/local/bin size=1440 dest="/usr/local/share/backgrounds/wallpaperEAA.jpg" read -r baseurl &lt; &lt;(lynx -nonumbers -listonly -dump 'http://www.eaa.org/en/eaa/aviation-education-and-resources/airplane-desktop-wallpaper' | grep $size) &amp;&amp; wget -q "$baseurl" -O "$dest" killall Dock </code></pre> <p>Dump it into <code>/etc/periodic/monthly/</code> and baby, you got a stew goin!</p>
0
2013-02-13T19:05:16Z
[ "python", "image", "osx" ]
How can I programatically change the background in Mac OS X?
431,205
<p>How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?</p>
27
2009-01-10T16:06:48Z
26,332,804
<p>The one-line solution for Mavericks is:</p> <pre><code>osascript -e 'tell application "Finder" to set desktop picture to POSIX file "/Library/Desktop Pictures/Earth Horizon.jpg"' </code></pre>
2
2014-10-13T04:15:12Z
[ "python", "image", "osx" ]
Restarting a Python Interpreter Quietly
431,432
<p>I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.</p> <p>I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.</p> <p>I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).</p> <p>So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?</p> <p>Thanks,</p> <p>Dan</p>
6
2009-01-10T17:56:27Z
431,460
<p>One very hacky and bug prone approach might be a c module that simply copies the memory to a file so it can be loaded back the next time. But since I can't imagine that this would always work properly, would pickling be an alternative?</p> <p>If you are able to make all of your modules pickleable than you should be able to pickle everything in globals() so it can be reloaded again.</p>
0
2009-01-10T18:11:07Z
[ "python", "interpreter" ]
Restarting a Python Interpreter Quietly
431,432
<p>I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.</p> <p>I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.</p> <p>I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).</p> <p>So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?</p> <p>Thanks,</p> <p>Dan</p>
6
2009-01-10T17:56:27Z
431,685
<p>If you know in advance the modules, classes, functions, variables, etc... in use, you could pickle them to disk and reload. I'm not sure off the top of my head the best way to tackle the issue if your environment contains many unknowns. Though, it may suffice to pickle globals and locals.</p>
0
2009-01-10T20:28:26Z
[ "python", "interpreter" ]
Restarting a Python Interpreter Quietly
431,432
<p>I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.</p> <p>I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.</p> <p>I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).</p> <p>So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?</p> <p>Thanks,</p> <p>Dan</p>
6
2009-01-10T17:56:27Z
431,784
<p>Try this code from ActiveState recipes: <a href="http://code.activestate.com/recipes/572213/" rel="nofollow">http://code.activestate.com/recipes/572213/</a></p> <p>It extends pickle so it supports pickling anything defined in the shell console. Theoretically you should just be able to pickle the <strong>main</strong> module, according to their documentation:</p> <pre><code>import savestate, pickle, __main__ pickle.dump(__main__, open('savestate.pickle', 'wb'), 2) </code></pre>
3
2009-01-10T21:19:39Z
[ "python", "interpreter" ]
Restarting a Python Interpreter Quietly
431,432
<p>I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.</p> <p>I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.</p> <p>I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).</p> <p>So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?</p> <p>Thanks,</p> <p>Dan</p>
6
2009-01-10T17:56:27Z
431,829
<p>I'd suggest tackling the root cause problem. </p> <blockquote> <p>"The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application"</p> </blockquote> <p>I doubt this is actually 100% true. If the overall application is the result of an act of Congress, okay, it can't be changed. But if the overall application was written by real people, then finding and moving the code to restart the Python interpreter should be possible. It's cheaper, simpler and more reliable than <em>anything</em> else you might do to hack around the problem.</p>
1
2009-01-10T21:46:02Z
[ "python", "interpreter" ]
Restarting a Python Interpreter Quietly
431,432
<p>I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.</p> <p>I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.</p> <p>I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).</p> <p>So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?</p> <p>Thanks,</p> <p>Dan</p>
6
2009-01-10T17:56:27Z
432,034
<blockquote> <p>storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before.</p> </blockquote> <p>The module-reload-forcing approach can be made to work in some circumstances but it's a bit hairy. In summary:</p> <ul> <li><p>You need to make sure that all modules that have dependencies on each other are all reloaded at once. So any module 'x' that does 'import y' or 'from y import ...' must be deleted from sys.modules at the same time as module 'y'.</p></li> <li><p>This process will need protecting with a lock if your app or any other active module is using threads.</p></li> <li><p>Any module that leaves hooks pointing to itself in other modules cannot usefully be reloaded as references to the old module will remain in unreloaded/unreloadable code. This includes stuff like exception hooks, signals, warnings filters, encodings, monkey-patches and so on. If you start blithely reloading modules containing other people's code you might be surprised how often they do stuff like that, potentially resulting in subtle and curious errors.</p></li> </ul> <p>So to get it to work you need to have well-defined boundaries between interdependent modules - "was it imported at initial start-up time" probably isn't quite good enough - and to make sure they're nicely encapsulated without unexpected dependencies like monkey-patching.</p> <p>This can be based on folder, so for example anything in /home/me/myapp/lib could be reloaded as a unit, whilst leaving other modules alone - especially the contents of the stdlib in eg. /usr/lib/python2.x/ which is in general not reliable to reload. I've got code for this in an as-yet-unreleased webapp reloading wrapper, if you need.</p> <p>Finally:</p> <ul> <li>You need to know a little bit about the internals of sys.modules, specifically that it leaves a bunch of 'None' values to signify failed relative imports. If you don't delete them at the same time as you delete your other module values, the subsequent attempt to import a module can (sometimes) end up importing 'None', leading to confusing errors.</li> </ul> <p>This is a nasty implementation detail which might change and break your app in some future Python version, but that is the price for playing with sys.modules in unsupported ways.</p>
1
2009-01-11T00:24:43Z
[ "python", "interpreter" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
431,694
<p><code>os.chdir()</code> is the Pythonic version of <code>cd</code>.</p>
5
2009-01-10T20:34:31Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
431,695
<p><code>os.chdir()</code> is the right way.</p>
6
2009-01-10T20:34:53Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
431,715
<p>You can change the working directory with</p> <pre><code>os.chdir(path) </code></pre> <p>There are two best practices to follow when using this method:</p> <ol> <li>Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.</li> <li>Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in <a href="http://stackoverflow.com/questions/431684/how-do-i-cd-in-python/13197763#13197763">his answer</a>.</li> </ol> <p>Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use <code>os.chdir()</code> to change the CWD of the calling process.</p>
338
2009-01-10T20:41:50Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
431,720
<p>I would use <code>os.chdir</code> probably. It works like this:</p> <pre><code>os.chdir("/path/to/change/to") </code></pre> <p>By the way, if you need to figure out your current path, use <code>os.getcwd()</code>.</p> <p>More here: <a href="http://effbot.org/librarybook/os.htm">http://effbot.org/librarybook/os.htm</a></p>
98
2009-01-10T20:43:26Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
431,747
<p>If you're using a relatively new version of Python, you can also use a context manager, such as <a href="http://software.clapper.org/grizzled-python/epydoc/grizzled.os-module.html#working_directory" rel="nofollow">this one</a>:</p> <pre><code>from __future__ import with_statement from grizzled.os import working_directory with working_directory(path_to_directory): # code in here occurs within the directory # code here is in the original directory </code></pre> <p><em>UPDATE</em></p> <p>If you prefer to roll your own:</p> <pre><code>import os from contextlib import contextmanager @contextmanager def working_directory(directory): owd = os.getcwd() try: os.chdir(directory) yield directory finally: os.chdir(owd) </code></pre>
18
2009-01-10T21:02:31Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
431,776
<p>and for easy interactive use, <a href="http://ipython.scipy.org/moin/" rel="nofollow">ipython</a> has all the common shell commands built in.</p>
-5
2009-01-10T21:15:09Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
10,783,138
<p>Try this on python command line:</p> <pre><code>import os print os.getcwd() </code></pre>
1
2012-05-28T10:30:07Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
13,197,763
<p>Here's an example of a context manager to change the working directory. It is simpler than an <a href="http://code.activestate.com/recipes/576620-changedirectory-context-manager">ActiveState version</a> referred to elsewhere, but this gets the job done.</p> <h3>Context Manager: <code>cd</code></h3> <pre><code>import os class cd: """Context manager for changing the current working directory""" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath) </code></pre> <p>Or try the <a href="http://stackoverflow.com/a/24176022/263998">more concise equivalent(below)</a>, using <a href="https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager">ContextManager</a>.</p> <h3>Example</h3> <pre><code>import subprocess # just to call an arbitrary command e.g. 'ls' # enter the directory like this: with cd("~/Library"): # we are in ~/Library subprocess.call("ls") # outside the context manager we are back wherever we started. </code></pre>
194
2012-11-02T15:00:21Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
16,694,919
<p>As already pointed out by others, all the solutions above only change the working directory of the current process. This is lost when you exit back to the Unix shell. If desperate you <strong>can</strong> change the parent shell directory on Unix with this horrible hack:</p> <pre><code>def quote_against_shell_expansion(s): import pipes return pipes.quote(s) def put_text_back_into_terminal_input_buffer(text): # use of this means that it only works in an interactive session # (and if the user types while it runs they could insert characters between the characters in 'text'!) import fcntl, termios for c in text: fcntl.ioctl(1, termios.TIOCSTI, c) def change_parent_process_directory(dest): # the horror put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n") </code></pre>
7
2013-05-22T14:48:03Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
17,427,393
<p>Further into direction pointed out by Brian and based on <a href="https://github.com/amoffat/sh" rel="nofollow">sh</a> (1.0.8+)</p> <pre><code>from sh import cd, ls cd('/tmp') print ls() </code></pre>
3
2013-07-02T13:50:24Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
24,176,022
<p><code>cd()</code> is easy to write using a generator and a decorator.</p> <pre><code>from contextlib import contextmanager import os @contextmanager def cd(newdir): prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: yield finally: os.chdir(prevdir) </code></pre> <p>Then, the directory is reverted even after an exception is thrown:</p> <pre><code>os.chdir('/home') with cd('/tmp'): # ... raise Exception("There's no place like home.") # Directory is now back to '/home'. </code></pre>
36
2014-06-12T03:30:46Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
35,832,594
<p>Changing the current directory of the script process is trivial. I think the question is actually how to change the current directory of the command window from which a python script is invoked, which is very difficult. A Bat script in Windows or a Bash script in a Bash shell can do this with an ordinary cd command because the shell itself is the interpreter. In both Windows and Linux Python is a program and no program can directly change its parent's environment. However the combination of a simple shell script with a Python script doing most of the hard stuff can achieve the desired result. For example, to make an extended cd command with traversal history for backward/forward/select revisit, I wrote a relatively complex Python script invoked by a simple bat script. The traversal list is stored in a file, with the target directory on the first line. When the python script returns, the bat script reads the first line of the file and makes it the argument to cd. The complete bat script (minus comments for brevity) is:</p> <pre><code>if _%1 == _. goto cdDone if _%1 == _? goto help if /i _%1 NEQ _-H goto doCd :help echo d.bat and dSup.py 2016.03.05. Extended chdir. echo -C = clear traversal list. echo -B or nothing = backward (to previous dir). echo -F or - = forward (to next dir). echo -R = remove current from list and return to previous. echo -S = select from list. echo -H, -h, ? = help. echo . = make window title current directory. echo Anything else = target directory. goto done :doCd %~dp0dSup.py %1 for /F %%d in ( %~dp0dSupList ) do ( cd %%d if errorlevel 1 ( %~dp0dSup.py -R ) goto cdDone ) :cdDone title %CD% :done </code></pre> <p>The python script, dSup.py is:</p> <pre><code>import sys, os, msvcrt def indexNoCase ( slist, s ) : for idx in range( len( slist )) : if slist[idx].upper() == s.upper() : return idx raise ValueError # .........main process ................... if len( sys.argv ) &lt; 2 : cmd = 1 # No argument defaults to -B, the most common operation elif sys.argv[1][0] == '-': if len(sys.argv[1]) == 1 : cmd = 2 # '-' alone defaults to -F, second most common operation. else : cmd = 'CBFRS'.find( sys.argv[1][1:2].upper()) else : cmd = -1 dir = os.path.abspath( sys.argv[1] ) + '\n' # cmd is -1 = path, 0 = C, 1 = B, 2 = F, 3 = R, 4 = S fo = open( os.path.dirname( sys.argv[0] ) + '\\dSupList', mode = 'a+t' ) fo.seek( 0 ) dlist = fo.readlines( -1 ) if len( dlist ) == 0 : dlist.append( os.getcwd() + '\n' ) # Prime new directory list with current. if cmd == 1 : # B: move backward, i.e. to previous target = dlist.pop(0) dlist.append( target ) elif cmd == 2 : # F: move forward, i.e. to next target = dlist.pop( len( dlist ) - 1 ) dlist.insert( 0, target ) elif cmd == 3 : # R: remove current from list. This forces cd to previous, a # desireable side-effect dlist.pop( 0 ) elif cmd == 4 : # S: select from list # The current directory (dlist[0]) is included essentially as ESC. for idx in range( len( dlist )) : print( '(' + str( idx ) + ')', dlist[ idx ][:-1]) while True : inp = msvcrt.getche() if inp.isdigit() : inp = int( inp ) if inp &lt; len( dlist ) : print( '' ) # Print the newline we didn't get from getche. break print( ' is out of range' ) # Select 0 means the current directory and the list is not changed. Otherwise # the selected directory is moved to the top of the list. This can be done by # either rotating the whole list until the selection is at the head or pop it # and insert it to 0. It isn't obvious which would be better for the user but # since pop-insert is simpler, it is used. if inp &gt; 0 : dlist.insert( 0, dlist.pop( inp )) elif cmd == -1 : # -1: dir is the requested new directory. # If it is already in the list then remove it before inserting it at the head. # This takes care of both the common case of it having been recently visited # and the less common case of user mistakenly requesting current, in which # case it is already at the head. Deleting and putting it back is a trivial # inefficiency. try: dlist.pop( indexNoCase( dlist, dir )) except ValueError : pass dlist = dlist[:9] # Control list length by removing older dirs (should be # no more than one). dlist.insert( 0, dir ) fo.truncate( 0 ) if cmd != 0 : # C: clear the list fo.writelines( dlist ) fo.close() exit(0) </code></pre>
-2
2016-03-06T21:08:55Z
[ "python" ]
How do I "cd" in Python?
431,684
<p><code>cd</code> as in the shell command to change the working directory.</p> <p>How do I change the current working directory in Python?</p>
343
2009-01-10T20:28:16Z
39,964,190
<p>If You would like to perform something like "cd.." option, just type:</p> <p><strong>os.chdir("..")</strong> </p> <p>it is the same as in Windows cmd: cd.. Of course <strong>import os</strong> is neccessary (e.g type it as 1st line of your code)</p>
1
2016-10-10T18:05:47Z
[ "python" ]
Python csv.reader: How do I return to the top of the file?
431,752
<p>When I'm moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like "file.seek(0)". Is there anything like that for the csv module?</p> <p>Thanks ahead of time ;)</p>
27
2009-01-10T21:04:49Z
431,767
<p>You can still use file.seek(0). For instance, look at the following:</p> <pre><code>import csv file_handle = open("somefile.csv", "r") reader = csv.reader(file_handle) # Do stuff with reader file_handle.seek(0) # Do more stuff with reader as it is back at the beginning now </code></pre> <p>This should work since csv.reader is working with the same.</p>
9
2009-01-10T21:11:23Z
[ "python", "csv" ]
Python csv.reader: How do I return to the top of the file?
431,752
<p>When I'm moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like "file.seek(0)". Is there anything like that for the csv module?</p> <p>Thanks ahead of time ;)</p>
27
2009-01-10T21:04:49Z
431,771
<p>You can seek the file directly. For example:</p> <pre><code>&gt;&gt;&gt; f = open("csv.txt") &gt;&gt;&gt; c = csv.reader(f) &gt;&gt;&gt; for row in c: print row ['1', '2', '3'] ['4', '5', '6'] &gt;&gt;&gt; f.seek(0) &gt;&gt;&gt; for row in c: print row # again ['1', '2', '3'] ['4', '5', '6'] </code></pre>
43
2009-01-10T21:12:26Z
[ "python", "csv" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
431,868
<p>You can use <code>x = func()[0]</code> to return the first value, <code>x = func()[1]</code> to return the second, and so on.</p> <p>If you want to get multiple values at a time, use something like <code>x, y = func()[2:4]</code>.</p>
256
2009-01-10T22:14:42Z
[ "python", "function", "tuples" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
431,871
<p>One common convention is to use a "_" as a variable name for the elements of the tuple you wish to ignore. For instance:</p> <pre><code>def f(): return 1, 2, 3 _, _, x = f() </code></pre>
100
2009-01-10T22:18:57Z
[ "python", "function", "tuples" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
431,872
<p>Three simple choices.</p> <p>Obvious</p> <pre><code>x, _ = func() x, junk = func() </code></pre> <p>Hideous</p> <pre><code>x = func()[0] </code></pre> <p>And there are ways to do this with a decorator.</p> <pre><code>def val0( aFunc ): def pick0( *args, **kw ): return aFunc(*args,**kw)[0] return pick0 func0= val0(func) </code></pre>
9
2009-01-10T22:19:44Z
[ "python", "function", "tuples" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
431,873
<p>Remember, when you return more than one item, you're really returning a tuple. So you can do things like this:</p> <pre><code>def func(): return 1, 2 print func()[0] # prints 1 print func()[1] # prints 2 </code></pre>
11
2009-01-10T22:20:20Z
[ "python", "function", "tuples" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
433,288
<p>This seems like the best choice to me:</p> <pre><code>val1, val2, ignored1, ignored2 = some_function() </code></pre> <p>It's not cryptic or ugly (like the func()[index] method), and clearly states your purpose.</p>
2
2009-01-11T17:44:24Z
[ "python", "function", "tuples" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
433,721
<p>If you're using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking.</p> <pre><code># Example 1: a is 1 and b is [2, 3] a, *b = [1, 2, 3] # Example 2: a is 1, b is [2, 3], and c is 4 a, *b, c = [1, 2, 3, 4] # Example 3: b is [1, 2] and c is 3 *b, c = [1, 2, 3] # Example 4: a is 1 and b is [] a, *b = [1] </code></pre>
34
2009-01-11T21:15:51Z
[ "python", "function", "tuples" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
22,274,810
<p>This is not a direct answer to the question. Rather it answers this question: "How do I choose a specific function output from many possible options?".</p> <p>If you are able to write the function (ie, it is not in a library you cannot modify), then add an input argument that indicates what you want out of the function. Make it a named argument with a default value so in the "common case" you don't even have to specify it.</p> <pre><code> def fancy_function( arg1, arg2, return_type=1 ): ret_val = None if( 1 == return_type ): ret_val = arg1 + arg2 elif( 2 == return_type ): ret_val = [ arg1, arg2, arg1 * arg2 ] else: ret_val = ( arg1, arg2, arg1 + arg2, arg1 * arg2 ) return( ret_val ) </code></pre> <p>This method gives the function "advanced warning" regarding the desired output. Consequently it can skip unneeded processing and only do the work necessary to get your desired output. Also because Python does dynamic typing, the return type can change. Notice how the example returns a scalar, a list or a tuple... whatever you like!</p>
2
2014-03-08T20:42:09Z
[ "python", "function", "tuples" ]
Ignore python multiple return value
431,866
<p>Say I have a Python function that returns multiple values in a tuple:</p> <pre><code>def func(): return 1, 2 </code></pre> <p>Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:</p> <pre><code>x, temp = func() </code></pre>
112
2009-01-10T22:12:49Z
28,896,373
<p>The common practice is to use the dummy variable <code>_</code> (single underscore), as many have indicated here before.</p> <p>However, to avoid collisions with other uses of that variable name (see <a href="http://stackoverflow.com/a/5893946/3511304">this</a> response) it might be a better practice to use <code>__</code> (double underscore) instead as a throwaway variable, as pointed by <a href="http://stackoverflow.com/users/597742/ncoghlan">ncoghlan</a>. E.g.:</p> <pre><code>x, __ = func() </code></pre>
5
2015-03-06T10:01:14Z
[ "python", "function", "tuples" ]
Python: unpack to unknown number of variables?
431,944
<p>How could I unpack a tuple of unknown to, say, a list?</p> <p>I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need?</p> <p>Thanks for your help :)</p>
6
2009-01-10T23:15:59Z
431,947
<p>Unpack the tuple to a list?</p> <pre><code>l = list(t) </code></pre>
7
2009-01-10T23:18:02Z
[ "python", "casting", "iterable-unpacking" ]
Python: unpack to unknown number of variables?
431,944
<p>How could I unpack a tuple of unknown to, say, a list?</p> <p>I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need?</p> <p>Thanks for your help :)</p>
6
2009-01-10T23:15:59Z
431,958
<p>Do you mean you want to create variables on the fly? How will your program know how to reference them, if they're dynamically created?</p> <p>Tuples have lengths, just like lists. It's perfectly permissable to do something like:</p> <pre><code>total_columns = len(the_tuple) </code></pre> <p>You can also convert a tuple to a list, though there's no benefit to doing so unless you want to start modifying the results. (Tuples can't be modified; lists can.) But, anyway, converting a tuple to a list is trivial:</p> <pre><code>my_list = list(the_tuple) </code></pre> <p>There <em>are</em> ways to create variables on the fly (e.g., with <code>eval</code>), but again, how would you know how to refer to them?</p> <p>I think you should clarify exactly what you're trying to do here.</p>
3
2009-01-10T23:23:39Z
[ "python", "casting", "iterable-unpacking" ]
Python: unpack to unknown number of variables?
431,944
<p>How could I unpack a tuple of unknown to, say, a list?</p> <p>I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need?</p> <p>Thanks for your help :)</p>
6
2009-01-10T23:15:59Z
431,959
<p>You can use the asterisk to unpack a variable length. For instance:</p> <pre><code>foo, bar, *other = funct() </code></pre> <p>This should put the first item into <code>foo</code>, the second into <code>bar</code>, and all the rest into <code>other</code>.</p> <p><b>Update:</b> I forgot to mention that this is Python 3.0 compatible only.</p>
11
2009-01-10T23:24:12Z
[ "python", "casting", "iterable-unpacking" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,000
<p>Don't over-engineer it. It's a 2-D array or maybe a Board class that represents a 2-D array at best. Have functions that calculate a given row/column and functions that let you access each square. Additional methods can be used validate that each sub-3x3 and row/column don't violate the required constraints.</p>
11
2009-01-11T00:05:14Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,001
<p>Maybe a design that had a box per square, and another class to represent the puzzle itself that would have a collection of boxes, contain all the rules for box interactions, and control the overall game would be a good design.</p>
0
2009-01-11T00:06:23Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,003
<p>Well, I would use one class for the sudoku itself, with a 9 x 9 array and all the functionality to add numbers and detect errors in the pattern.</p> <p>Another class will be used to solve the puzzle.</p>
2
2009-01-11T00:06:27Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,005
<p>Do you need to do it in Python or Java? I do a lot of programming in Python, but this can be done much more concisely with integer program using a language like AMPL or GLPK, which I find more elegant (and generally more efficient) for problems like this.</p> <p>Here it is in AMPL, although I haven't verified how this works: <a href="http://taha.ineg.uark.edu/Sudoku.txt" rel="nofollow">http://taha.ineg.uark.edu/Sudoku.txt</a></p>
1
2009-01-11T00:07:04Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,008
<p>The simplest way to do it is to represent the board by a 2D 9x9 array. You'll want to have references to each row, column and 3x3 box as a separate object, so storing each cell in a String makes more sense (in Java) than using a primitive. With a String you can keep references to the same object in multiple containers.</p>
1
2009-01-11T00:08:57Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,031
<p>If you're stuck and are interested in a walkthrough of a solution, Peter Norvig wrote an article on a <a href="http://norvig.com/sudoku.html" rel="nofollow" title="Peter Norvig">Sudoku solver</a> implemented in Python.</p>
8
2009-01-11T00:20:41Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,052
<p>First, it looks like there are two kinds of cells.</p> <ul> <li><p>Known calls; those with a fixed value, no choices.</p></li> <li><p>Unknown cells; those with a set of candidate values that reduces down to a single final value.</p></li> </ul> <p>Second, there are several groups of cells.</p> <ul> <li><p>Horizontal rows and Vertical columns which must have one cell of each value. That constraint is used to remove values from various cells in the row or column.</p></li> <li><p>3x3 blocks which must have one cell of each value. That constraint is used to remove values from various cells in the block.</p></li> </ul> <p>Finally, there's the overall grid. This has several complementary views.</p> <ul> <li><p>It's 81 cells.</p></li> <li><p>The cells are also collected into a 3x3 grid of 3x3 blocks.</p></li> <li><p>The cells are also collected into 9 columns.</p></li> <li><p>The cells are also collected into 9 rows.</p></li> </ul> <p>And you have a solver strategy object. </p> <ol> <li><p>Each Unknown cell it set to having <code>set( range(1,10) )</code> as the candidate values.</p></li> <li><p>For each row, column and 3x3 block (27 different collections):</p> <p>a. For each cell:</p> <ul> <li>If it has definite value (Known cells and Unknown cells implement this differently): remove that value from all other cells in this grouping.</li> </ul></li> </ol> <p>The above must be iterated until no changes are found.</p> <p>At this point, you either have it solved (all cells report a definite value), or, you have some cells with multiple values. Now you have to engage in a sophisticated back-tracking solver to find a combination of the remaining values that "works".</p>
0
2009-01-11T00:40:43Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
432,060
<p>A class containing a 1d array of 81 ints (0 is empty) is sufficient for the rule class. The rule class enforces the rules (no duplicate numbers in each row, column or 3x3 square). It also has an array of 81 bools so it knows which cells are fixed and which need to be solved. The public interface to this class has all the methods you need to manipulate the board:</p> <pre><code>int getCell(int x, int y); bool setCell(int x, int y, int value); bool clearCell(int x, int y); int[] getRow(int x); int[] getCol(int y); int[] getSubBox(int x, int y); void resetPuzzle(); void loadPuzzle(InputStream stream); </code></pre> <p>Then your solver uses the public interface to this class to solve the puzzle. The class structure of the solver I presume is the purpose of writing the 5 millionth Sudoku solver. If you are looking for hints, I'll edit this post later.</p>
0
2009-01-11T00:49:56Z
[ "python", "design", "data-structures", "sudoku" ]
Programming Design Help - How to Structure a Sudoku Solver program?
431,996
<p>I'm trying to create a sudoku solver program in Java (maybe Python). I'm just wondering how I should go about structuring this...</p> <p>Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the class?</p> <p>Do I just create functions to calculate and just control all the numbers in there with something like an multi-D array?</p> <p>And actually, even if I could just create multiple functions, how would I control all the objects if I were to make each box an object?</p> <p>Thanks.</p>
1
2009-01-10T23:57:46Z
725,867
<p>just for fun, here is what is supposed to be the shortest program, in python, that can solve a sudoku grid:</p> <pre><code>def r(a):i=a.find('0') if i&lt;0:print a [m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in`14**7*9`]r(raw_input()) </code></pre> <p>hmm ok it's quite cryptic and I don't think it matchs your question so I apologize for this noise :) </p> <p>Anyway you'll find some explanation of these 173 characters <a href="http://www.daniweb.com/software-development/python/threads/86363/soduko-problem" rel="nofollow">here</a>. There's also an explanation in french <a href="http://drgoulu.com/2008/10/12/python/" rel="nofollow">here</a></p>
1
2009-04-07T13:58:12Z
[ "python", "design", "data-structures", "sudoku" ]
3D Polygons in Python
432,080
<p>As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it.</p> <p>Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't find what I wanted. Thus before I reinvent the wheel (or invent it a whole), does anybody know of a Polygon system for Python?</p> <p>Note that it does need to be 3D (I found quite a few 2D ones). Note also that I am not interested in the displaying of them but in storing them and the datastructure within Python.</p> <p>Thanks</p>
1
2009-01-11T01:06:05Z
432,134
<p>One of the most complete geography/mapping systems available for Python that I know about is <a href="http://geodjango.org/" rel="nofollow">GeoDjango</a>. This works on top of the <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, an MVC framework. With it comes a large collection of polygon, line and distance calculation tools that can even take into account the curvature of the earth's surface if need be.</p> <p>With that said, the quickest way I can think of to produce a 3D map is using a height map. Create a two dimensional list of tuples containing (x, y, z) coordinates. Each tuple represents an evenly spaced point on a grid, mapped out by the dimensions of the array. This creates a simple plane along the X and Z axes; the ground plane. The polygons that make up the plane are quads, a polygon with four sides.</p> <p>Next, to produce the three dimensional height, simply give each point a Y value. This will create peaks and valleys in your ground plane.</p> <p>How you render this will be up to you, and converting your grid of points into a polygon format that something like OpenGL can understand may take some work, but have a look at <a href="http://vpython.org/" rel="nofollow">Visual Python</a>, its the simplest 3D library I've seen for Python.</p>
4
2009-01-11T01:37:41Z
[ "python", "3d", "polygon" ]
3D Polygons in Python
432,080
<p>As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it.</p> <p>Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't find what I wanted. Thus before I reinvent the wheel (or invent it a whole), does anybody know of a Polygon system for Python?</p> <p>Note that it does need to be 3D (I found quite a few 2D ones). Note also that I am not interested in the displaying of them but in storing them and the datastructure within Python.</p> <p>Thanks</p>
1
2009-01-11T01:06:05Z
432,238
<p>I think you mean Polyhedron, not Polygon .. and you might wanna look at <a href="http://vpython.org/" rel="nofollow">vpython</a></p>
2
2009-01-11T02:35:58Z
[ "python", "3d", "polygon" ]
3D Polygons in Python
432,080
<p>As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it.</p> <p>Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't find what I wanted. Thus before I reinvent the wheel (or invent it a whole), does anybody know of a Polygon system for Python?</p> <p>Note that it does need to be 3D (I found quite a few 2D ones). Note also that I am not interested in the displaying of them but in storing them and the datastructure within Python.</p> <p>Thanks</p>
1
2009-01-11T01:06:05Z
4,937,983
<p>CGAL is a C++ geometry library which, amongst other things, models Polyhedra (3D flat-surfaced shapes)</p> <p>It has Python bindings available. The documentation for the Polygon3 class is here: <a href="http://cgal-python.gforge.inria.fr/Manual/CGAL.Polyhedron.html#Polyhedron_3" rel="nofollow">http://cgal-python.gforge.inria.fr/Manual/CGAL.Polyhedron.html#Polyhedron_3</a></p>
0
2011-02-08T20:24:09Z
[ "python", "3d", "polygon" ]
Is there a Numpy function to return the first index of something in an array?
432,112
<p>I know there is a method for python list to return the first index of something</p> <pre><code>l = list(1,2,3) l.index(2) &gt;&gt;&gt; 1 </code></pre> <p>Is there something like that for numpy arrays?</p>
190
2009-01-11T01:21:39Z
432,146
<p>There are lots of operations in numpy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:</p> <pre><code>numpy.nonzero(array - item) </code></pre> <p>You could then take the first elements of the lists to get a single element.</p>
4
2009-01-11T01:46:53Z
[ "python", "arrays", "numpy" ]
Is there a Numpy function to return the first index of something in an array?
432,112
<p>I know there is a method for python list to return the first index of something</p> <pre><code>l = list(1,2,3) l.index(2) &gt;&gt;&gt; 1 </code></pre> <p>Is there something like that for numpy arrays?</p>
190
2009-01-11T01:21:39Z
432,175
<p>to index on any criteria, you can so something like the following:</p> <pre><code>In [1]: from numpy import * In [2]: x = arange(125).reshape((5,5,5)) In [3]: y = indices(x.shape) In [4]: locs = y[:,x &gt;= 120] # put whatever you want in place of x &gt;= 120 In [5]: pts = hsplit(locs, len(locs[0])) In [6]: for pt in pts: .....: print(', '.join(str(p[0]) for p in pt)) 4, 4, 0 4, 4, 1 4, 4, 2 4, 4, 3 4, 4, 4 </code></pre> <p>[edit] and here's a quick function to do what list.index() does, except doesn't raise an exception if it's not found. beware -- this is probably very slow on large arrays. you can probably monkeypatch this on to arrays if you'd rather use it as a method.</p> <pre><code>def ndindex(ndarray, item): if len(ndarray.shape) == 1: try: return [ndarray.tolist().index(item)] except: pass else: for i, subarray in enumerate(ndarray): try: return [i] + ndindex(subarray, item) except: pass In [1]: ndindex(x, 103) Out[1]: [4, 0, 3] </code></pre>
5
2009-01-11T02:04:27Z
[ "python", "arrays", "numpy" ]
Is there a Numpy function to return the first index of something in an array?
432,112
<p>I know there is a method for python list to return the first index of something</p> <pre><code>l = list(1,2,3) l.index(2) &gt;&gt;&gt; 1 </code></pre> <p>Is there something like that for numpy arrays?</p>
190
2009-01-11T01:21:39Z
432,289
<p>Yes, here is the answer given a Numpy array, array, and a value, item, to search for.</p> <pre><code>itemindex = numpy.where(array==item) </code></pre> <p>The result is a tuple with first all the row indices, then all the column indices.</p> <p>For example if array is two dimensions and it contained your item at two locations then</p> <pre><code>array[itemindex[0][0]][itemindex[1][0]] </code></pre> <p>would be equal to your item and so would</p> <pre><code>array[itemindex[0][1]][itemindex[1][1]] </code></pre> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html">numpy.where</a></p>
244
2009-01-11T03:12:03Z
[ "python", "arrays", "numpy" ]