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 |
|---|---|---|---|---|---|---|---|---|---|
Extracting data from MS Word
| 505,925
|
<p>I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.</p>
<p>I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.</p>
<p>Which is the best way to do this:</p>
<ol>
<li>VBA macro from inside Word to create CSV and then upload to the DB?</li>
<li>VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)</li>
<li>Python script via win32com then upload to DB?</li>
</ol>
<p>The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.</p>
<p><strong>EDIT:</strong> I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:</p>
<pre><code>sFile = "D:\temp\output.txt"
fnum = FreeFile
Open sFile For Output As #fnum
num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text
Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text
If Target = "" Then
ExportText = ""
Else
ExportText = Descr & Chr(44) & Assign & Chr(44) & _
Target & Chr(13) & Chr(10)
Print #fnum, ExportText
End If
Next n
Close #fnum
</code></pre>
<p>What's up with the little control character box? Is some kind of character code coming across from Word?</p>
| 5
|
2009-02-03T03:27:53Z
| 506,134
|
<p>Word has a little marker thingy that it puts at the end of every cell of text in a table. </p>
<p>It is used just like an end-of-paragraph marker in paragraphs: to store the formatting for the entire paragraph.</p>
<p>Just use the Left() function to strip it out, i.e. </p>
<pre><code> Left(Target, Len(Target)-1))
</code></pre>
<p>By the way, instead of </p>
<pre><code> num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
</code></pre>
<p>Try this:</p>
<pre><code> For Each row in Application.ActiveDocument.Tables(2).Rows
Descr = row.Cells(2).Range.Text
</code></pre>
| 4
|
2009-02-03T05:52:44Z
|
[
"python",
"vba",
"ms-word",
"word-vba",
"pywin32"
] |
Extracting data from MS Word
| 505,925
|
<p>I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.</p>
<p>I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.</p>
<p>Which is the best way to do this:</p>
<ol>
<li>VBA macro from inside Word to create CSV and then upload to the DB?</li>
<li>VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)</li>
<li>Python script via win32com then upload to DB?</li>
</ol>
<p>The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.</p>
<p><strong>EDIT:</strong> I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:</p>
<pre><code>sFile = "D:\temp\output.txt"
fnum = FreeFile
Open sFile For Output As #fnum
num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text
Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text
If Target = "" Then
ExportText = ""
Else
ExportText = Descr & Chr(44) & Assign & Chr(44) & _
Target & Chr(13) & Chr(10)
Print #fnum, ExportText
End If
Next n
Close #fnum
</code></pre>
<p>What's up with the little control character box? Is some kind of character code coming across from Word?</p>
| 5
|
2009-02-03T03:27:53Z
| 506,812
|
<p>You could use OpenOffice. It can open word files, and also can run python macros.</p>
| 1
|
2009-02-03T11:52:04Z
|
[
"python",
"vba",
"ms-word",
"word-vba",
"pywin32"
] |
Extracting data from MS Word
| 505,925
|
<p>I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia.</p>
<p>I want to be able to pull the action items from these meeting minutes into a database so that we can access them from a web-interface, turn them into tasks and update them as they are completed.</p>
<p>Which is the best way to do this:</p>
<ol>
<li>VBA macro from inside Word to create CSV and then upload to the DB?</li>
<li>VBA macro in Word with connection to DB (how does one connect to MySQL from VBA?)</li>
<li>Python script via win32com then upload to DB?</li>
</ol>
<p>The last one is attractive to me as the web-interface is being built with Django, but I've never used win32com or tried scripting Word from python.</p>
<p><strong>EDIT:</strong> I've started extracting the text with VBA because it makes it a little easier to deal with the Word Object Model. I am having a problem though - all the text is in Tables, and when I pull the strings out of the CELLS I want, I get a strange little box character at the end of each string. My code looks like:</p>
<pre><code>sFile = "D:\temp\output.txt"
fnum = FreeFile
Open sFile For Output As #fnum
num_rows = Application.ActiveDocument.Tables(2).Rows.Count
For n = 1 To num_rows
Descr = Application.ActiveDocument.Tables(2).Cell(n, 2).Range.Text
Assign = Application.ActiveDocument.Tables(2).Cell(n, 3).Range.Text
Target = Application.ActiveDocument.Tables(2).Cell(n, 4).Range.Text
If Target = "" Then
ExportText = ""
Else
ExportText = Descr & Chr(44) & Assign & Chr(44) & _
Target & Chr(13) & Chr(10)
Print #fnum, ExportText
End If
Next n
Close #fnum
</code></pre>
<p>What's up with the little control character box? Is some kind of character code coming across from Word?</p>
| 5
|
2009-02-03T03:27:53Z
| 506,948
|
<p>It is possible to programmatically save a Word document as HTML and to import the table(s) contained into Access. This requires very little effort.</p>
| 0
|
2009-02-03T12:46:49Z
|
[
"python",
"vba",
"ms-word",
"word-vba",
"pywin32"
] |
Is there a widely used STOMP adapter for Twisted?
| 506,594
|
<p>I checked out stomper and it didn't look complete. (I'm very new to Python) Is anybody out there using stomper in a production environment?</p>
<p>If not, I guess I'll have to roll out my own Twisted Stomp adapter.</p>
<p>Thanks in advance!</p>
| 2
|
2009-02-03T10:12:30Z
| 511,246
|
<p>Twisted Stomp adapter would be way too cool. Would you consider sharing it and keep us up to date with the development?</p>
<p>Cheers</p>
| 1
|
2009-02-04T13:02:58Z
|
[
"python",
"twisted",
"activemq",
"stomp"
] |
Is there a widely used STOMP adapter for Twisted?
| 506,594
|
<p>I checked out stomper and it didn't look complete. (I'm very new to Python) Is anybody out there using stomper in a production environment?</p>
<p>If not, I guess I'll have to roll out my own Twisted Stomp adapter.</p>
<p>Thanks in advance!</p>
| 2
|
2009-02-03T10:12:30Z
| 561,901
|
<p>There is a python library called <a href="https://github.com/oisinmulvihill/stomper" rel="nofollow">stomper</a> which I've used in the past with twisted (it comes with twisted example code). Disclaimer, I've worked on the code for stomper so I like it :)</p>
<p>These days I've moved away from stomp/ActiveMQ towards AMQP + <a href="http://www.rabbitmq.com/" rel="nofollow">RabbitMQ</a>, using the <a href="https://launchpad.net/txamqp" rel="nofollow">txAMQP</a> and <a href="http://barryp.org/software/py-amqplib/" rel="nofollow">py-amqplib</a> libraries. I've found rabbit more reliable and the AMQP protocol quite good. See <a href="http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/" rel="nofollow">this article</a> for a very good overview. A big bonus is good java and .net library support too.</p>
| 7
|
2009-02-18T16:45:59Z
|
[
"python",
"twisted",
"activemq",
"stomp"
] |
Is there a widely used STOMP adapter for Twisted?
| 506,594
|
<p>I checked out stomper and it didn't look complete. (I'm very new to Python) Is anybody out there using stomper in a production environment?</p>
<p>If not, I guess I'll have to roll out my own Twisted Stomp adapter.</p>
<p>Thanks in advance!</p>
| 2
|
2009-02-03T10:12:30Z
| 4,867,000
|
<p>We just open-sourced one that's built on top of stomper: <a href="https://github.com/mozes/stompest" rel="nofollow">https://github.com/mozes/stompest</a></p>
| 1
|
2011-02-01T19:21:22Z
|
[
"python",
"twisted",
"activemq",
"stomp"
] |
Problem using django mptt
| 507,006
|
<p>I am having problem implementing django mptt.</p>
<p>Here is my model:</p>
<pre><code> class Company(models.Model):
name = models.CharField( max_length=100)
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
mptt.register(Company, order_insertion_by=['name'])
</code></pre>
<p>And </p>
<pre><code>class Financials(models.Model):
company = models.ForeignKey(Company, related_name="financials")
year = models.IntegerField()
revenue = models.DecimalField(max_digits = 10, decimal_places = 2)
</code></pre>
<p>So what I am looking at is how to add Financial as an child to Company.
I tried <code>mptt.register(Financials, parent = Company)</code> which of course give me error.</p>
<p>so mytree structure will be:</p>
<pre><code>company1
....................> Financial1
--------------------> Financial 2
company2
-------------------->Financial 3
</code></pre>
<p>Thanks</p>
| 1
|
2009-02-03T13:09:04Z
| 512,473
|
<p>Django-mptt does not support multiple types of object in the same tree. You <em>could</em> have Financial and Company both inherit from the same parent class, and then build the tree out of instances of that parent class. You'd need to store a "content type" field on the parent class so you can cast instances of the parent class to the proper subclass. This is a gross hack though, as it violates the spirit of inheritance. A Financial is not a Company, it's an attribute of a Company. The correct answer is to fix your ACL design so you can use a ForeignKey.</p>
| 1
|
2009-02-04T17:37:51Z
|
[
"python",
"django",
"mptt",
"django-mptt"
] |
Problem using django mptt
| 507,006
|
<p>I am having problem implementing django mptt.</p>
<p>Here is my model:</p>
<pre><code> class Company(models.Model):
name = models.CharField( max_length=100)
parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
mptt.register(Company, order_insertion_by=['name'])
</code></pre>
<p>And </p>
<pre><code>class Financials(models.Model):
company = models.ForeignKey(Company, related_name="financials")
year = models.IntegerField()
revenue = models.DecimalField(max_digits = 10, decimal_places = 2)
</code></pre>
<p>So what I am looking at is how to add Financial as an child to Company.
I tried <code>mptt.register(Financials, parent = Company)</code> which of course give me error.</p>
<p>so mytree structure will be:</p>
<pre><code>company1
....................> Financial1
--------------------> Financial 2
company2
-------------------->Financial 3
</code></pre>
<p>Thanks</p>
| 1
|
2009-02-03T13:09:04Z
| 12,845,637
|
<p>I recommend django-polymorphic_tree </p>
| 0
|
2012-10-11T17:53:56Z
|
[
"python",
"django",
"mptt",
"django-mptt"
] |
Python xml minidom. generate <text>Some text</text> element
| 507,405
|
<p>I have the following code.</p>
<pre><code>from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
</code></pre>
<p>The result is:</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
</code></pre>
<p>This is all fine and dandy, but what if I want the output to look like this?</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
</code></pre>
<p>Can this easily be done?</p>
<p>Orjanp...</p>
| 10
|
2009-02-03T14:59:17Z
| 507,555
|
<blockquote>
<p>Can this easily be done?</p>
</blockquote>
<p>It depends what exact rule you want, but generally no, you get little control over pretty-printing. If you want a specific format you'll usually have to write your own walker.</p>
<p>The DOM Level 3 LS parameter format-pretty-print in <a href="http://www.doxdesk.com/software/py/pxdom.html">pxdom</a> comes pretty close to your example. Its rule is that if an element contains only a single TextNode, no extra whitespace will be added. However it (currently) uses two spaces for an indent rather than four.</p>
<pre><code>>>> doc= pxdom.parseString('<a><b>c</b></a>')
>>> doc.domConfig.setParameter('format-pretty-print', True)
>>> print doc.pxdomContent
<?xml version="1.0" encoding="utf-16"?>
<a>
<b>c</b>
</a>
</code></pre>
<p>(Adjust encoding and output format for whatever type of serialisation you're doing.)</p>
<p>If that's the rule you want, and you can get away with it, you might also be able to monkey-patch minidom's Element.writexml, eg.:</p>
<pre><code>>>> from xml.dom import minidom
>>> def newwritexml(self, writer, indent= '', addindent= '', newl= ''):
... if len(self.childNodes)==1 and self.firstChild.nodeType==3:
... writer.write(indent)
... self.oldwritexml(writer) # cancel extra whitespace
... writer.write(newl)
... else:
... self.oldwritexml(writer, indent, addindent, newl)
...
>>> minidom.Element.oldwritexml= minidom.Element.writexml
>>> minidom.Element.writexml= newwritexml
</code></pre>
<p>All the usual caveats about the badness of monkey-patching apply.</p>
| 8
|
2009-02-03T15:30:32Z
|
[
"python",
"xml",
"minidom"
] |
Python xml minidom. generate <text>Some text</text> element
| 507,405
|
<p>I have the following code.</p>
<pre><code>from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
</code></pre>
<p>The result is:</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
</code></pre>
<p>This is all fine and dandy, but what if I want the output to look like this?</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
</code></pre>
<p>Can this easily be done?</p>
<p>Orjanp...</p>
| 10
|
2009-02-03T14:59:17Z
| 623,868
|
<p>The pyxml package offers a simple solution to this by using the xml.dom.ext.PrettyPrint() function. It can also print to a file descriptor.</p>
<p>But the pyxml package is no longer maintained.</p>
<p>Oerjan Pettersen</p>
| 0
|
2009-03-08T16:48:22Z
|
[
"python",
"xml",
"minidom"
] |
Python xml minidom. generate <text>Some text</text> element
| 507,405
|
<p>I have the following code.</p>
<pre><code>from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
</code></pre>
<p>The result is:</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
</code></pre>
<p>This is all fine and dandy, but what if I want the output to look like this?</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
</code></pre>
<p>Can this easily be done?</p>
<p>Orjanp...</p>
| 10
|
2009-02-03T14:59:17Z
| 1,302,302
|
<p>I was looking for exactly the same thing, and I came across this post. (the indenting provided in xml.dom.minidom broke another tool that I was using to manipulate the XML, and I needed it to be indented) I tried the accepted solution with a slightly more complex example and this was the result:</p>
<pre><code>In [1]: import pxdom
In [2]: xml = '<a><b>fda</b><c><b>fdsa</b></c></a>'
In [3]: doc = pxdom.parseString(xml)
In [4]: doc.domConfig.setParameter('format-pretty-print', True)
In [5]: print doc.pxdomContent
<?xml version="1.0" encoding="utf-16"?>
<a>
<b>fda</b><c>
<b>fdsa</b>
</c>
</a>
</code></pre>
<p>The pretty printed XML isn't formatted correctly, and I'm not too happy about monkey patching (i.e. I barely know what it means, and understand it's bad), so I looked for another solution. </p>
<p>I'm writing the output to file, so I can use the xmlindent program for Ubuntu ($sudo aptitude install xmlindent). So I just write the unformatted to the file, then call the xmlindent from within the python program:</p>
<pre><code>from subprocess import Popen, PIPE
Popen(["xmlindent", "-i", "2", "-w", "-f", "-nbe", file_name],
stderr=PIPE,
stdout=PIPE).communicate()
</code></pre>
<p>The -w switch causes the file to be overwritten, but annoyingly leaves a named e.g. "myfile.xml~" which you'll probably want to remove. The other switches are there to get the formatting right (for me). </p>
<p>P.S. xmlindent is a stream formatter, i.e. you can use it as follows:</p>
<pre><code>cat myfile.xml | xmlindent > myfile_indented.xml
</code></pre>
<p>So you might be able to use it in a python script without writing to a file if you needed to.</p>
| 2
|
2009-08-19T19:58:11Z
|
[
"python",
"xml",
"minidom"
] |
Python xml minidom. generate <text>Some text</text> element
| 507,405
|
<p>I have the following code.</p>
<pre><code>from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
</code></pre>
<p>The result is:</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
</code></pre>
<p>This is all fine and dandy, but what if I want the output to look like this?</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
</code></pre>
<p>Can this easily be done?</p>
<p>Orjanp...</p>
| 10
|
2009-02-03T14:59:17Z
| 2,517,273
|
<p>This solution worked for me without monkey patching or ceasing to use minidom: </p>
<pre><code>from xml.dom.ext import PrettyPrint
from StringIO import StringIO
def toprettyxml_fixed (node, encoding='utf-8'):
tmpStream = StringIO()
PrettyPrint(node, stream=tmpStream, encoding=encoding)
return tmpStream.getvalue()
</code></pre>
<p><a href="http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/#best-solution" rel="nofollow">http://ronrothman.com/public/leftbraned/xml-dom-minidom-toprettyxml-and-silly-whitespace/#best-solution</a></p>
| 0
|
2010-03-25T16:18:07Z
|
[
"python",
"xml",
"minidom"
] |
Python xml minidom. generate <text>Some text</text> element
| 507,405
|
<p>I have the following code.</p>
<pre><code>from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
</code></pre>
<p>The result is:</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
</code></pre>
<p>This is all fine and dandy, but what if I want the output to look like this?</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
</code></pre>
<p>Can this easily be done?</p>
<p>Orjanp...</p>
| 10
|
2009-02-03T14:59:17Z
| 12,146,051
|
<p>This could be done with toxml(), using regular expressions to tidy things up.</p>
<pre><code>>>> from xml.dom.minidom import Document
>>> import re
>>> doc = Document()
>>> root = doc.createElement('root')
>>> _ = doc.appendChild(root)
>>> main = doc.createElement('Text')
>>> _ = root.appendChild(main)
>>> text = doc.createTextNode('Some text here')
>>> _ = main.appendChild(text)
>>> out = doc.toxml()
>>> niceOut = re.sub(r'><', r'>\n<', re.sub(r'(<\/.*?>)', r'\1\n', out))
>>> print niceOut
<?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
</code></pre>
| 1
|
2012-08-27T16:43:31Z
|
[
"python",
"xml",
"minidom"
] |
Python xml minidom. generate <text>Some text</text> element
| 507,405
|
<p>I have the following code.</p>
<pre><code>from xml.dom.minidom import Document
doc = Document()
root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
root.appendChild(main)
text = doc.createTextNode('Some text here')
main.appendChild(text)
print doc.toprettyxml(indent='\t')
</code></pre>
<p>The result is:</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>
Some text here
</Text>
</root>
</code></pre>
<p>This is all fine and dandy, but what if I want the output to look like this?</p>
<pre><code><?xml version="1.0" ?>
<root>
<Text>Some text here</Text>
</root>
</code></pre>
<p>Can this easily be done?</p>
<p>Orjanp...</p>
| 10
|
2009-02-03T14:59:17Z
| 29,493,250
|
<p>Easiest way to do this is to use prettyxml, and remove the \n and \t inside the tags. That way you keep your indent as you required in your example.</p>
<p><code>xml_output = doc.toprettyxml()
nojunkintags = re.sub('>(\n|\t)</', '', xml_output)
print nojunkintags</code></p>
| 0
|
2015-04-07T13:51:20Z
|
[
"python",
"xml",
"minidom"
] |
Python includes, module scope issue
| 507,425
|
<p>I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP. </p>
<p>What I would like to do is have one single file that sets up a number of configuration variables, which would then be used throughout the code. Also, I want to make certain functions and classes available globally. For example, the main file would include a single other file, and that file would load a bunch of commonly used functions (each in its own file) and a configuration file. Within those loaded files, I also want to be able to access the functions and configuration variables. What I don't want to do, is to have to put the entire routine at the beginning of each (included) file to include all of the rest. Also, these included files are in various sub-directories, which is making it much harder to import them (especially if I have to re-import in every single file).</p>
<p>Anyway I'm looking for general advice on the best way to structure the code to achieve what I want.</p>
<p>Thanks!</p>
| 2
|
2009-02-03T15:02:03Z
| 507,576
|
<p>As far as I know program-wide global variables/functions/classes/etc. does not exist in Python, everything is "confined" in some module (namespace). So if you want some functions or classes to be used in many parts of your code one solution is creating some modules like: "globFunCl" (defining/importing from elsewhere everything you want to be "global") and "config" (containing configuration variables) and importing those everywhere you need them. If you don't like idea of using nested namespaces you can use:</p>
<pre><code>from globFunCl import *
</code></pre>
<p>This way you'll "hide" namespaces (making names look like "globals").</p>
<p>I'm not sure what you mean by not wanting to "<em>put the entire routine at the beginning of each (included) file to include all of the rest</em>", I'm afraid you can't really escape from this. Check out the <a href="http://docs.python.org/tutorial/modules.html#packages" rel="nofollow">Python Packages</a> though, they should make it easier for you.</p>
| 0
|
2009-02-03T15:35:06Z
|
[
"python",
"import",
"include",
"module"
] |
Python includes, module scope issue
| 507,425
|
<p>I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP. </p>
<p>What I would like to do is have one single file that sets up a number of configuration variables, which would then be used throughout the code. Also, I want to make certain functions and classes available globally. For example, the main file would include a single other file, and that file would load a bunch of commonly used functions (each in its own file) and a configuration file. Within those loaded files, I also want to be able to access the functions and configuration variables. What I don't want to do, is to have to put the entire routine at the beginning of each (included) file to include all of the rest. Also, these included files are in various sub-directories, which is making it much harder to import them (especially if I have to re-import in every single file).</p>
<p>Anyway I'm looking for general advice on the best way to structure the code to achieve what I want.</p>
<p>Thanks!</p>
| 2
|
2009-02-03T15:02:03Z
| 507,582
|
<p>In python, it is a common practice to have a bunch of modules that implement various functions and then have one single module that is the point-of-access to all the functions. This is basically the <a href="http://en.wikipedia.org/wiki/Facade_Pattern" rel="nofollow">facade pattern</a>.</p>
<p>An example: say you're writing a package <code>foo</code>, which includes the <code>bar</code>, <code>baz</code>, and <code>moo</code> modules.</p>
<pre><code>~/project/foo
~/project/foo/__init__.py
~/project/foo/bar.py
~/project/foo/baz.py
~/project/foo/moo.py
~/project/foo/config.py
</code></pre>
<p>What you would usually do is write <code>__init__.py</code> like this:</p>
<pre><code>from foo.bar import func1, func2
from foo.baz import func3, constant1
from foo.moo import func1 as moofunc1
from foo.config import *
</code></pre>
<p>Now, when you want to use the functions you just do</p>
<pre><code>import foo
foo.func1()
print foo.constant1
# assuming config defines a config1 variable
print foo.config1
</code></pre>
<p><hr /></p>
<p>If you wanted, you could arrange your code so that you only need to write</p>
<pre><code>import foo
</code></pre>
<p>At the top of every module, and then access everything through <code>foo</code> (which you should probably name "globals" or something to that effect). If you don't like namespaces, you could even do</p>
<pre><code>from foo import *
</code></pre>
<p>and have everything as global, but this is really not recommended. Remember: namespaces are one honking great idea!</p>
| 6
|
2009-02-03T15:36:21Z
|
[
"python",
"import",
"include",
"module"
] |
Python includes, module scope issue
| 507,425
|
<p>I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP. </p>
<p>What I would like to do is have one single file that sets up a number of configuration variables, which would then be used throughout the code. Also, I want to make certain functions and classes available globally. For example, the main file would include a single other file, and that file would load a bunch of commonly used functions (each in its own file) and a configuration file. Within those loaded files, I also want to be able to access the functions and configuration variables. What I don't want to do, is to have to put the entire routine at the beginning of each (included) file to include all of the rest. Also, these included files are in various sub-directories, which is making it much harder to import them (especially if I have to re-import in every single file).</p>
<p>Anyway I'm looking for general advice on the best way to structure the code to achieve what I want.</p>
<p>Thanks!</p>
| 2
|
2009-02-03T15:02:03Z
| 507,585
|
<p>This is a two-step process:</p>
<ol>
<li>In your module globals.py import the items from wherever.</li>
<li>In all of your other modules, do "from globals import *"</li>
</ol>
<p>This brings all of those names into the current module's namespace.</p>
<p>Now, having told you how to do this, <em>let me suggest that you don't</em>. First of all, you are loading up the local namespace with a bunch of "magically defined" entities. This violates precept 2 of the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen of Python</a>, "Explicit is better than implicit." Instead of "from foo import *", try using "import foo" and then saying "foo.some_value". If you want to use the shorter names, use "from foo import mumble, snort". Either of these methods directly exposes the actual use of the module foo.py. Using the globals.py method is just a little too magic. The primary exception to this is in an __init__.py where you are hiding some internal aspects of a package.</p>
<p>Globals are also semi-evil in that it can be very difficult to figure out who is modifying (or corrupting) them. If you have well-defined routines for getting/setting globals, then debugging them can be <em>much</em> simpler.</p>
<p>I know that PHP has this "everything is one, big, happy namespace" concept, but it's really just an artifact of poor language design.</p>
| 1
|
2009-02-03T15:36:36Z
|
[
"python",
"import",
"include",
"module"
] |
Python includes, module scope issue
| 507,425
|
<p>I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP. </p>
<p>What I would like to do is have one single file that sets up a number of configuration variables, which would then be used throughout the code. Also, I want to make certain functions and classes available globally. For example, the main file would include a single other file, and that file would load a bunch of commonly used functions (each in its own file) and a configuration file. Within those loaded files, I also want to be able to access the functions and configuration variables. What I don't want to do, is to have to put the entire routine at the beginning of each (included) file to include all of the rest. Also, these included files are in various sub-directories, which is making it much harder to import them (especially if I have to re-import in every single file).</p>
<p>Anyway I'm looking for general advice on the best way to structure the code to achieve what I want.</p>
<p>Thanks!</p>
| 2
|
2009-02-03T15:02:03Z
| 507,635
|
<p>This depends a bit on how you want to package things up. You can either think in terms of <em>files</em> or <em>modules</em>. The latter is "more pythonic", and enables you to decide exactly which items (and they can be anything with a name: classes, functions, variables, etc.) you want to make visible.</p>
<p>The basic rule is that for any file or module you import, anything directly in its namespace can be accessed. So if myfile.py contains definitions <code>def myfun(...):</code> and <code>class myclass(...)</code> as well as <code>myvar = ...</code> then you can access them from another file by</p>
<pre><code>import myfile
y = myfile.myfun(...)
x = myfile.myvar
</code></pre>
<p>or</p>
<pre><code>from myfile import myfun, myvar, myclass
</code></pre>
<p>Crucially, anything at the top level of myfile is accessible, <em>including</em> imports. So if myfile contains <code>from foo import bar</code>, then <code>myfile.bar</code> is also available. </p>
| 0
|
2009-02-03T15:47:01Z
|
[
"python",
"import",
"include",
"module"
] |
Python includes, module scope issue
| 507,425
|
<p>I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP. </p>
<p>What I would like to do is have one single file that sets up a number of configuration variables, which would then be used throughout the code. Also, I want to make certain functions and classes available globally. For example, the main file would include a single other file, and that file would load a bunch of commonly used functions (each in its own file) and a configuration file. Within those loaded files, I also want to be able to access the functions and configuration variables. What I don't want to do, is to have to put the entire routine at the beginning of each (included) file to include all of the rest. Also, these included files are in various sub-directories, which is making it much harder to import them (especially if I have to re-import in every single file).</p>
<p>Anyway I'm looking for general advice on the best way to structure the code to achieve what I want.</p>
<p>Thanks!</p>
| 2
|
2009-02-03T15:02:03Z
| 507,854
|
<p>Others have talked about the right way to do this from Python.</p>
<p>Let me add, however, that having users change a source file to configure your application -- while common in the PHP world -- isn't very Pythonic. Consider using the <A HREF="http://docs.python.org/library/configparser.html" rel="nofollow">ConfigParser</A> standard library module or the <A HREF="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow">ConfigObj</A> third-party module (which supports complex datatypes such as nested dicts, lists, etc) to parse a configuration file instead.</p>
<p>Having a <code>config.py</code> module which is responsible for parsing this configuration file, and which other code in your application imports and queries for settings, is appropriate -- but having the user edit this <code>config.py</code> on installation really isn't.</p>
| 0
|
2009-02-03T16:32:49Z
|
[
"python",
"import",
"include",
"module"
] |
How do i install pyCurl?
| 507,927
|
<p>I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.</p>
<p>i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.</p>
| 22
|
2009-02-03T16:50:24Z
| 507,955
|
<p>Depends on platform. Here on ubuntu it's as simple as:</p>
<pre><code>sudo aptitude install python-pycurl
</code></pre>
<p>It's common enough a package to think that most major Linux distributions will have it in their sources.</p>
<p>If you're on windows, you'll need <a href="http://curl.haxx.se/download.html">cURL</a> too. Then you can install <a href="http://pycurl.sourceforge.net/download/">pycurl</a> which comes wrapped in an installer.</p>
| 7
|
2009-02-03T16:56:48Z
|
[
"python",
"libcurl",
"pycurl",
"installation"
] |
How do i install pyCurl?
| 507,927
|
<p>I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.</p>
<p>i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.</p>
| 22
|
2009-02-03T16:50:24Z
| 508,143
|
<p>As it has been said already, it depends on the platform.</p>
<p>In general, I prefer to use only the Python interpreter itself that is packaged for my OS and install everything else in a <a href="http://pypi.python.org/pypi/virtualenv">virtual environment</a>, but this is a whole different story...
If you've got <a href="http://pypi.python.org/pypi/setuptools/">setuptools</a> installed, installing most Python packages is as simple as:</p>
<pre><code>easy_install pycurl
</code></pre>
| 7
|
2009-02-03T17:42:26Z
|
[
"python",
"libcurl",
"pycurl",
"installation"
] |
How do i install pyCurl?
| 507,927
|
<p>I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.</p>
<p>i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.</p>
| 22
|
2009-02-03T16:50:24Z
| 551,418
|
<p>According to <a href="http://bazaar-vcs.org/PyCurl">http://bazaar-vcs.org/PyCurl</a></p>
<blockquote>
<p>Since Windows does not come with
neither cURL or pycURL, Windows users
will have to install both.</p>
<p>cURL downloads:
<a href="http://curl.haxx.se/download.html">http://curl.haxx.se/download.html</a>.</p>
<p>pycURL downloads:
<a href="http://pycurl.sourceforge.net/download/">http://pycurl.sourceforge.net/download/</a>.</p>
<p>Both links contain Linux (and other
*Nix) tarballs/packages and Windows installer files.</p>
</blockquote>
<p>There are windows installers at both links, hopefully they will work for you.</p>
| 11
|
2009-02-15T19:07:16Z
|
[
"python",
"libcurl",
"pycurl",
"installation"
] |
How do i install pyCurl?
| 507,927
|
<p>I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.</p>
<p>i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.</p>
| 22
|
2009-02-03T16:50:24Z
| 5,385,014
|
<p>You can try to download pycurl from here </p>
<p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
<blockquote>
<p>PycURL is a interface to the libcurl library.<br>
pycurl-7.19.0.win-amd64-py2.6.âexe [863 KB] [Python 2.6] [64 bit] [Dec 09, 2010]<br>
pycurl-7.19.0.win-amd64-py2.7.âexe [863 KB] [Python 2.7] [64 bit] [Dec 09, 2010]<br>
pycurl-7.19.0.win32-py2.6.âexe [764 KB] [Python 2.6] [32 bit] [Dec 09, 2010]<br>
pycurl-7.19.0.win32-py2.7.âexe [764 KB] [Python 2.7] [32 bit] [Dec 09, 2010]</p>
</blockquote>
<p>or here</p>
<p><a href="http://pycurl.sourceforge.net/download/" rel="nofollow">http://pycurl.sourceforge.net/download/</a></p>
<blockquote>
<p>pycurl-ssl-7.15.5.1.win32-py2.4.exe 02-Oct-2006 10:10 534K precompiled win32 installer (with openssl-0.9.8c, zlib-1.2.3, c-ares-1.3.1)<br>
pycurl-ssl-7.15.5.1.win32-py2.5.exe 02-Oct-2006 10:10 534K precompiled win32 installer (with openssl-0.9.8c, zlib-1.2.3, c-ares-1.3.1)<br>
pycurl-ssl-7.16.4.win32-py2.4.exe 05-Sep-2007 19:28 546K precompiled win32 installer (with openssl-0.9.8e, zlib-1.2.3, c-ares-1.4.0)<br>
pycurl-ssl-7.16.4.win32-py2.5.exe 05-Sep-2007 19:27 546K precompiled win32 installer (with openssl-0.9.8e, zlib-1.2.3, c-ares-1.4.0)<br>
pycurl-ssl-7.18.2.win32-py2.5.exe 17-Jun-2008 20:43 540K precompiled win32 installer (with openssl-0.9.8h, zlib-1.2.3) </p>
</blockquote>
| 12
|
2011-03-21T23:35:40Z
|
[
"python",
"libcurl",
"pycurl",
"installation"
] |
How do i install pyCurl?
| 507,927
|
<p>I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.</p>
<p>i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.</p>
| 22
|
2009-02-03T16:50:24Z
| 10,699,666
|
<p><strong>TL,DR</strong></p>
<p>Get a binary from this website: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a></p>
<p>Direct links: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win32-py2.6.exe" rel="nofollow"><code>2.6 32bit</code></a>,
<a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win32-py2.7.exe" rel="nofollow"><code>2.7 32bit</code></a>,<a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win-amd64-py2.6.exe" rel="nofollow"><code>2.6 64bit</code></a>, <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/qjbh48zu/pycurl-7.19.0.win-amd64-py2.7.exe" rel="nofollow"><code>2.7 64bit</code></a></p>
<hr>
<p>For pycURL, both <code>pip</code> and <code>easy_install</code> will fail on Windows.</p>
<p>I also tried to download and install the pycURL package manually, after
downloading cURL, but that didn't work either, even if specifying the
<code>CURL_DIR</code> ( it complained that it cannot find 'lib\libcurl.lib' ). From what
I can gather from the README, what it needs in the <code>CURL_DIR</code> is the source
distribution of cURL, not the executable.</p>
<p>Downloading the precompiled version from the official <a href="http://pycurl.sourceforge.net/download/" rel="nofollow">pycURL
repository</a> will probably get you
nowhere, because it requires Python 2.5. It will <em>not</em> work with 2.6.</p>
<p>The only easy way at the moment seems to be
<a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/5kq9gygp/pycurl-7.19.0.win32-py2.6.exe" rel="nofollow">this</a>
unofficial release. It an executable installer, and I have used it without any
issues with Python 2.6. A <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/5kq9gygp/pycurl-7.19.0.win32-py2.7.exe" rel="nofollow">version for Python
2.7</a>
is available from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">the same site</a>.</p>
<hr>
<p>You might also want to consider using <a href="http://docs.python-requests.org/en/latest/" rel="nofollow"><code>requests</code></a>, a popular alternative to pycURL. It's a pleasure to use, and is actively developed.</p>
| 14
|
2012-05-22T09:52:55Z
|
[
"python",
"libcurl",
"pycurl",
"installation"
] |
How do i install pyCurl?
| 507,927
|
<p>I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.</p>
<p>i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.</p>
| 22
|
2009-02-03T16:50:24Z
| 19,478,322
|
<p>I am using Anaconda(x64) and tried to install</p>
<pre><code>easy_install pycurl
</code></pre>
<p>but when I tried to load the module package, there is an error occured.</p>
<pre><code>import pycurl
Traceback (most recent call last):
File "<ipython-input-48-859fc1d70075>", line 1, in <module>
import pycurl
ImportError: DLL load failed: %1 is not a valid Win32 application.
</code></pre>
<p>Is it re-install Anaconda(x86) is only way to solve this problem?</p>
| 0
|
2013-10-20T14:09:20Z
|
[
"python",
"libcurl",
"pycurl",
"installation"
] |
How do i install pyCurl?
| 507,927
|
<p>I am VERY new to python. I used libcurl with no problems and used pyCurl once in the past. Now i want to set it up on my machine and dev. However i have no idea how to do it. I rather not DL libcirl files and compile that along with pycurl, i want to know the simplest method. I have libcurl installed on my machine.</p>
<p>i'm on windows, i tried DLing the sources and use pycurl setup script, i had no luck.</p>
| 22
|
2009-02-03T16:50:24Z
| 27,862,269
|
<p>My environment is Windows 7 and Python 2.7. Although my Windows 7 is 64-bit, my Python 2.7 is 32-bit.</p>
<p>I had success by visiting <a href="http://pycurl.sourceforge.net/download/" rel="nofollow">http://pycurl.sourceforge.net/download/</a> and downloading and running pycurl-7.19.3.win32-py2.7.msi.</p>
| 0
|
2015-01-09T14:03:08Z
|
[
"python",
"libcurl",
"pycurl",
"installation"
] |
Fast PDF splitter library
| 508,144
|
<p>pyPdf is a great library to split, merge PDF files.
I'm using it to split pdf documents into 1 page documents. pyPdf is pure python and spends quite a lot of time in the _sweepIndirectReferences() method of the PdfFileWriter object when saving the extracted page. I need something with better performance. I've tried using multi-threading but since most of the time is spent in python code there was no speed gain because of the GIL (it actually ran slower).</p>
<p>Is there any library written in c that provides the same functionality? or does anyone have a good idea on how to improve performance (other than spawning a new process for each pdf file that I want to split)</p>
<p>Thank you in advance.</p>
<p>Follow up.
Links to a couple of command line solutions, that can prove sometimes faster than pyPDF: </p>
<ul>
<li><a href="http://multivalent.sourceforge.net/Tools/pdf/Split.html" rel="nofollow">http://multivalent.sourceforge.net/Tools/pdf/Split.html</a></li>
<li><a href="http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/" rel="nofollow">http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/</a></li>
</ul>
<p>I modified pyPDF PdfWriter class to keep track of how much time has been spent on the _sweepIndirectReferences() method. If it has been too long (right now I use the magical value of 3 seconds) then I revert to using ghostscript by making a call to it from python. </p>
<p>Thanks for all your answers. (codelogic's xpdf reference is the one that made me look for a different approach)</p>
| 4
|
2009-02-03T17:42:37Z
| 508,190
|
<p>pdfLaTex can do a lot of PDF managing and is <em>very</em> fast.</p>
<p>i've used it for some quite complex imposition worflows. the TeX language is really alien to programming, but it's easy to write a python script that generates the needed LaTex layout and processes it.</p>
| 0
|
2009-02-03T17:55:37Z
|
[
"python",
"c",
"pdf",
"pypdf"
] |
Fast PDF splitter library
| 508,144
|
<p>pyPdf is a great library to split, merge PDF files.
I'm using it to split pdf documents into 1 page documents. pyPdf is pure python and spends quite a lot of time in the _sweepIndirectReferences() method of the PdfFileWriter object when saving the extracted page. I need something with better performance. I've tried using multi-threading but since most of the time is spent in python code there was no speed gain because of the GIL (it actually ran slower).</p>
<p>Is there any library written in c that provides the same functionality? or does anyone have a good idea on how to improve performance (other than spawning a new process for each pdf file that I want to split)</p>
<p>Thank you in advance.</p>
<p>Follow up.
Links to a couple of command line solutions, that can prove sometimes faster than pyPDF: </p>
<ul>
<li><a href="http://multivalent.sourceforge.net/Tools/pdf/Split.html" rel="nofollow">http://multivalent.sourceforge.net/Tools/pdf/Split.html</a></li>
<li><a href="http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/" rel="nofollow">http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/</a></li>
</ul>
<p>I modified pyPDF PdfWriter class to keep track of how much time has been spent on the _sweepIndirectReferences() method. If it has been too long (right now I use the magical value of 3 seconds) then I revert to using ghostscript by making a call to it from python. </p>
<p>Thanks for all your answers. (codelogic's xpdf reference is the one that made me look for a different approach)</p>
| 4
|
2009-02-03T17:42:37Z
| 508,420
|
<p><a href="http://thierry.schmit.free.fr/spip/spip.php?article15" rel="nofollow">mbtPdfAsm</a> is a fast, open source command line tool for PDF processing.</p>
<p><a href="http://www.foolabs.com/xpdf/download.html" rel="nofollow">Xpdf</a> is also worth mentioning since it's GPL and written in C++. The source code is well modularized and allows for writing command line tools. </p>
| 2
|
2009-02-03T18:53:10Z
|
[
"python",
"c",
"pdf",
"pypdf"
] |
Fast PDF splitter library
| 508,144
|
<p>pyPdf is a great library to split, merge PDF files.
I'm using it to split pdf documents into 1 page documents. pyPdf is pure python and spends quite a lot of time in the _sweepIndirectReferences() method of the PdfFileWriter object when saving the extracted page. I need something with better performance. I've tried using multi-threading but since most of the time is spent in python code there was no speed gain because of the GIL (it actually ran slower).</p>
<p>Is there any library written in c that provides the same functionality? or does anyone have a good idea on how to improve performance (other than spawning a new process for each pdf file that I want to split)</p>
<p>Thank you in advance.</p>
<p>Follow up.
Links to a couple of command line solutions, that can prove sometimes faster than pyPDF: </p>
<ul>
<li><a href="http://multivalent.sourceforge.net/Tools/pdf/Split.html" rel="nofollow">http://multivalent.sourceforge.net/Tools/pdf/Split.html</a></li>
<li><a href="http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/" rel="nofollow">http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/</a></li>
</ul>
<p>I modified pyPDF PdfWriter class to keep track of how much time has been spent on the _sweepIndirectReferences() method. If it has been too long (right now I use the magical value of 3 seconds) then I revert to using ghostscript by making a call to it from python. </p>
<p>Thanks for all your answers. (codelogic's xpdf reference is the one that made me look for a different approach)</p>
| 4
|
2009-02-03T17:42:37Z
| 509,037
|
<p>Have you tried using <a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a> with pyPdf?</p>
| 1
|
2009-02-03T21:44:30Z
|
[
"python",
"c",
"pdf",
"pypdf"
] |
Fast PDF splitter library
| 508,144
|
<p>pyPdf is a great library to split, merge PDF files.
I'm using it to split pdf documents into 1 page documents. pyPdf is pure python and spends quite a lot of time in the _sweepIndirectReferences() method of the PdfFileWriter object when saving the extracted page. I need something with better performance. I've tried using multi-threading but since most of the time is spent in python code there was no speed gain because of the GIL (it actually ran slower).</p>
<p>Is there any library written in c that provides the same functionality? or does anyone have a good idea on how to improve performance (other than spawning a new process for each pdf file that I want to split)</p>
<p>Thank you in advance.</p>
<p>Follow up.
Links to a couple of command line solutions, that can prove sometimes faster than pyPDF: </p>
<ul>
<li><a href="http://multivalent.sourceforge.net/Tools/pdf/Split.html" rel="nofollow">http://multivalent.sourceforge.net/Tools/pdf/Split.html</a></li>
<li><a href="http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/" rel="nofollow">http://www.linuxsolutions.fr/how-to-extract-pages-from-a-pdf/</a></li>
</ul>
<p>I modified pyPDF PdfWriter class to keep track of how much time has been spent on the _sweepIndirectReferences() method. If it has been too long (right now I use the magical value of 3 seconds) then I revert to using ghostscript by making a call to it from python. </p>
<p>Thanks for all your answers. (codelogic's xpdf reference is the one that made me look for a different approach)</p>
| 4
|
2009-02-03T17:42:37Z
| 509,904
|
<p>Does it have to be python? My pure-Perl library <a href="http://search.cpan.org/dist/CAM-PDF/" rel="nofollow">CAM::PDF</a> is pretty fast at appending and deleting PDF document pages. It saves the sweeping for the very end, where possible.</p>
| 1
|
2009-02-04T02:47:53Z
|
[
"python",
"c",
"pdf",
"pypdf"
] |
get site name from a URL in python
| 508,183
|
<p>I am new to Python and it seems to have a lot of nice functions that I don't know about. What function can I use to get the root site name? For example, how would I get <em>faqs.org</em> if I gave the function the URL "<a href="http://ttp://www.faqs.org/docs/diveintopython/kgp_commandline.html" rel="nofollow">http://www.faqs.org/docs/diveintopython/kgp_commandline.html</a>"?</p>
| 1
|
2009-02-03T17:53:30Z
| 508,196
|
<pre><code> >>> from urllib.parse import urlparse
>>> urlparse('http://www.cwi.nl:80/%7Eguido/Python.html').hostname
'www.cwi.nl'
</code></pre>
| 5
|
2009-02-03T17:57:18Z
|
[
"python"
] |
get site name from a URL in python
| 508,183
|
<p>I am new to Python and it seems to have a lot of nice functions that I don't know about. What function can I use to get the root site name? For example, how would I get <em>faqs.org</em> if I gave the function the URL "<a href="http://ttp://www.faqs.org/docs/diveintopython/kgp_commandline.html" rel="nofollow">http://www.faqs.org/docs/diveintopython/kgp_commandline.html</a>"?</p>
| 1
|
2009-02-03T17:53:30Z
| 508,203
|
<p>The much overlooked <a href="http://www.python.org/doc/2.5.4/lib/module-urlparse.html" rel="nofollow">urlparse</a> module:</p>
<pre><code>from urlparse import urlparse
scheme, netloc, path, params, query, fragment = urlparse("http://www.faqs.org/docs/diveintopython/kgp_commandline.html")
print netloc
</code></pre>
| 2
|
2009-02-03T17:58:24Z
|
[
"python"
] |
get site name from a URL in python
| 508,183
|
<p>I am new to Python and it seems to have a lot of nice functions that I don't know about. What function can I use to get the root site name? For example, how would I get <em>faqs.org</em> if I gave the function the URL "<a href="http://ttp://www.faqs.org/docs/diveintopython/kgp_commandline.html" rel="nofollow">http://www.faqs.org/docs/diveintopython/kgp_commandline.html</a>"?</p>
| 1
|
2009-02-03T17:53:30Z
| 508,246
|
<p>What version of Python are you learning with? Note that SilentGhost's answer is for Python 3.0, while Alabaster Codify's will work with the 2.x series.</p>
| 2
|
2009-02-03T18:08:01Z
|
[
"python"
] |
Is there a good dependency analysis tool for Python?
| 508,277
|
<p>Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module.</p>
<p>What is the best dependency analysis tool for Python code?</p>
| 23
|
2009-02-03T18:18:07Z
| 508,975
|
<p>I don't know what is the <em>best</em> dependency analysis tool. You could look into <code>modulefinder</code> â it's a module in the standard library that determines the set of modules imported by a script.</p>
<p>Of course, with python you have problems of conditional imports, and even potentially scripts calling <code>__import__</code> directly, so it may not find everything. This is why tools like py2exe need special help to cope with packages like PIL.</p>
| 1
|
2009-02-03T21:30:33Z
|
[
"python",
"dependencies"
] |
Is there a good dependency analysis tool for Python?
| 508,277
|
<p>Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module.</p>
<p>What is the best dependency analysis tool for Python code?</p>
| 23
|
2009-02-03T18:18:07Z
| 509,194
|
<p>I recommend using <a href="http://furius.ca/snakefood/">snakefood</a> for creating graphical dependency graphs of Python projects. It detects dependencies nicely enough to immediately see areas for refactorisation. Its usage is pretty straightforward if you read a little bit of documentation.</p>
<p>Of course, you can omit the graph-creation step and receive a dependency dictionary in a file instead.</p>
| 24
|
2009-02-03T22:26:13Z
|
[
"python",
"dependencies"
] |
Is there a good dependency analysis tool for Python?
| 508,277
|
<p>Dependency analysis programs help us organize code by controlling the dependencies between modules in our code. When one module is a circular dependency of another module, it is a clue to find a way to turn that into a unidirectional dependency or merge two modules into one module.</p>
<p>What is the best dependency analysis tool for Python code?</p>
| 23
|
2009-02-03T18:18:07Z
| 865,757
|
<p>PyStructure â Automated Structure and Dependency Analysis of Python Code</p>
<p>This is used for PyDev's refactoring features. <a href="http://pystructure.ifs.hsr.ch/trac/" rel="nofollow">http://pystructure.ifs.hsr.ch/trac/</a></p>
| 1
|
2009-05-14T21:03:08Z
|
[
"python",
"dependencies"
] |
Why does Django only serve files containing a space?
| 508,609
|
<p>I'm writing a basic Django application. For testing / development purposes I'm trying to serve the static content of the website using Django's development server as per <a href="http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files" rel="nofollow">http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files</a>.</p>
<p>My urls.py contains:</p>
<pre><code> (r'^admin/(.*)', admin.site.root),
(r'^(?P<page_name>\S*)$', 'Blah.content.views.index'),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': 'C:/Users/My User/workspace/Blah/media',
'show_indexes': True})
</code></pre>
<p>However, when I try to access a file such as <a href="http://localhost:8000/static/images/Logo.jpg" rel="nofollow">http://localhost:8000/static/images/Logo.jpg</a> Django gives me a 404 error claiming that "No Page matches the given query."</p>
<p>When I try to access a file such as <a href="http://localhost:8000/static/images/Blah%20Logo.jpg" rel="nofollow">http://localhost:8000/static/images/Blah%20Logo.jpg</a> it serves the file!</p>
<p>What's going on?</p>
| 1
|
2009-02-03T19:45:25Z
| 508,852
|
<p>You have wrong patterns order in <code>urls.py</code>.</p>
<p>When you try to retrieve path <em>without</em> space it matches:</p>
<pre><code>(r'^(?P<page_name>\S*)$', 'Blah.content.views.index'),
</code></pre>
<p>not <code>static.serve</code> and of course you have not such page, But when you try to access path <em>with</em> space it matches proper <code>static.serve</code> pattern because it is more generic and allows spaces.</p>
<p>To solve this problem just swap those patterns.</p>
| 10
|
2009-02-03T20:50:48Z
|
[
"python",
"django"
] |
AUTO_INCREMENT in sqlite problem with python
| 508,627
|
<p>I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <a href="http://www.sqlite.org/syntaxdiagrams.html#column-constraint">http://www.sqlite.org/syntaxdiagrams.html#column-constraint</a> but that did not work either. Without AUTO_INCREMENT my table can be created.</p>
<pre><code>An error occurred: near "AUTO_INCREMENT": syntax error
CREATE TABLE fileInfo
(
fileId int NOT NULL AUTO_INCREMENT,
name varchar(255),
status int NOT NULL,
PRIMARY KEY (fileId)
);
</code></pre>
| 8
|
2009-02-03T19:49:59Z
| 508,664
|
<p>This is addressed in the <a href="http://www.sqlite.org/faq.html">SQLite FAQ</a>. <a href="http://www.sqlite.org/faq.html#q1">Question #1</a>.</p>
<p>Which states:</p>
<blockquote>
<p>How do I create an AUTOINCREMENT
field?</p>
<p>Short answer: A column declared
INTEGER PRIMARY KEY will
autoincrement.</p>
<p>Here is the long answer: If you
declare a column of a table to be
INTEGER PRIMARY KEY, then whenever you
insert a NULL into that column of the
table, the NULL is automatically
converted into an integer which is one
greater than the largest value of that
column over all other rows in the
table, or 1 if the table is empty. (If
the largest possible integer key,
9223372036854775807, then an unused
key value is chosen at random.) For
example, suppose you have a table like
this:</p>
<p><code>CREATE TABLE t1( a INTEGER PRIMARY</code>
<code>KEY, b INTEGER );</code> With this table,
the statement</p>
<p><code>INSERT INTO t1 VALUES(NULL,123);</code> is
logically equivalent to saying:</p>
<p><code>INSERT INTO t1 VALUES((SELECT max(a)
FROM t1)+1,123);</code> There is a function
named <code>sqlite3_last_insert_rowid()</code>
which will return the integer key for
the most recent insert operation.</p>
<p>Note that the integer key is one
greater than the largest key that was
in the table just prior to the insert.
The new key will be unique over all
keys currently in the table, but it
might overlap with keys that have been
previously deleted from the table. To
create keys that are unique over the
lifetime of the table, add the
AUTOINCREMENT keyword to the INTEGER
PRIMARY KEY declaration. Then the key
chosen will be one more than than the
largest key that has ever existed in
that table. If the largest possible
key has previously existed in that
table, then the INSERT will fail with
an SQLITE_FULL error code.</p>
</blockquote>
| 34
|
2009-02-03T19:56:53Z
|
[
"python",
"sqlite"
] |
AUTO_INCREMENT in sqlite problem with python
| 508,627
|
<p>I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <a href="http://www.sqlite.org/syntaxdiagrams.html#column-constraint">http://www.sqlite.org/syntaxdiagrams.html#column-constraint</a> but that did not work either. Without AUTO_INCREMENT my table can be created.</p>
<pre><code>An error occurred: near "AUTO_INCREMENT": syntax error
CREATE TABLE fileInfo
(
fileId int NOT NULL AUTO_INCREMENT,
name varchar(255),
status int NOT NULL,
PRIMARY KEY (fileId)
);
</code></pre>
| 8
|
2009-02-03T19:49:59Z
| 508,667
|
<p>It looks like AUTO_INCREMENT should be AUTOINCREMENT see <a href="http://www.sqlite.org/syntaxdiagrams.html#column-constraint">http://www.sqlite.org/syntaxdiagrams.html#column-constraint</a></p>
| 10
|
2009-02-03T19:57:06Z
|
[
"python",
"sqlite"
] |
AUTO_INCREMENT in sqlite problem with python
| 508,627
|
<p>I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page <a href="http://www.sqlite.org/syntaxdiagrams.html#column-constraint">http://www.sqlite.org/syntaxdiagrams.html#column-constraint</a> but that did not work either. Without AUTO_INCREMENT my table can be created.</p>
<pre><code>An error occurred: near "AUTO_INCREMENT": syntax error
CREATE TABLE fileInfo
(
fileId int NOT NULL AUTO_INCREMENT,
name varchar(255),
status int NOT NULL,
PRIMARY KEY (fileId)
);
</code></pre>
| 8
|
2009-02-03T19:49:59Z
| 508,684
|
<p>You could try</p>
<pre>CREATE TABLE fileInfo
(
fileid INTEGER PRIMARY KEY AUTOINCREMENT,
name STRING,
status INTEGER NOT NULL
);</pre>
| 5
|
2009-02-03T20:01:05Z
|
[
"python",
"sqlite"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 261,008
|
<p>For numeric data, <a href="http://numpy.scipy.org/" rel="nofollow">Numpy Arrays</a>:</p>
<pre><code>>>> matrix1 = array(([0,1],[1,3]))
>>> print matrix1
[[0 1]
[1 3]]
</code></pre>
<p>For general data (e.g. strings), you can use a list of lists, list of tuples, ...</p>
<pre><code>matrix2 = [['a','b'], ['x','y']]
</code></pre>
| 3
|
2008-11-04T05:47:59Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 261,084
|
<p>If you restrict yourself to the Python standard library, then a list of lists is the closest construct:</p>
<pre><code>arr = [[1,2],[3,4]]
</code></pre>
<p>gives a 2d-like array. The rows can be accessed as <code>arr[i]</code> for <code>i</code> in <code>{0,..,len(arr}</code>, but column access is difficult.</p>
<p>If you are willing to add a library dependency, the <a href="http://numpy.scipy.org" rel="nofollow">NumPy</a> package is what you really want. You can create a fixed-length array from a list of lists using:</p>
<pre><code>import numpy
arr = numpy.array([[1,2],[3,4]])
</code></pre>
<p>Column access is the same as for the list-of-lists, but column access is easy: <code>arr[:,i]</code> for <code>i</code> in <code>{0,..,arr.shape[1]}</code> (the number of columns).</p>
<p>In fact NumPy arrays can be n-dimensional.</p>
<p>Empty arrays can be created with</p>
<pre><code>numpy.empty(shape)
</code></pre>
<p>where <code>shape</code> is a tuple of size in each dimension; <code>shape=(1,3,2)</code> gives a 3-d array with size 1 in the first dimension, size 3 in the second dimension and 2 in the 3rd dimension.</p>
<p>If you want to store objects in a NumPy array, you can do that as well:</p>
<pre><code> arr = numpy.empty((1,), dtype=numpy.object)
arr[0] = 'abc'
</code></pre>
<p>For more info on the NumPy project, check out the <a href="http://numpy.scipy.org" rel="nofollow">NumPy homepage</a>.</p>
| 18
|
2008-11-04T06:37:50Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 261,340
|
<p>To create a standard python array of arrays of arbitrary size:</p>
<pre><code>a = [[0]*cols for _ in [0]*rows]
</code></pre>
<p>It is accessed like this:</p>
<pre><code>a[0][1] = 5 # set cell at row 0, col 1 to 5
</code></pre>
<p>A small python gotcha that's worth mentioning: It is tempting to just type</p>
<pre><code>a = [[0]*cols]*rows
</code></pre>
<p>but that'll copy the <em>same</em> column array to each row, resulting in unwanted behaviour. Namely:</p>
<pre><code>>>> a[0][0] = 5
>>> print a[1][0]
5
</code></pre>
| 13
|
2008-11-04T09:34:25Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 261,656
|
<p>Multidimensional arrays are a little murky. There are few reasons for using them and many reasons for thinking twice and using something else that more properly reflects what you're doing. [Hint. your question was thin on context ;-) ]</p>
<p>If you're doing matrix math, then use <code>numpy</code>.</p>
<p>However, some folks have worked with languages that force them to use multi-dimensional arrays because it's all they've got. If your as old as I am (I started programming in the 70's) then you may remember the days when multidimensional arrays were the only data structure you had. Or, your experience may have limited you to languages where you had to morph your problem into multi-dimensional arrays.</p>
<p>Say you have a collection <em>n</em> 3D points. Each point has an x, y, z, and time value. Is this an <em>n</em> x 4 array? Or a 4 * <em>n</em> array? Not really. </p>
<p>Since each point has 4 fixed values, this is more properly a list of tuples.</p>
<pre><code>a = [ ( x, y, z, t ), ( x, y, z, t ), ... ]
</code></pre>
<p>Better still, we could represent this as a list of objects.</p>
<pre><code>class Point( object ):
def __init__( self, x, y, z, t ):
self.x, self.y, self.z, self.t = x, y, z, t
a = [ Point(x,y,x,t), Point(x,y,z,t), ... ]
</code></pre>
| 10
|
2008-11-04T12:04:00Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 264,562
|
<p>Another option is to use a dictionary:</p>
<pre><code>>>> from collections import defaultdict
>>> array = defaultdict(int) # replace int with the default-factory you want
>>> array[(0,0)]
0
>>> array[(99,99)]
0
</code></pre>
<p>You'll need to keep track of the upper & lower bounds as well.</p>
| 0
|
2008-11-05T07:33:36Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 508,677
|
<p>You can create it using nested lists:</p>
<pre><code>matrix = [[a,b],[c,d],[e,f]]
</code></pre>
<p>If it has to be dynamic it's more complicated, why not write a small class yourself?</p>
<pre><code>class Matrix(object):
def __init__(self, rows, columns, default=0):
self.m = []
for i in range(rows):
self.m.append([default for j in range(columns)])
def __getitem__(self, index):
return self.m[index]
</code></pre>
<p>This can be used like this:</p>
<pre><code>m = Matrix(10,5)
m[3][6] = 7
print m[3][6] // -> 7
</code></pre>
<p>I'm sure one could implement it much more efficient. :)</p>
<p>If you need multidimensional arrays you can either create an array and calculate the offset or you'd use arrays in arrays in arrays, which can be pretty bad for memory. (Could be faster thoughâ¦) I've implemented the first idea like this:</p>
<pre><code>class Matrix(object):
def __init__(self, *dims):
self._shortcuts = [i for i in self._create_shortcuts(dims)]
self._li = [None] * (self._shortcuts.pop())
self._shortcuts.reverse()
def _create_shortcuts(self, dims):
dimList = list(dims)
dimList.reverse()
number = 1
yield 1
for i in dimList:
number *= i
yield number
def _flat_index(self, index):
if len(index) != len(self._shortcuts):
raise TypeError()
flatIndex = 0
for i, num in enumerate(index):
flatIndex += num * self._shortcuts[i]
return flatIndex
def __getitem__(self, index):
return self._li[self._flat_index(index)]
def __setitem__(self, index, value):
self._li[self._flat_index(index)] = value
</code></pre>
<p>Can be used like this:</p>
<pre><code>m = Matrix(4,5,2,6)
m[2,3,1,3] = 'x'
m[2,3,1,3] // -> 'x'
</code></pre>
| 11
|
2009-02-03T19:59:02Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 508,679
|
<p>Take a look at <a href="http://numpy.scipy.org//">numpy</a></p>
<p>here's a code snippet for you</p>
<pre><code>import numpy as npy
d = npy.zeros((len(x)+1, len(y)+1, len(x)+len(y)+3))
d[0][0][0] = 0 # although this is unnecessary since zeros initialises to zero
d[i][j][k] = npy.inf
</code></pre>
<p>I don't think you need to be implementing a scientific application to justify the use of numpy. It is faster and more flexible and you can store pretty much anything. Given that I think it is probably better to try and justify <em>not</em> using it. There are legitimate reasons, but it adds a great deal and costs very little so it deserves consideration.</p>
<p>P.S. Are your array lengths right? It looks like a pretty peculiar shaped matrix...</p>
| 11
|
2009-02-03T20:00:21Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 508,681
|
<p>Probably not relevant for you but if you are doing serious matrix work see <a href="http://numpy.scipy.org/" rel="nofollow">numpy</a></p>
| 4
|
2009-02-03T20:00:38Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 508,700
|
<p>If you are OK using sparse arrays, you could use a dict to store your values. Python's dicts allow you to use tuples as keys, as such, you could assign to and access elements of the "sparse array" (which is really a dict here) like this:</p>
<pre><code>d = {}
d[0,2,7] = 123 # assign 123 to x=0, y=2, z=7
v = d[0,2,7]
</code></pre>
| 5
|
2009-02-03T20:04:14Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 508,991
|
<p>Here's a quick way to create a nested 3-dimensional list initialized with zeros:</p>
<pre><code># dim1, dim2, dim3 are the dimensions of the array
a =[[[0 for _ in range(dim1)] for _ in range(dim2)] for _ in range(dim1) ]
a[0][0][0] = 1
</code></pre>
<p>this is a list of lists of lists, a bit more flexible than an array, you can do:</p>
<pre><code>a[0][0] = [1,2,3,4]
</code></pre>
<p>to replace a whole row in the array, or even abuse it like that:</p>
<pre><code>a[0] = "Ouch"
print a[0][0] #will print "O", since strings are indexable the same way as lists
print a[0][0][0] #will raise an error, since "O" isn't indexable
</code></pre>
<p>but if you need performance, then I agree that numpy is the way to go.</p>
<p>Also, beware of:</p>
<pre><code>a = [[[0] * 5]*5]*5]
</code></pre>
<p>If you try <code>a[0][0][0]=7</code> on the object above, you will see what's wrong with that.</p>
| 2
|
2009-02-03T21:34:16Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 1,194,934
|
<p>I've just stepped into a similar need and coded this:</p>
<pre><code>def nDimensionsMatrix(dims, elem_count, ptr=[]):
if (dims > 1):
for i in range(elem_count[dims-1]):
empty = []
ptr.append(empty)
nDimensionsMatrix(dims-1, elem_count, empty)
return ptr
elif dims == 1:
ptr.extend([0 for i in range(elem_count[dims])])
return ptr
matrix = nDimensionsMatrix(3, (2,2,2))
</code></pre>
<p>I'm not looking at speed, only funcionality ;)</p>
<p>I want to create a matrix with N dimensions and initialize with 0 (a *elem_count* number of elements in each dimension).</p>
<p>Hope its helps someone</p>
| 0
|
2009-07-28T15:31:04Z
|
[
"java",
"python",
"arrays"
] |
Multidimensional array in Python
| 508,657
|
<p>I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:</p>
<pre><code>double dArray[][][] = new double[x.length()+1][y.length()+1][x.length()+y.length()+3];
dArray[0][0][0] = 0;
dArray[0][0][1] = POSITIVE_INFINITY;
</code></pre>
<p>Further values will be created bei loops and written into the array.</p>
<p>How do I instantiate the array?</p>
<p>PS: There is no matrix multiplication involved...</p>
| 8
|
2009-02-03T19:54:37Z
| 1,494,477
|
<p>Easy, when using numpy:</p>
<pre><code>b = ones((2,3,4)) # creates a 2x3x4 array containing all ones.
</code></pre>
<p>'ones' can be replaced with 'zeros'</p>
| 0
|
2009-09-29T19:29:39Z
|
[
"java",
"python",
"arrays"
] |
Python time to age
| 508,727
|
<p>I'm trying to convert a date string into an age.</p>
<p>The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.</p>
<p>I have sucessfully converted the date using:</p>
<pre><code>>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, -1)
</code></pre>
<p>For some reason %z gives me an error for the +0200 but it doesn't matter that much.</p>
<p>I can get the current time using:</p>
<pre><code>>>> time.localtime()
(2009, 2, 3, 19, 55, 32, 1, 34, 0)
</code></pre>
<p>but how can I subtract one from the other without going though each item in the list and doing it manually?</p>
| 2
|
2009-02-03T20:12:06Z
| 508,742
|
<p>You need to use the module <code>datetime</code> and the object <a href="http://docs.python.org/library/datetime.html#datetime.timedelta" rel="nofollow"><code>datetime.timedelta</code></a></p>
<pre><code>from datetime import datetime
t1 = datetime.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
t2 = datetime.now()
tdelta = t2 - t1 # actually a datetime.timedelta object
print tdelta.days
</code></pre>
| 16
|
2009-02-03T20:16:48Z
|
[
"python",
"datetime"
] |
Python time to age
| 508,727
|
<p>I'm trying to convert a date string into an age.</p>
<p>The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.</p>
<p>I have sucessfully converted the date using:</p>
<pre><code>>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, -1)
</code></pre>
<p>For some reason %z gives me an error for the +0200 but it doesn't matter that much.</p>
<p>I can get the current time using:</p>
<pre><code>>>> time.localtime()
(2009, 2, 3, 19, 55, 32, 1, 34, 0)
</code></pre>
<p>but how can I subtract one from the other without going though each item in the list and doing it manually?</p>
| 2
|
2009-02-03T20:12:06Z
| 508,764
|
<pre><code>from datetime import datetime, timedelta
datetime.now()
datetime.datetime(2009, 2, 3, 15, 17, 35, 156000)
datetime.now() - datetime(1984, 6, 29 )
datetime.timedelta(8985, 55091, 206000)
datetime.now() - datetime(1984, 6, 29 )
datetime.timedelta(8985, 55094, 198000) # my age...
</code></pre>
<p>timedelta(days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) </p>
| 2
|
2009-02-03T20:21:39Z
|
[
"python",
"datetime"
] |
Python time to age
| 508,727
|
<p>I'm trying to convert a date string into an age.</p>
<p>The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.</p>
<p>I have sucessfully converted the date using:</p>
<pre><code>>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, -1)
</code></pre>
<p>For some reason %z gives me an error for the +0200 but it doesn't matter that much.</p>
<p>I can get the current time using:</p>
<pre><code>>>> time.localtime()
(2009, 2, 3, 19, 55, 32, 1, 34, 0)
</code></pre>
<p>but how can I subtract one from the other without going though each item in the list and doing it manually?</p>
| 2
|
2009-02-03T20:12:06Z
| 508,797
|
<p>In Python, <code>datetime</code> objects natively support subtraction:</p>
<pre><code>from datetime import datetime
age = datetime.now() - datetime.strptime(...)
print age.days
</code></pre>
<p>The result is a <a href="http://docs.python.org/library/datetime.html#datetime.timedelta" rel="nofollow">timedelta</a> object.</p>
| 5
|
2009-02-03T20:30:17Z
|
[
"python",
"datetime"
] |
Python time to age
| 508,727
|
<p>I'm trying to convert a date string into an age.</p>
<p>The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.</p>
<p>I have sucessfully converted the date using:</p>
<pre><code>>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, -1)
</code></pre>
<p>For some reason %z gives me an error for the +0200 but it doesn't matter that much.</p>
<p>I can get the current time using:</p>
<pre><code>>>> time.localtime()
(2009, 2, 3, 19, 55, 32, 1, 34, 0)
</code></pre>
<p>but how can I subtract one from the other without going though each item in the list and doing it manually?</p>
| 2
|
2009-02-03T20:12:06Z
| 508,881
|
<p>Thanks guys, I ended up with the following:</p>
<pre><code>def getAge( d ):
""" Calculate age from date """
delta = datetime.now() - datetime.strptime(d, "%a, %d %b %Y %H:%M:%S +0200")
return delta.days + delta.seconds / 86400.0 # divide secs into days
</code></pre>
<p>Giving:</p>
<pre><code>>>> getAge("Mon, 17 Nov 2008 01:45:32 +0200")
78.801319444444445
</code></pre>
| 0
|
2009-02-03T20:59:42Z
|
[
"python",
"datetime"
] |
Python time to age
| 508,727
|
<p>I'm trying to convert a date string into an age.</p>
<p>The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.</p>
<p>I have sucessfully converted the date using:</p>
<pre><code>>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, -1)
</code></pre>
<p>For some reason %z gives me an error for the +0200 but it doesn't matter that much.</p>
<p>I can get the current time using:</p>
<pre><code>>>> time.localtime()
(2009, 2, 3, 19, 55, 32, 1, 34, 0)
</code></pre>
<p>but how can I subtract one from the other without going though each item in the list and doing it manually?</p>
| 2
|
2009-02-03T20:12:06Z
| 510,638
|
<p>If you don't want to use datetime (e.g. if your Python is old and you don't have the module), you can just use the time module.</p>
<pre><code>s = "Mon, 17 Nov 2008 01:45:32 +0200"
import time
import email.utils # Using email.utils means we can handle the timezone.
t = email.utils.parsedate_tz(s) # Gets the time.mktime 9-tuple, plus tz
d = time.time() - time.mktime(t[:9]) + t[9] # Gives the difference in seconds.
</code></pre>
| 1
|
2009-02-04T09:24:29Z
|
[
"python",
"datetime"
] |
Python time to age
| 508,727
|
<p>I'm trying to convert a date string into an age.</p>
<p>The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is.</p>
<p>I have sucessfully converted the date using:</p>
<pre><code>>>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200")
(2008, 11, 17, 1, 45, 32, 0, 322, -1)
</code></pre>
<p>For some reason %z gives me an error for the +0200 but it doesn't matter that much.</p>
<p>I can get the current time using:</p>
<pre><code>>>> time.localtime()
(2009, 2, 3, 19, 55, 32, 1, 34, 0)
</code></pre>
<p>but how can I subtract one from the other without going though each item in the list and doing it manually?</p>
| 2
|
2009-02-03T20:12:06Z
| 25,426,694
|
<p>Since Python 3.2, <code>datetime.strptime()</code> returns an aware datetime object if <code>%z</code> directive is provided:</p>
<pre><code>#!/usr/bin/env python3
from datetime import datetime, timezone, timedelta
s = "Mon, 17 Nov 2008 01:45:32 +0200"
birthday = datetime.strptime(s, '%a, %d %b %Y %H:%M:%S %z')
age = (datetime.now(timezone.utc) - birthday) / timedelta(1) # age in days
print("%.0f" % age)
</code></pre>
<p>On older Python versions the correct version of <a href="http://stackoverflow.com/a/510638/4279">@Tony Meyer's answer</a> could be used:</p>
<pre><code>#!/usr/bin/env python
import time
from email.utils import parsedate_tz, mktime_tz
s = "Mon, 17 Nov 2008 01:45:32 +0200"
ts = mktime_tz(parsedate_tz(s)) # seconds since Epoch
age = (time.time() - ts) / 86400 # age in days
print("%.0f" % age)
</code></pre>
<p>Both code examples produce the same result.</p>
| 0
|
2014-08-21T12:44:32Z
|
[
"python",
"datetime"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 508,839
|
<p>You seem to assume its the library. Its open source, so it would be worth checking the code to see if it is.</p>
<p>You mention that you're sending a lot of data over HTTP. The inefficieny might be because of the library, but HTTP isn't the most efficient protocol for sending large amounts of data. Then again, it could be the simple use of the library (are you sending a big string or list, or using a stream or generators?).</p>
| 1
|
2009-02-03T20:44:32Z
|
[
"python",
"http",
"curl",
"twisted"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 508,840
|
<p>Often when I've had performance problems with httplib, the problem hasn't been with the httplib itself, but with how I'm using it. Here are a few common pitfalls:</p>
<p>(1) Don't make a new TCP connection for every web request. If you are making lots of request to the same server, instead of this pattern: </p>
<pre>
conn = httplib.HTTPConnection("www.somewhere.com")
conn.request("GET", '/foo')
conn = httplib.HTTPConnection("www.somewhere.com")
conn.request("GET", '/bar')
conn = httplib.HTTPConnection("www.somewhere.com")
conn.request("GET", '/baz')
</pre>
<p>Do this instead:</p>
<pre>
conn = httplib.HTTPConnection("www.somewhere.com")
conn.request("GET", '/foo')
conn.request("GET", '/bar')
conn.request("GET", '/baz')
</pre>
<p>(2) Don't serialize your requests. You can use threads or asynccore or whatever you like, but if you are making multiple requests from different servers, you can improve performance by running them in parallel.</p>
| 21
|
2009-02-03T20:44:37Z
|
[
"python",
"http",
"curl",
"twisted"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 508,858
|
<blockquote>
<p>Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else?</p>
</blockquote>
<p>Do you <em>suspect</em> it or are you <em>sure</em> that that it's <code>httplib</code>? Profile before you do anything to improve the performance of your app.</p>
<p>I've found my own intuition on where time is spent is often pretty bad (given that there isn't some code kernel executed millions of times). It's really disappointing to implement something to improve performance then pull up the app and see that it made no difference.</p>
<p>If you're not profiling, you're shooting in the dark!</p>
| 18
|
2009-02-03T20:53:12Z
|
[
"python",
"http",
"curl",
"twisted"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 509,006
|
<p>httplib2 is another option:
<a href="http://code.google.com/p/httplib2/" rel="nofollow">http://code.google.com/p/httplib2/</a></p>
<p>I have never benchmarked or profiled it in comparison to httplib, but I would also be interested in any findings there.</p>
<hr>
<p>Dec. 2012 update:
I no longer use httplib2. now using <strong><a href="http://docs.python-requests.org" rel="nofollow">Requests</a></strong>: HTTP For Humans, for any http with Python.</p>
| 2
|
2009-02-03T21:38:43Z
|
[
"python",
"http",
"curl",
"twisted"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 509,486
|
<p>PyCurl is awesome, and extremely high performance.</p>
| 5
|
2009-02-03T23:36:07Z
|
[
"python",
"http",
"curl",
"twisted"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 510,084
|
<p>httplib2 is a very good option. Joe Gregorio has fixed many bugs of httplib.</p>
| 0
|
2009-02-04T04:37:50Z
|
[
"python",
"http",
"curl",
"twisted"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 515,335
|
<p>As others answered httplib2 is a good alternative because it handles headers properly and can cache responses, but I doubt this would help in POST performance.</p>
<p>An alternative that might actually give you a performance boost for POST, especially on Windows, is the <a href="http://twistedmatrix.com/trac/ticket/886" rel="nofollow">new HTTP 1.1 client in Twisted.web</a></p>
| 1
|
2009-02-05T10:33:18Z
|
[
"python",
"http",
"curl",
"twisted"
] |
A replacement for python's httplib?
| 508,817
|
<p>I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.</p>
<p>Could I improve performance by replacing httplib with something else? </p>
<p>I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. </p>
<p>PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code.</p>
<p>So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation.</p>
<p>UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following:</p>
<pre><code>conn = httplib.HTTPConnection(host, port)
conn.request("POST", url, params, headers)
compressedstream = StringIO.StringIO(conn.getresponse().read())
</code></pre>
<p>That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible.</p>
<p>UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.</p>
| 9
|
2009-02-03T20:36:21Z
| 6,769,260
|
<p>It works on my windows machine:
With Py 2.3 (without IPv6 support) this is only the IPv4 address,
but with Py 2.4-2.6 the order is (on my Win XP host) the IPv6 address
first, then the IPv4 address. Since the IPv6 address is checked first,
this gives a timeout and causes the slow connect() call. </p>
<p>I have only changed "localhost" to 127.0.0.1 and it started working 10 times faster (from 1087ms to 87ms).
Solution from <a href="http://www.velocityreviews.com/forums/t668272-problem-with-slow-httplib-connections-on-windows-and-maybe-otherplatforms.html" rel="nofollow">http://www.velocityreviews.com/forums/t668272-problem-with-slow-httplib-connections-on-windows-and-maybe-otherplatforms.html</a></p>
| 0
|
2011-07-20T22:21:18Z
|
[
"python",
"http",
"curl",
"twisted"
] |
How to overwrite some bytes in the middle of a file with Python?
| 508,983
|
<p>I'd like to be able to overwrite some bytes at a given offset in a file using Python.</p>
<p>My attempts have failed miserably and resulted in:</p>
<ul>
<li>overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+") </li>
<li>appending the bytes at the end of the file (file mode = "a" or "a+") </li>
</ul>
<p>Is it possible to achieve this with Python in a portable way? </p>
| 11
|
2009-02-03T21:31:53Z
| 509,010
|
<p>According to <a href="http://www.sthurlow.com/python/lesson10/" rel="nofollow">this python page</a> you can type file.seek to seek to a particualar offset. You can then write whatever you want.</p>
<p>To avoid truncating the file, you can open it with "a+" then seek to the right offset.</p>
| 3
|
2009-02-03T21:39:43Z
|
[
"python",
"file",
"patching"
] |
How to overwrite some bytes in the middle of a file with Python?
| 508,983
|
<p>I'd like to be able to overwrite some bytes at a given offset in a file using Python.</p>
<p>My attempts have failed miserably and resulted in:</p>
<ul>
<li>overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+") </li>
<li>appending the bytes at the end of the file (file mode = "a" or "a+") </li>
</ul>
<p>Is it possible to achieve this with Python in a portable way? </p>
| 11
|
2009-02-03T21:31:53Z
| 509,014
|
<p>Try this:</p>
<pre><code>fh = open("filename.ext", "r+b")
fh.seek(offset)
fh.write(bytes)
fh.close()
</code></pre>
| 18
|
2009-02-03T21:39:57Z
|
[
"python",
"file",
"patching"
] |
How to overwrite some bytes in the middle of a file with Python?
| 508,983
|
<p>I'd like to be able to overwrite some bytes at a given offset in a file using Python.</p>
<p>My attempts have failed miserably and resulted in:</p>
<ul>
<li>overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+") </li>
<li>appending the bytes at the end of the file (file mode = "a" or "a+") </li>
</ul>
<p>Is it possible to achieve this with Python in a portable way? </p>
| 11
|
2009-02-03T21:31:53Z
| 509,036
|
<p>Very inefficient, but I don't know any other way right now, that <strong>doesn't overwrite</strong> the bytes in the middle (as Ben Blanks one does):</p>
<pre><code>a=file('/tmp/test123','r+')
s=a.read()
a.seek(0)
a.write(s[:3]+'xxx'+s[3:])
a.close()
</code></pre>
<p>will write 'xxx' at offset 3: <code>123456789 --> 123xxx456789</code></p>
| 0
|
2009-02-03T21:44:25Z
|
[
"python",
"file",
"patching"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 509,295
|
<p>It's pretty simple really:</p>
<pre><code>a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
</code></pre>
<p>There is also the <code>step</code> value, which can be used with any of the above:</p>
<pre><code>a[start:end:step] # start through not past end, by step
</code></pre>
<p>The key point to remember is that the <code>:end</code> value represents the first value that is <em>not</em> in the selected slice. So, the difference beween <code>end</code> and <code>start</code> is the number of elements selected (if <code>step</code> is 1, the default).</p>
<p>The other feature is that <code>start</code> or <code>end</code> may be a <em>negative</em> number, which means it counts from the end of the array instead of the beginning. So:</p>
<pre><code>a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
</code></pre>
<p>Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for <code>a[:-2]</code> and <code>a</code> only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.</p>
| 1,891
|
2009-02-03T22:48:24Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 509,297
|
<p>The tutorial talks about it:</p>
<p><a href="http://docs.python.org/tutorial/introduction.html#strings">http://docs.python.org/tutorial/introduction.html#strings</a></p>
<p>(Scroll down a bit until you get to the part about slicing.) </p>
<p>The ASCII art diagram is helpful too for remembering how slices work:</p>
<pre><code> +---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
</code></pre>
<blockquote>
<p>"One way to remember how slices work
is to think of the indices as pointing
<em>between</em> characters, with the left edge of the first character numbered
0."</p>
</blockquote>
| 245
|
2009-02-03T22:49:04Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 509,377
|
<p>Enumerating the possibilities allowed by the grammar:</p>
<pre><code>>>> seq[:] # [seq[0], seq[1], ..., seq[-1] ]
>>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ]
>>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]]
>>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]]
>>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ]
>>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ]
>>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]]
>>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]]
</code></pre>
<p>Of course, if <code>(high-low)%stride != 0</code>, then the end point will be a little lower than <code>high-1</code>.</p>
<p>Extended slicing (with commas and ellipses) are mostly used only by special data structures (like Numpy); the basic sequences don't support them.</p>
<pre><code>>>> class slicee:
... def __getitem__(self, item):
... return `item`
...
>>> slicee()[0, 1:2, ::5, ...]
'(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)'
</code></pre>
| 180
|
2009-02-03T23:08:22Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 509,415
|
<p>And a couple of things that weren't immediately obvious to me when I first saw the slicing syntax:</p>
<pre><code>>>> x = [1,2,3,4,5,6]
>>> x[::-1]
[6,5,4,3,2,1]
</code></pre>
<p>Easy way to reverse sequences!</p>
<p>And if you wanted, for some reason, every second item in the reversed sequence:</p>
<pre><code>>>> x = [1,2,3,4,5,6]
>>> x[::-2]
[6,4,2]
</code></pre>
| 82
|
2009-02-03T23:15:02Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 522,212
|
<p>I use the "an index points between elements" method of thinking about it myself, but one way of describing it which sometimes helps others get it is this:</p>
<pre><code>mylist[X:Y]
</code></pre>
<p>X is the index of the first element you want.<br />
Y is the index of the first element you <em>don't</em> want.</p>
| 20
|
2009-02-06T21:16:28Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 567,094
|
<p>After using it a bit I realise that the simplest description is that it is exactly the same as the arguments in a for loop...</p>
<pre><code>(from:to:step)
</code></pre>
<p>any of them are optional</p>
<pre><code>(:to:step)
(from::step)
(from:to)
</code></pre>
<p>then the negative indexing just needs you to add the length of the string to the negative indices to understand it.</p>
<p>This works for me anyway...</p>
| 33
|
2009-02-19T20:52:44Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 4,729,334
|
<p>The answers above don't discuss slice assignment:</p>
<pre><code>>>> r=[1,2,3,4]
>>> r[1:1]
[]
>>> r[1:1]=[9,8]
>>> r
[1, 9, 8, 2, 3, 4]
>>> r[1:1]=['blah']
>>> r
[1, 'blah', 9, 8, 2, 3, 4]
</code></pre>
<p>This may also clarify the difference between slicing and indexing.</p>
| 119
|
2011-01-18T21:37:57Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 7,315,935
|
<p>Found this great table at <a href="http://wiki.python.org/moin/MovingToPythonFromOtherLanguages">http://wiki.python.org/moin/MovingToPythonFromOtherLanguages</a></p>
<pre><code>Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4]
+---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3]
| a | b | c | d | e | f | a[5]==5 a[1:2]==[1]
+---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4]
Slice from front: : 1 2 3 4 5 : a[-2]==4
Slice from rear: : -5 -4 -3 -2 -1 :
b=a[:]
b==[0,1,2,3,4,5] (shallow copy of a)</code></pre>
| 64
|
2011-09-06T06:50:08Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 9,827,284
|
<p>This is just for some extra info...
Consider the list below </p>
<pre><code>>>> l=[12,23,345,456,67,7,945,467]
</code></pre>
<p>Few other tricks for reversing the list:</p>
<pre><code>>>> l[len(l):-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]
>>> l[:-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]
>>> l[len(l)::-1]
[467, 945, 7, 67, 456, 345, 23, 12]
>>> l[::-1]
[467, 945, 7, 67, 456, 345, 23, 12]
>>> l[-1:-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]
</code></pre>
<p>See abc's answer above</p>
| 16
|
2012-03-22T17:20:59Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 9,923,354
|
<p>I find it easier to remember how it's works, then I can figure out any specific start/stop/step combination.</p>
<p>It's instructive to understand <code>range()</code> first:</p>
<pre><code>def range(start=0, stop, step=1): # illegal syntax, but that's the effect
i = start
while (i < stop if step > 0 else i > stop):
yield i
i += step
</code></pre>
<p>Begin from <code>start</code>, increment by <code>step</code>, do not reach <code>stop</code>. Very simple.</p>
<p>The thing to remember about negative step is that <code>stop</code> is always the excluded end, whether it's higher or lower. If you want same slice in opposite order, it's much cleaner to do the reversal separately: e.g. <code>'abcde'[1:-2][::-1]</code> slices off one char from left, two from right, then reverses. (See also <a href="http://www.python.org/dev/peps/pep-0322/"><code>reversed()</code></a>.)</p>
<p>Sequence slicing is same, except it first normalizes negative indexes, and can never go outside the sequence:</p>
<pre><code>def this_is_how_slicing_works(seq, start=None, stop=None, step=1):
if start is None:
start = (0 if step > 0 else len(seq)-1)
elif start < 0:
start += len(seq)
if stop is None:
stop = (len(seq) if step > 0 else -1) # really -1, not last element
elif stop < 0:
stop += len(seq)
for i in range(start, stop, step):
if 0 <= i < len(seq):
yield seq[i]
</code></pre>
<p>Don't worry about the <code>is None</code> details - just remember that omitting <code>start</code> and/or <code>stop</code> always does the right thing to give you the whole sequence.</p>
<p>Normalizing negative indexes first allows start and/or stop to be counted from the end independently: <code>'abcde'[1:-2] == 'abcde'[1:3] == 'bc'</code> despite <code>range(1,-2) == []</code>.
The normalization is sometimes thought of as "modulo the length" but note it adds the length just once: e.g. <code>'abcde'[-53:42]</code> is just the whole string.</p>
| 21
|
2012-03-29T10:15:12Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 13,005,464
|
<p>In python 2.7</p>
<p>Slicing in python</p>
<pre><code>[a:b:c]
len = length of string, tuple or list
c -- default is +1. sign of c indicates forward or backward, absolute value of c indicates steps. Default is forward with step size 1. Positive means forward, negative means backward.
a -- when c is positive or blank, default is 0. when c is negative, default is -1.
b -- when c is positive or blank, default is len. when c is negative, default is -(len+1).
</code></pre>
<p>Understanding index assignment is very important.</p>
<pre><code>In forward direction, starts at 0 and ends at len-1
In backward direction, starts at -1 and ends at -len
</code></pre>
<p>when you say [a:b:c] you are saying depending on sign of c (forward or backward), start at a and end at b ( excluding element at bth index). Use the indexing rule above and remember you will only find elements in this range </p>
<pre><code>-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1
</code></pre>
<p>but this range continues in both directions infinitely</p>
<pre><code>...,-len -2 ,-len-1,-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1, len, len +1, len+2 , ....
</code></pre>
<p>e.g. </p>
<pre><code> 0 1 2 3 4 5 6 7 8 9 10 11
a s t r i n g
-9 -8 -7 -6 -5 -4 -3 -2 -1
</code></pre>
<p>if your choice of a , b and c allows overlap with the range above as you traverse using rules for a,b,c above you will either get a list with elements (touched during traversal) or you will get an empty list.</p>
<p>One last thing: if a and b are equal , then also you get an empty list</p>
<pre><code>>>> l1
[2, 3, 4]
>>> l1[:]
[2, 3, 4]
>>> l1[::-1] # a default is -1 , b default is -(len+1)
[4, 3, 2]
>>> l1[:-4:-1] # a default is -1
[4, 3, 2]
>>> l1[:-3:-1] # a default is -1
[4, 3]
>>> l1[::] # c default is +1, so a default is 0, b default is len
[2, 3, 4]
>>> l1[::-1] # c is -1 , so a default is -1 and b default is -(len+1)
[4, 3, 2]
>>> l1[-100:-200:-1] # interesting
[]
>>> l1[-1:-200:-1] # interesting
[4, 3, 2]
>>> l1[-1:-1:1]
[]
>>> l1[-1:5:1] # interesting
[4]
>>> l1[1:-7:1]
[]
>>> l1[1:-7:-1] # interesting
[3, 2]
</code></pre>
| 51
|
2012-10-22T05:33:39Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 14,682,039
|
<pre><code>index:
------------>
0 1 2 3 4
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
0 -4 -3 -2 -1
<------------
slice:
<---------------|
|--------------->
: 1 2 3 4 :
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
: -4 -3 -2 -1 :
|--------------->
<---------------|
</code></pre>
<p>hope this will help you to model the list in Python</p>
<p>reference:<a href="http://wiki.python.org/moin/MovingToPythonFromOtherLanguages">http://wiki.python.org/moin/MovingToPythonFromOtherLanguages</a></p>
| 13
|
2013-02-04T07:20:03Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 15,824,717
|
<p>You can also use slice assignment to remove one or more elements from a list:</p>
<pre><code>r = [1, 'blah', 9, 8, 2, 3, 4]
>>> r[1:4] = []
>>> r
[1, 2, 3, 4]
</code></pre>
| 16
|
2013-04-05T01:59:41Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 16,267,103
|
<p>Python slicing notation:</p>
<pre><code>a[start:end:step]
</code></pre>
<ul>
<li>For <code>start</code> and <code>end</code>, negative values are interpreted as being relative to the end of the sequence.</li>
<li>Positive indices for <code>end</code> indicate the position <em>after</em> the last element to be included.</li>
<li>Blank values are defaulted as follows: <code>[+0:-0:1]</code>.</li>
<li>Using a negative step reverses the interpretation of <code>start</code> and <code>end</code></li>
</ul>
<p>The notation extends to (numpy) matrices and multidimensional arrays. For example, to slice entire columns you can use:</p>
<pre><code>m[::,0:2:] ## slice the first two columns
</code></pre>
<p>Slices hold references, not copies, of the array elements. If you want to make a separate copy an array, you can use <a href="http://stackoverflow.com/questions/6532881/how-to-make-a-copy-of-a-2d-array-in-python"><code>deepcopy()</code></a>.</p>
| 19
|
2013-04-28T19:49:39Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 20,136,130
|
<p>To get a certain piece of an iterable (like a list), here is an example:</p>
<pre><code>variable[number1:number2]
</code></pre>
<p>In this example, a positive number for number 1 is how many components you take off the front. A negative number is the exact opposite, how many you keep from the end. A positive number for number 2 indicates how many components you intend to keep from the beginning, and a negative is how many you intend to take off from the end. This is somewhat counter intuitive, but you are correct in supposing that list slicing is extremely useful.</p>
| 4
|
2013-11-22T02:53:27Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 20,443,928
|
<p>As a general rule, writing code with a lot of hardcoded index values leads to a readability
and maintenance mess. For example, if you come back to the code a year later, youâll
look at it and wonder what you were thinking when you wrote it. The solution shown
is simply a way of more clearly stating what your code is actually doing.
In general, the built-in slice() creates a slice object that can be used anywhere a slice
is allowed. For example:</p>
<pre><code>>>> items = [0, 1, 2, 3, 4, 5, 6]
>>> a = slice(2, 4)
>>> items[2:4]
[2, 3]
>>> items[a]
[2, 3]
>>> items[a] = [10,11]
>>> items
[0, 1, 10, 11, 4, 5, 6]
>>> del items[a]
>>> items
[0, 1, 4, 5, 6]
</code></pre>
<p>If you have a slice instance s, you can get more information about it by looking at its
s.start, s.stop, and s.step attributes, respectively. For example:</p>
<blockquote>
<pre><code>>>> a = slice(10, 50, 2)
>>> a.start
10
>>> a.stop
50
>>> a.step
2
>>>
</code></pre>
</blockquote>
| 15
|
2013-12-07T16:52:45Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 24,546,555
|
<p>If you prefer a video and voiceover instead, the guy in <a href="http://youtu.be/tKTZoB2Vjuk?t=42m34s" rel="nofollow">the Google Python course (click here)</a> talks about slice syntax and some of its practical uses, starting from the time index 42:34; the link will take you to that point.</p>
| 6
|
2014-07-03T06:36:03Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 24,713,353
|
<blockquote>
<h1>Explain Python's slice notation</h1>
</blockquote>
<p>In short, the colons (<code>:</code>) in subscript notation (<code>subscriptable[subscriptarg]</code>) make slice notation - which has the optional arguments, <code>start</code>, <code>stop</code>, <code>step</code>:</p>
<pre><code>sliceable[start:stop:step]
</code></pre>
<p>Python slicing is a computationally fast way to methodically access parts of your data. In my opinion, to be even an intermediate Python programmer, it's one aspect of the language that it is necessary to be familiar with.</p>
<h1>Important Definitions</h1>
<p>To begin with, let's define a few terms:</p>
<blockquote>
<p><strong>start:</strong> the beginning index of the slice, it will include the element at this index unless it is the same as <em>stop</em>, defaults to 0, i.e. the first index. If it's negative, it means to start <code>n</code> items from the end.</p>
<p><strong>stop:</strong> the ending index of the slice, it does <em>not</em> include the element at this index, defaults to length of the sequence being sliced, that is, up to and including the end.</p>
<p><strong>step:</strong> the amount by which the index increases, defaults to 1. If it's negative, you're slicing over the iterable in reverse.</p>
</blockquote>
<h1>How Indexing Works</h1>
<p>You can make any of these positive or negative numbers. The meaning of the positive numbers is straightforward, but for negative numbers, just like indexes in Python, you count backwards from the end for the <em>start</em> and <em>stop</em>, and for the <em>step</em>, you simply decrement your index. This example is <a href="https://docs.python.org/2/tutorial/introduction.html" rel="nofollow">from the documentation's tutorial</a>, but I've modified it slightly to indicate which item in a sequence each index references:</p>
<pre><code> +---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
</code></pre>
<h1>How Slicing Works</h1>
<p>To use slice notation with a sequence that supports it, you must include at least one colon in the square brackets that follow the sequence (which actually <a href="https://docs.python.org/2/reference/datamodel.html#object.__getitem__" rel="nofollow">implement the <code>__getitem__</code> method of the sequence, according to the Python data model</a>.)</p>
<p>Slice notation works like this:</p>
<pre><code>sequence[start:stop:step]
</code></pre>
<p>And recall that there are defaults for <em>start</em>, <em>stop</em>, and <em>step</em>, so to access the defaults, simply leave out the argument.</p>
<p>Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:</p>
<pre><code>my_list[-9:]
</code></pre>
<p>When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")</p>
<h1>Explanation:</h1>
<p>The full notation is </p>
<pre><code>my_list[-9:None:None]
</code></pre>
<p>and to substitute the defaults (actually when <code>step</code> is negative, <code>stop</code>'s default is <code>-len(my_list) - 1</code>), so <code>None</code> for stop really just means it goes to whichever end step takes it to):</p>
<pre><code>my_list[-9:len(my_list):1]
</code></pre>
<p>The <strong>colon</strong>, <code>:</code>, is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of making a shallow copy of lists in Python 2 is</p>
<pre><code>list_copy = sequence[:]
</code></pre>
<p>And clearing them is with:</p>
<pre><code>del my_list[:]
</code></pre>
<p>(Python 3 gets a <code>list.copy</code> and <code>list.clear</code> method.)</p>
<h1>Give your slices a descriptive name!</h1>
<p>You may find it useful to separate forming the slice from passing it to the <code>list.__getitem__</code> method (<a href="https://docs.python.org/2/reference/datamodel.html#object.__getitem__" rel="nofollow">that's what the square brackets do</a>). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.</p>
<p>However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:</p>
<pre><code>last_nine_slice = slice(-9, None)
</code></pre>
<p>The second argument, <code>None</code>, is required, so that the first argument is interpreted as the <code>start</code> argument <a href="https://docs.python.org/2/library/functions.html#slice" rel="nofollow">otherwise it would be the <code>stop</code> argument</a>. </p>
<p>You can then pass the slice object to your sequence:</p>
<pre><code>>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]
</code></pre>
<h1>Memory Considerations:</h1>
<p>Since slices of Python lists create new objects in memory, another important function to be aware of is <code>itertools.islice</code>. Typically you'll want to iterate over a slice, not just have it created statically in memory. <code>islice</code> is perfect for this. A caveat, it doesn't support negative arguments to <code>start</code>, <code>stop</code>, or <code>step</code>, so if that's an issue you may need to calculate indices or reverse the iterable in advance.</p>
<pre><code>>>> length = 100
>>> last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1)
>>> list_last_nine = list(last_nine)
>>> list_last_nine
[91, 92, 93, 94, 95, 96, 97, 98, 99]
</code></pre>
<p>The fact that list slices make a copy is a feature of lists themselves. If you're slicing advanced objects like a Pandas DataFrame, it may return a view on the original, and not a copy. </p>
| 62
|
2014-07-12T13:19:03Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 26,442,691
|
<pre><code>#!/usr/bin/env python
def slicegraphical(s, lista):
if len(s) > 9:
print """Enter a string of maximum 9 characters,
so the printig would looki nice"""
return 0;
# print " ",
print ' '+'+---' * len(s) +'+'
print ' ',
for letter in s:
print '| {}'.format(letter),
print '|'
print " ",; print '+---' * len(s) +'+'
print " ",
for letter in range(len(s) +1):
print '{} '.format(letter),
print ""
for letter in range(-1*(len(s)), 0):
print ' {}'.format(letter),
print ''
print ''
for triada in lista:
if len(triada) == 3:
if triada[0]==None and triada[1] == None and triada[2] == None:
# 000
print s+'[ : : ]' +' = ', s[triada[0]:triada[1]:triada[2]]
elif triada[0] == None and triada[1] == None and triada[2] != None:
# 001
print s+'[ : :{0:2d} ]'.format(triada[2], '','') +' = ', s[triada[0]:triada[1]:triada[2]]
elif triada[0] == None and triada[1] != None and triada[2] == None:
# 010
print s+'[ :{0:2d} : ]'.format(triada[1]) +' = ', s[triada[0]:triada[1]:triada[2]]
elif triada[0] == None and triada[1] != None and triada[2] != None:
# 011
print s+'[ :{0:2d} :{1:2d} ]'.format(triada[1], triada[2]) +' = ', s[triada[0]:triada[1]:triada[2]]
elif triada[0] != None and triada[1] == None and triada[2] == None:
# 100
print s+'[{0:2d} : : ]'.format(triada[0]) +' = ', s[triada[0]:triada[1]:triada[2]]
elif triada[0] != None and triada[1] == None and triada[2] != None:
# 101
print s+'[{0:2d} : :{1:2d} ]'.format(triada[0], triada[2]) +' = ', s[triada[0]:triada[1]:triada[2]]
elif triada[0] != None and triada[1] != None and triada[2] == None:
# 110
print s+'[{0:2d} :{1:2d} : ]'.format(triada[0], triada[1]) +' = ', s[triada[0]:triada[1]:triada[2]]
elif triada[0] != None and triada[1] != None and triada[2] != None:
# 111
print s+'[{0:2d} :{1:2d} :{2:2d} ]'.format(triada[0], triada[1], triada[2]) +' = ', s[triada[0]:triada[1]:triada[2]]
elif len(triada) == 2:
if triada[0] == None and triada[1] == None:
# 00
print s+'[ : ] ' + ' = ', s[triada[0]:triada[1]]
elif triada[0] == None and triada[1] != None:
# 01
print s+'[ :{0:2d} ] '.format(triada[1]) + ' = ', s[triada[0]:triada[1]]
elif triada[0] != None and triada[1] == None:
# 10
print s+'[{0:2d} : ] '.format(triada[0]) + ' = ', s[triada[0]:triada[1]]
elif triada[0] != None and triada[1] != None:
# 11
print s+'[{0:2d} :{1:2d} ] '.format(triada[0],triada[1]) + ' = ', s[triada[0]:triada[1]]
elif len(triada) == 1:
print s+'[{0:2d} ] '.format(triada[0]) + ' = ', s[triada[0]]
if __name__ == '__main__':
# Change "s" to what ever string you like, make it 9 characters for
# better representation.
s = 'COMPUTERS'
# add to this list different lists to experement with indexes
# to represent ex. s[::], use s[None, None,None], otherwise you get an error
# for s[2:] use s[2:None]
lista = [[4,7],[2,5,2],[-5,1,-1],[4],[-4,-6,-1], [2,-3,1],[2,-3,-1], [None,None,-1],[-5,None],[-5,0,-1],[-5,None,-1],[-1,1,-2]]
slicegraphical(s, lista)
</code></pre>
<p>You can run this script and experiment with it, below is some samples that I got from the script.</p>
<pre><code> +---+---+---+---+---+---+---+---+---+
| C | O | M | P | U | T | E | R | S |
+---+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8 9
-9 -8 -7 -6 -5 -4 -3 -2 -1
COMPUTERS[ 4 : 7 ] = UTE
COMPUTERS[ 2 : 5 : 2 ] = MU
COMPUTERS[-5 : 1 :-1 ] = UPM
COMPUTERS[ 4 ] = U
COMPUTERS[-4 :-6 :-1 ] = TU
COMPUTERS[ 2 :-3 : 1 ] = MPUT
COMPUTERS[ 2 :-3 :-1 ] =
COMPUTERS[ : :-1 ] = SRETUPMOC
COMPUTERS[-5 : ] = UTERS
COMPUTERS[-5 : 0 :-1 ] = UPMO
COMPUTERS[-5 : :-1 ] = UPMOC
COMPUTERS[-1 : 1 :-2 ] = SEUM
[Finished in 0.9s]
</code></pre>
<p>When using a negative step, notice that the answer is shifted to the right by 1.</p>
| 3
|
2014-10-18T17:40:45Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 29,237,560
|
<p>This is how I teach slices to newbies:</p>
<p><strong>Understanding difference between indexing and slicing:</strong></p>
<p>Wiki Python has this amazing picture which clearly distinguishes indexing and slicing.</p>
<p><img src="http://i.stack.imgur.com/o99aU.png" alt="enter image description here"></p>
<p>It is a list with 6 elements in it. To understand slicing better, consider that list as a set of six boxes placed together. Each box has an alphabet in it.</p>
<p>Indexing is like dealing with the contents of box. You can check contents of any box. But You can't check contents of multiple boxes at once. You can even replace contents of the box. But You can't place 2 balls in 1 box or replace 2 balls at a time.</p>
<pre><code>In [122]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
In [123]: alpha
Out[123]: ['a', 'b', 'c', 'd', 'e', 'f']
In [124]: alpha[0]
Out[124]: 'a'
In [127]: alpha[0] = 'A'
In [128]: alpha
Out[128]: ['A', 'b', 'c', 'd', 'e', 'f']
In [129]: alpha[0,1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-129-c7eb16585371> in <module>()
----> 1 alpha[0,1]
TypeError: list indices must be integers, not tuple
</code></pre>
<p>Slicing is like dealing with boxes itself. You can pickup first box and place it on another table. To pickup the box all You need to know is the position of beginning & ending of the box.</p>
<p>You can even pickup first 3 boxes or last 2 boxes or all boxes between 1 & 4. So, You can pick any set of boxes if You know beginning & ending. This positions are called start & stop positions.</p>
<p>The interesting thing is that You can replace multiple boxes at once. Also You can place multiple boxes where ever You like.</p>
<pre><code>In [130]: alpha[0:1]
Out[130]: ['A']
In [131]: alpha[0:1] = 'a'
In [132]: alpha
Out[132]: ['a', 'b', 'c', 'd', 'e', 'f']
In [133]: alpha[0:2] = ['A', 'B']
In [134]: alpha
Out[134]: ['A', 'B', 'c', 'd', 'e', 'f']
In [135]: alpha[2:2] = ['x', 'xx']
In [136]: alpha
Out[136]: ['A', 'B', 'x', 'xx', 'c', 'd', 'e', 'f']
</code></pre>
<p><strong>Slicing With Step:</strong></p>
<p>Till now You have picked boxes continuously. But some times You need to pickup discretely. For example You can pickup every second box. You can even pickup every third box from the end. This value is called step size. This represents the gap between Your successive pickups. The step size should be positive if You are picking boxes from the beginning to end and vice versa.</p>
<pre><code>In [137]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
In [142]: alpha[1:5:2]
Out[142]: ['b', 'd']
In [143]: alpha[-1:-5:-2]
Out[143]: ['f', 'd']
In [144]: alpha[1:5:-2]
Out[144]: []
In [145]: alpha[-1:-5:2]
Out[145]: []
</code></pre>
<p><strong>How Python Figures Out Missing Parameters:</strong></p>
<p>When slicing if You leave out any parameter, Python tries to figure it out automatically.</p>
<p>If You check source code of CPython, You will find a function called PySlice_GetIndicesEx which figures out indices to a slice for any given parameters. Here is the logical equivalent code in Python.</p>
<p>This function takes a Python object & optional parameters for slicing and returns start, stop, step & slice length for the requested slice.</p>
<pre><code>def py_slice_get_indices_ex(obj, start=None, stop=None, step=None):
length = len(obj)
if step is None:
step = 1
if step == 0:
raise Exception("Step cannot be zero.")
if start is None:
start = 0 if step > 0 else length - 1
else:
if start < 0:
start += length
if start < 0:
start = 0 if step > 0 else -1
if start >= length:
start = length if step > 0 else length - 1
if stop is None:
stop = length if step > 0 else -1
else:
if stop < 0:
stop += length
if stop < 0:
stop = 0 if step > 0 else -1
if stop >= length:
stop = length if step > 0 else length - 1
if (step < 0 and stop >= start) or (step > 0 and start >= stop):
slice_length = 0
elif step < 0:
slice_length = (stop - start + 1)/(step) + 1
else:
slice_length = (stop - start - 1)/(step) + 1
return (start, stop, step, slice_length)
</code></pre>
<p>This is the intelligence that is present behind slices. Since Python has inbuilt function called slice, You can pass some parameters & check how smartly it calculates missing parameters.</p>
<pre><code>In [21]: alpha = ['a', 'b', 'c', 'd', 'e', 'f']
In [22]: s = slice(None, None, None)
In [23]: s
Out[23]: slice(None, None, None)
In [24]: s.indices(len(alpha))
Out[24]: (0, 6, 1)
In [25]: range(*s.indices(len(alpha)))
Out[25]: [0, 1, 2, 3, 4, 5]
In [26]: s = slice(None, None, -1)
In [27]: range(*s.indices(len(alpha)))
Out[27]: [5, 4, 3, 2, 1, 0]
In [28]: s = slice(None, 3, -1)
In [29]: range(*s.indices(len(alpha)))
Out[29]: [5, 4]
</code></pre>
<p><strong>Note:</strong> This post is originally written in my blog <a href="http://www.avilpage.com/2015/03/a-slice-of-python-intelligence-behind.html">http://www.avilpage.com/2015/03/a-slice-of-python-intelligence-behind.html</a></p>
| 11
|
2015-03-24T16:08:36Z
|
[
"python",
"list",
"slice"
] |
Explain Python's slice notation
| 509,211
|
<p>I need a good explanation (references are a plus) on Python's slice notation. </p>
<p>To me, this notation needs a bit of picking up. </p>
<p>It looks extremely powerful, but I haven't quite got my head around it.</p>
| 1,331
|
2009-02-03T22:31:02Z
| 37,455,246
|
<p>My brain seems happy to accept that <code>lst[start:end]</code> contains the <code>start</code>-th item. I might even say that it is a 'natural assumption'.</p>
<p>But occasionally a doubt creeps in and my brain asks for reassurance that it does not contain the <code>end</code>-th element.</p>
<p>In these moments I rely on this simple theorem:</p>
<pre><code>for any n, lst = lst[:n] + lst[n:]
</code></pre>
<p>This pretty property tells me that <code>lst[start:end]</code> does not contain the <code>end</code>-th item because it is in <code>lst[end:]</code>.</p>
<p>Note that this theorem is true for any <code>n</code> at all. For example, you can check that</p>
<pre><code>lst = range(10)
lst[:-42] + lst[-42:] == lst
</code></pre>
<p>returns <code>True</code>.</p>
| 0
|
2016-05-26T08:16:54Z
|
[
"python",
"list",
"slice"
] |
python reading lines w/o \n?
| 509,446
|
<p>Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform?</p>
<pre><code>while 1:
line = f.readline()
if line == "":
break
line = line[:-1]
print "\"" + line + "\""
</code></pre>
| 3
|
2009-02-03T23:23:57Z
| 509,482
|
<p>First of all, there is <a href="https://www.python.org/dev/peps/pep-0278/" rel="nofollow">universal newline support</a></p>
<p>Second: just use <code>line.strip()</code>. Use <code>line.rstrip('\r\n')</code>, if you want to preserve any whitespace at the beginning or end of the line.</p>
<p>Oh, and</p>
<pre><code>print '"%s"' % line
</code></pre>
<p>or at least</p>
<pre><code>print '"' + line + '"'
</code></pre>
<p>might look a bit nicer.</p>
<p>You can iterate over the lines in a file like this (this will not break on empty lines in the middle of the file like your code):</p>
<pre><code>for line in f:
print '"' + line.strip('\r\n') + '"'
</code></pre>
<p>If your input file is short enough, you can use the fact that <code>str.splitlines</code> throws away the line endings by default:</p>
<pre><code>with open('input.txt', 'rU') as f:
for line in f.read().splitlines():
print '"%s"' % line
</code></pre>
| 13
|
2009-02-03T23:34:39Z
|
[
"python",
"file",
"newline"
] |
python reading lines w/o \n?
| 509,446
|
<p>Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform?</p>
<pre><code>while 1:
line = f.readline()
if line == "":
break
line = line[:-1]
print "\"" + line + "\""
</code></pre>
| 3
|
2009-02-03T23:23:57Z
| 509,485
|
<p>Try this instead:</p>
<pre><code>line = line.rstrip('\r\n')
</code></pre>
| 4
|
2009-02-03T23:35:03Z
|
[
"python",
"file",
"newline"
] |
python reading lines w/o \n?
| 509,446
|
<p>Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform?</p>
<pre><code>while 1:
line = f.readline()
if line == "":
break
line = line[:-1]
print "\"" + line + "\""
</code></pre>
| 3
|
2009-02-03T23:23:57Z
| 509,827
|
<blockquote>
<p>line = line[:-1]</p>
</blockquote>
<p>A line can have no trailing newline, if it's the last line of a file.</p>
<p>As suggested above, try universal newlines with rstrip().</p>
| 0
|
2009-02-04T02:05:33Z
|
[
"python",
"file",
"newline"
] |
Python M2Crypto - generating a DSA key pair and separating public/private components
| 509,449
|
<p>Could anybody explain what is the cause of the following:</p>
<pre><code>>>> from M2Crypto import DSA, BIO
>>> dsa = DSA.gen_params(1024)
..+........+++++++++++++++++++++++++++++++++++++++++++++++++++*
............+.+.+..+.........+.............+.....................+.
...+.............+...........+.........................................
+.........+................+..........+......+..+.+...+..........+..+..
..+...+......+....+.............+.................+.......+.........+..
....+......+.+..+..........+........+.+...+..+...............+.........
..+.....+........+..........+++++++++++++++++++++++++++++++++++++++++++
++++++++*
>>> mem = BIO.MemoryBuffer()
>>> dsa.save_key_bio(mem, cipher=None)
1
>>> dsa.save_pub_key_bio(mem)
0
>>> print mem.getvalue()
-----BEGIN DSA PRIVATE KEY-----
MIIBIgIBAAKBgQDPGRFSTqqx8vet5kaW5m99A83REotTcX9HOv+zrqMxQpaTlinS
MDz49I4psDPJ+bWH7vySEdOYO2JGUj6kYZdz/ZwyNjphWNjQkaUrmfaVLzS3PHpW
aMrPEweLesf/PT4KXm2HaDbaW/g2Ds5h+Zlq9LDKcN2vfvyeiTCmf1esyQIVAO9I
ippU4PIdvJVO9HQRkqrD2bxPAoGBAIwVgM7dgNVwihJva6qeeh7ypy3ESNB9k8nY
fOnES+SqZGQbkPrJIusRCJNKERiMATJXNRMfBeWD8htNRezbgtr0OpuYSBurAQjp
hKKVI3DHSv7XT49BQ3tdJww8lQfkOhHOfFTG6U1dJhWdggp0WN3EjYlt77agRsjR
4t5sD1f3
-----END DSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
-----END PUBLIC KEY-----
>>>
</code></pre>
<p>clearly I'm missing something. M2Crypto nonexistant docs don't help.</p>
| 2
|
2009-02-03T23:25:04Z
| 509,633
|
<p>Call dsa.gen_key(), then save. You aren't actually generating the public key.</p>
<pre><code>>>> from M2Crypto import DSA, BIO
>>> dsa = DSA.gen_params(1024)
..+..etc
>>> mem = BIO.MemoryBuffer()
>>> dsa.gen_key()
>>> dsa.save_key_bio(mem, cipher=None)
1
>>> dsa.save_pub_key_bio(mem)
1
>>> print mem.getvalue()
-----BEGIN DSA PRIVATE KEY-----
MIIBuwIBAAKBgQDowiLFDXGwaWIOkZybeeqSXYZ8KCLmXg5XfnAtDBlVOokB91Rj
etc.
-----END DSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MIIBtzCCASsGByqGSM44BAEwggEeAoGBAOjCIsUNcbBpYg6RnJt56pJdhnwoIuZe
Dld+cC0MGVU6iQH3VGNEzKycBVQeVYke3itZwQALSlT2JfUsmOjeZYIkc9l2YYob
rixObXfQyc0AOBM/J53F0F6R8+xvEwN/Hmdd9SjjbdZi8gve+dr9UfnKHXi0KPUF
s2ougGhXeEjTAhUAiW5bMzG8nCVjXErgwaDEx+JEdtECgYACba2quw3xibhT3JNd
sDh0gIRpHPQgIgxgzGv6A09Vdb4VgtWf0MYAo6gAhxsZIWWKzQ94Oe1nf7OhC+B+
VjT+PW+ExSrbJVONTN5ycE64O7+2L+q/hZSjjkxXgfcApqeVtZp4wKqbS976Kpch
WgNl0zdkvV8JddRs0oKQ0Bl7dwOBhQACgYEAgkdF/+ncobVcYXfXHBUH3H5SLD3y
u2zUWGhXM4/MUTwPromDOQ8Zd0H7myYhmQvVUb+J9mJHMIn7Guf4JDH+8d6rBpzo
U5yEGqgsSqYqgtStzDvsKHfqw3mvjvsktm66N/vm36eai2I6J15QibdtP0lb1Um8
EeECDTxWUWT93rs=
-----END PUBLIC KEY-----
>>>
</code></pre>
| 7
|
2009-02-04T00:35:25Z
|
[
"python",
"cryptography",
"rsa",
"m2crypto"
] |
Python quotient vs remainder
| 509,710
|
<p>The python 2.6 docs state that <code>x % y</code> is defined as the remainder of x / y (<a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex" rel="nofollow">http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex</a>). I am not clear on what is really occurring though, as:</p>
<pre><code>for i in range(2, 11):
print 1.0 % i
</code></pre>
<p>prints "1.0" ten times, rather than "0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc). </p>
| -2
|
2009-02-04T01:05:46Z
| 509,721
|
<p>Modulo is performed in the integer context, not fractional (remainders are integers). Therefore:</p>
<pre><code>1 % 1 = 0 (1 times 1 plus 0)
1 % 2 = 1 (2 times 0 plus 1)
1 % 3 = 1 (3 times 0 plus 1)
6 % 3 = 0 (3 times 2 plus 0)
7 % 3 = 1 (3 times 2 plus 1)
8 % 3 = 2 (3 times 2 plus 2)
etc
</code></pre>
<blockquote>
<p><em>How do I get the actual remainder of x / y?</em></p>
</blockquote>
<p>By that I presume you mean doing a regular floating point division?</p>
<pre><code>for i in range(2, 11):
print 1.0 / i
</code></pre>
| 10
|
2009-02-04T01:10:12Z
|
[
"python",
"modulo"
] |
Python quotient vs remainder
| 509,710
|
<p>The python 2.6 docs state that <code>x % y</code> is defined as the remainder of x / y (<a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex" rel="nofollow">http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex</a>). I am not clear on what is really occurring though, as:</p>
<pre><code>for i in range(2, 11):
print 1.0 % i
</code></pre>
<p>prints "1.0" ten times, rather than "0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc). </p>
| -2
|
2009-02-04T01:05:46Z
| 509,724
|
<p>Wouldn't dividing 1 by an number larger than it result in 0 with remainder 1?</p>
<p>The number theorists in the crowd may correct me, but I think modulus/remainder is defined only on integers.</p>
| 3
|
2009-02-04T01:11:49Z
|
[
"python",
"modulo"
] |
Python quotient vs remainder
| 509,710
|
<p>The python 2.6 docs state that <code>x % y</code> is defined as the remainder of x / y (<a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex" rel="nofollow">http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex</a>). I am not clear on what is really occurring though, as:</p>
<pre><code>for i in range(2, 11):
print 1.0 % i
</code></pre>
<p>prints "1.0" ten times, rather than "0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc). </p>
| -2
|
2009-02-04T01:05:46Z
| 509,764
|
<p>I think you can get the result you want by doing something like this:</p>
<pre><code>for i in range(2, 11):
print 1.0*(1 % i) / i
</code></pre>
<p>This computes the (integer) remainder as explained by others. Then you divide by the denominator again, to produce the fractional part of the quotient.</p>
<p>Note that I multiply the result of the modulo operation by 1.0 to ensure that a floating point division operation is done (rather than integer division, which will result in 0).</p>
| 8
|
2009-02-04T01:37:06Z
|
[
"python",
"modulo"
] |
Python quotient vs remainder
| 509,710
|
<p>The python 2.6 docs state that <code>x % y</code> is defined as the remainder of x / y (<a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex" rel="nofollow">http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex</a>). I am not clear on what is really occurring though, as:</p>
<pre><code>for i in range(2, 11):
print 1.0 % i
</code></pre>
<p>prints "1.0" ten times, rather than "0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc). </p>
| -2
|
2009-02-04T01:05:46Z
| 509,836
|
<p>You've confused <a href="http://en.wikipedia.org/wiki/Division_(mathematics)" rel="nofollow">division</a> and <a href="http://en.wikipedia.org/wiki/Modular_arithmetic" rel="nofollow">modulus</a>.</p>
<p>"0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc)."</p>
<p>That's the result of <em>division</em>. </p>
<p>Not <em>modulus</em>.</p>
<p>Modulus (<code>%</code>) is the remainder left over after integer division.</p>
<p>Your sample values are simple division, which is the <code>/</code> operator. Not the <code>%</code> operator.</p>
| 4
|
2009-02-04T02:08:57Z
|
[
"python",
"modulo"
] |
Change directory to the directory of a Python script
| 509,742
|
<p>How do i change directory to the directory with my python script in? So far I figured out I should use <code>os.chdir</code> and <code>sys.argv[0]</code>. I'm sure there is a better way then to write my own function to parse argv[0].</p>
| 4
|
2009-02-04T01:24:43Z
| 509,754
|
<pre><code>os.chdir(os.path.dirname(__file__))
</code></pre>
| 14
|
2009-02-04T01:30:18Z
|
[
"python",
"scripting",
"directory"
] |
Change directory to the directory of a Python script
| 509,742
|
<p>How do i change directory to the directory with my python script in? So far I figured out I should use <code>os.chdir</code> and <code>sys.argv[0]</code>. I'm sure there is a better way then to write my own function to parse argv[0].</p>
| 4
|
2009-02-04T01:24:43Z
| 509,987
|
<p>Sometimes <code>__file__</code> is not defined, in this case you can try <code>sys.path[0]</code></p>
| 4
|
2009-02-04T03:47:25Z
|
[
"python",
"scripting",
"directory"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.