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 ... | 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... | 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>... | 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>... | 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 = ... | 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/... | 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... | 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/... | 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://d... | 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>&... | 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>>>> from collections import Counter
>>> Counter([1, 2, 1, 1, 3, 2, 3,... | 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><</Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources<</ColorSpace<</CS0 563 0 R>>/ExtGState<</GS0 568 0 R>>/Font<<... | 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><</Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources<</ColorSpace<</CS0 563 0 R>>/ExtGState<</GS0 568 0 R>>/Font<<... | 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><</Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 /Resources<</ColorSpace<</CS0 563 0 R>>/ExtGState<</GS0 568 0 R>>/Font<<... | 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 ... | 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.cre... | 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.cre... | 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.cre... | 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.cre... | 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 = ... | 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 Py... | 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 Py... | 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... | 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 que... | 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"(?<!\.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.htm... | 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 que... | 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>>>> r = re.compile("([a-zA-Z]+)([0-9]+)")
>>> m = r.match("foobar12345")
>>> m.group(1)
'foobar'
>>> 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... | 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>>>> strings = ['foofo21', 'bar432', 'foobar12345']
>>> [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 mos... | 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>>>> [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 seco... | 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 ... | 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 seco... | 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.cl... | 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 corne... | 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
rege... | 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>/(?<!\\)'((?:\\'|[^'])*)(?<!\\)'/
</code></pre>
<p>Basically:</p>
<ul>
<li>Start with a single quote that isn't preceded ... | 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
rege... | 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
... | 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
rege... | 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"(?<!\\)'((?:\\'|[^'])*)(?<!\\)'", s)
</code></pre>
<p>A test finding several matches in a string:</p>
<pre><code>>>> re.findall(r"(?<!\\)'((?:\\'|[^'])*)(?&l... | 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
rege... | 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>(?<... | 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
rege... | 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.c... | 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
rege... | 9 | 2009-01-10T08:45:09Z | 19,041,124 | <pre><code>>>> 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><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>
... | 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><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>
... | 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><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>
... | 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'''<link\s+.*?href=['"](.*?)['"].*?(?:</link|/)>''', 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><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>
... | 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><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>
... | 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><link title='hello">world' href="x">link</link>
<!-- <link href="x">not a link</link> -->
<![CDATA[ &... | 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><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>
... | 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 itse... | 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><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>
... | 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... | 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><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>
... | 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 ... | 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... | 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 apple... | 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>
... | 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 in... | 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 & White/Lightning.jpg"; };}'
</code></pre>
<p>Or, as root, for another user:</p>
<pre><code>/usr/bin/defaults write /U... | 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 ar... | 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 downloa... | 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 s... | 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... | 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 s... | 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 s... | 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</stro... | 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 s... | 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 ... | 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 s... | 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... | 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 destruc... | 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.ht... | 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_dir... | 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>impo... | 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_expan... | 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>The... | 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 ... | -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 c... | 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>>>> f = open("csv.txt")
>>> c = csv.reader(f)
>>> for row in c: print row
['1', '2', '3']
['4', '5', '6']
>>> f.seek(0)
>>> 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... | 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... | 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... | 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]
retu... | 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... | 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... | 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... | 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 ... | 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... | 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 func... | 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... | 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>_... | 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?</... | 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?</... | 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... | 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?</... | 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 Py... | 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 met... | 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 met... | 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 met... | 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 met... | 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 t... | 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 met... | 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 contai... | 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 met... | 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 met... | 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>Horizont... | 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 met... | 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 al... | 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 met... | 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<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 ... | 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.... | 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 ... | 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.... | 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.... | 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.gf... | 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)
>>> 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)
>>> 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 >= 120] # put whatever you want in place of x >= 120
In [5]: pts = hsplit(locs, len(locs[0]))
In [6]: for pt ... | 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)
>>> 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 ... | 244 | 2009-01-11T03:12:03Z | [
"python",
"arrays",
"numpy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.