title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
How do I calculate the date six months from the current date using the datetime Python module?
| 546,321
|
<p>I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?</p>
<p>The reason I want to generate a date 6 months from the current date is to produce a Review Date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data. </p>
| 143
|
2009-02-13T15:16:25Z
| 35,474,438
|
<p>Here's a example which allows the user to decide how to return a date where the day is greater than the number of days in the month.</p>
<pre><code>def add_months(date, months, endOfMonthBehaviour='RoundUp'):
assert endOfMonthBehaviour in ['RoundDown', 'RoundIn', 'RoundOut', 'RoundUp'], \
'Unknown end of month behaviour'
year = date.year + (date.month + months - 1) / 12
month = (date.month + months - 1) % 12 + 1
day = date.day
last = monthrange(year, month)[1]
if day > last:
if endOfMonthBehaviour == 'RoundDown' or \
endOfMonthBehaviour == 'RoundOut' and months < 0 or \
endOfMonthBehaviour == 'RoundIn' and months > 0:
day = last
elif endOfMonthBehaviour == 'RoundUp' or \
endOfMonthBehaviour == 'RoundOut' and months > 0 or \
endOfMonthBehaviour == 'RoundIn' and months < 0:
# we don't need to worry about incrementing the year
# because there will never be a day in December > 31
month += 1
day = 1
return datetime.date(year, month, day)
>>> from calendar import monthrange
>>> import datetime
>>> add_months(datetime.datetime(2016, 1, 31), 1)
datetime.date(2016, 3, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2)
datetime.date(2015, 12, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2, 'RoundDown')
datetime.date(2015, 11, 30)
</code></pre>
| 0
|
2016-02-18T06:32:43Z
|
[
"python",
"datetime"
] |
How Do I Perform Introspection on an Object in Python 2.x?
| 546,337
|
<p>I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property. </p>
<p>Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.</p>
<p>I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun.</p>
| 22
|
2009-02-13T15:22:50Z
| 546,349
|
<p>Well ... Your first stop will be a simple dir(object). This will show you all the object's members, both fields and methods. Try it in an interactive Python shell, and play around a little.</p>
<p>For instance:</p>
<pre><code>> class Foo:
def __init__(self):
self.a = "bar"
self.b = 4711
> a=Foo()
> dir(a)
['__doc__', '__init__', '__module__', 'a', 'b']
</code></pre>
| 24
|
2009-02-13T15:27:23Z
|
[
"python",
"introspection",
"python-datamodel"
] |
How Do I Perform Introspection on an Object in Python 2.x?
| 546,337
|
<p>I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property. </p>
<p>Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.</p>
<p>I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun.</p>
| 22
|
2009-02-13T15:22:50Z
| 546,366
|
<p>How about something like:</p>
<pre><code>>>> o=object()
>>> [(a,type(o.__getattribute__(a))) for a in dir(o)]
[('__class__', <type 'type'>), ('__delattr__', <type 'method-wrapper'>),
('__doc__', <type 'str'>), ('__format__', <type 'builtin_function_or_method'>),
('__getattribute__', <type 'method-wrapper'>), ('__hash__', <type 'method-wrapper'>),
('__init__', <type 'method-wrapper'>),
('__new__', <type 'builtin_function_or_method'>),
('__reduce__', <type 'builtin_function_or_method'>),
('__reduce_ex__', <type 'builtin_function_or_method'>),
('__repr__', <type 'method-wrapper'>), ('__setattr__', <type 'method-wrapper'>),
('__sizeof__', <type 'builtin_function_or_method'>),
('__str__', <type 'method-wrapper'>),
('__subclasshook__', <type 'builtin_function_or_method'>)]
>>>
</code></pre>
<p>A more structured method will be to use the <a href="http://docs.python.org/library/inspect.html#module-inspect">inspect module</a>:</p>
<blockquote>
<p>The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.</p>
</blockquote>
| 8
|
2009-02-13T15:31:19Z
|
[
"python",
"introspection",
"python-datamodel"
] |
How Do I Perform Introspection on an Object in Python 2.x?
| 546,337
|
<p>I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property. </p>
<p>Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.</p>
<p>I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun.</p>
| 22
|
2009-02-13T15:22:50Z
| 546,372
|
<p>"<a href="https://web.archive.org/web/20120926041111/http://www.ibm.com/developerworks/library/l-pyint/index.html" rel="nofollow">Guide to Python introspection</a>" is a nice article to get you started.</p>
| 6
|
2009-02-13T15:33:17Z
|
[
"python",
"introspection",
"python-datamodel"
] |
How Do I Perform Introspection on an Object in Python 2.x?
| 546,337
|
<p>I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property. </p>
<p>Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.</p>
<p>I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun.</p>
| 22
|
2009-02-13T15:22:50Z
| 546,394
|
<p>You could have a look at the <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect module</a>. It provides a wide variety of tools for inspection of live objects as well as source code.</p>
| 2
|
2009-02-13T15:40:04Z
|
[
"python",
"introspection",
"python-datamodel"
] |
How Do I Perform Introspection on an Object in Python 2.x?
| 546,337
|
<p>I'm using Python 2.x and I have an object I'm summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of properties for that object and the type of each property. </p>
<p>Similarly, I'd like to get a list of methods for that object, as well, plus any other information I could find on that method, such as number of arguments and their respective types.</p>
<p>I have a feeling that I am simply missing the correct jargon in my Google searches. Not that I want to derail with specifics, but it's Active Directory, so that's always fun.</p>
| 22
|
2009-02-13T15:22:50Z
| 546,493
|
<p>If you're using win32com.client.Dispatch, inspecting the Python object might not be much help as it's a generic wrapper for IDispatch. </p>
<p>You can use <a href="http://starship.python.net/crew/mhammond/win32/" rel="nofollow">makepy</a> (which comes with <a href="http://www.activestate.com" rel="nofollow">Activestate Python</a>) to generate a Python wrapper from the type library. Then you can look at the code for the wrapper.</p>
| 0
|
2009-02-13T16:04:23Z
|
[
"python",
"introspection",
"python-datamodel"
] |
Generating lists/reports with in-line summaries in Django
| 546,385
|
<p>I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the way.</p>
<p>In my case, each Item is part of an Order. An Order can have several items, and I want to be able to display SUM based summaries after the end of each order.</p>
<p>So the report kind of looks like this:</p>
<pre><code>Order #25 <Qty> <Qty Sold> <Cost> <Cost Value>
Some Item 2 1 29.99 29.99
Another Item 4 0 10.00 40.00
<Subtotal Line> 6 1 39.99 69.99
Order #26 <Qty> <Qty Sold> <Cost> <Cost Value>
... Etc, you get the point
</code></pre>
<p>Now, I'm perfectly capable of displaying all the values and already have a report showing all the Items, but I have no idea how I can place Subtotals within the report like that without doing <strong>alot</strong> of queries. The Quantity, Qty Sold, and Cost fields are just part of the Item model, and Cost Value is just a simple model function.</p>
<p>Any help would be appreciated. Thanks in advance :-)</p>
| 5
|
2009-02-13T15:37:31Z
| 546,429
|
<p>You could compute the subtotals in Python in the Django view.</p>
<p>The sub-totals could be stored in instances of the Model object with an attribute indicating that it's a sub-total. To keep the report template simple you could insert the sub-total objects in the right places in the result list and use the sub-total attribute to render the sub-total lines differently.</p>
| 1
|
2009-02-13T15:48:08Z
|
[
"python",
"django",
"list",
"report"
] |
Generating lists/reports with in-line summaries in Django
| 546,385
|
<p>I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the way.</p>
<p>In my case, each Item is part of an Order. An Order can have several items, and I want to be able to display SUM based summaries after the end of each order.</p>
<p>So the report kind of looks like this:</p>
<pre><code>Order #25 <Qty> <Qty Sold> <Cost> <Cost Value>
Some Item 2 1 29.99 29.99
Another Item 4 0 10.00 40.00
<Subtotal Line> 6 1 39.99 69.99
Order #26 <Qty> <Qty Sold> <Cost> <Cost Value>
... Etc, you get the point
</code></pre>
<p>Now, I'm perfectly capable of displaying all the values and already have a report showing all the Items, but I have no idea how I can place Subtotals within the report like that without doing <strong>alot</strong> of queries. The Quantity, Qty Sold, and Cost fields are just part of the Item model, and Cost Value is just a simple model function.</p>
<p>Any help would be appreciated. Thanks in advance :-)</p>
| 5
|
2009-02-13T15:37:31Z
| 546,435
|
<p>Subtotals are <code>SELECT SUM(qty) GROUP BY order_number</code> things.</p>
<p>They are entirely separate from a query to get details.</p>
<p>The results of the two queries need to be interleaved. A good way to do this is to create each order as a tuple <code>( list_of_details, appropriate summary )</code>.</p>
<p>Then the display is easy</p>
<pre><code>{% for order in orderList %}
{% for line in order.0 %}
{{ line }}
{% endfor %}
{{ order.1 }}
{% endfor %}
</code></pre>
<p>The hard part is interleaving the two queries.</p>
<pre><code>details = Line.objects.all()
ddict = defaultdict( list )
for d in details:
ddict[d.order_number].append(d)
interleaved= []
subtotals = ... Django query to get subtotals ...
for s in subtotals:
interleaved.append( ( ddict[s.order], s.totals ) )
</code></pre>
<p>This <code>interleaved</code> object can be given to your template for rendering.</p>
| 3
|
2009-02-13T15:49:36Z
|
[
"python",
"django",
"list",
"report"
] |
Generating lists/reports with in-line summaries in Django
| 546,385
|
<p>I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the way.</p>
<p>In my case, each Item is part of an Order. An Order can have several items, and I want to be able to display SUM based summaries after the end of each order.</p>
<p>So the report kind of looks like this:</p>
<pre><code>Order #25 <Qty> <Qty Sold> <Cost> <Cost Value>
Some Item 2 1 29.99 29.99
Another Item 4 0 10.00 40.00
<Subtotal Line> 6 1 39.99 69.99
Order #26 <Qty> <Qty Sold> <Cost> <Cost Value>
... Etc, you get the point
</code></pre>
<p>Now, I'm perfectly capable of displaying all the values and already have a report showing all the Items, but I have no idea how I can place Subtotals within the report like that without doing <strong>alot</strong> of queries. The Quantity, Qty Sold, and Cost fields are just part of the Item model, and Cost Value is just a simple model function.</p>
<p>Any help would be appreciated. Thanks in advance :-)</p>
| 5
|
2009-02-13T15:37:31Z
| 546,650
|
<p>Assuming you're not going to use any order-specific fields, you could perform single DB query followed by some python calculations:</p>
<pre><code>from itertools import groupby
items = OrderItem.objects.select_related('order').order_by('order').all() # order_by is essential
items_by_order = dict(groupby(items, lambda x: x.order))
for order, items in items_by_order:
items_by_order[order]['subtotals'] = ... # calculate subtotals for all needed fields
</code></pre>
<p>This is more generic approach compared to using separeate SQL query for calculating subtotals which imposes liability of syncronising WHERE clauses on both queries. You can also use any agregate function, not only thoses available on DB side.</p>
| 1
|
2009-02-13T16:39:06Z
|
[
"python",
"django",
"list",
"report"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,495
|
<p>The biggest differences are that Python is duck typed, meaning that you won't need to plan out class hierarchies in as much detail as in Java, and has first class functions. The strategy pattern, for example, becomes much simpler and more obvious when you can just pass a function in, rather than having to make interfaces, etc. just to simulate higher order functions. More generally, Python has syntactic sugar for a lot of common design patterns, such as the iterator and the aforementioned strategy. It might be useful to understand these patterns (I've read Head First and found it pretty useful), but think about Pythonic ways to implement them rather than just doing things the same way you would in Java.</p>
| 36
|
2009-02-13T16:04:41Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,502
|
<p>It depends on the pattern. Some things are difficult to do in Python: Singleton is an example. You replace this pattern with another, such as, in the case of Singleton, Borg.<br>
It's not insane to use design patterns in Python-- the Iterator pattern, for instance, is integrated into the syntax. However, many things simply aren't done as OO- or pattern-heavy stuff. Python is made to be procedural or functional when it best suits the task, and OO too.<br>
Overall, I'd just say to use your best judgment. If it seems like using Design Pattern Alpha-Gamma is overkill and overcomplication, then it probably is. If it seems like the pattern is perfect for what you want, it probably is.</p>
| 4
|
2009-02-13T16:05:49Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,515
|
<p>Python has it's own design idioms. Some of the standard patterns apply, others don't. Something like strategy or factories have in-language support that make them transparent. </p>
<p>For instance, with first-class types anything can be a factory. There's no need for a factory type, you can use the class directly to construct any object you want.</p>
<p>Basically, Python has its own design idioms that are somewhat different largely because it's so dynamic and has incredible introspection capabilities.</p>
<p>Example:</p>
<pre><code>x = list
my_list = x(range(0,5)) #creates a new list by invoking list's constructor
</code></pre>
<p>By assigning the class-type to a callable object you can essentially remove any 'factory' types in your code. You are only left with callables that produce objects that should conform to some given conventions.</p>
<p>Furthermore, there are design patterns in Python that just can't be represented in other statically-typed languages efficiently. Metaclasses and function decorators are good examples of this.</p>
| 12
|
2009-02-13T16:07:07Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,516
|
<p>I'd say they apply to Python once you're already doing object-oriented programming with Python. Keep in mind that Python can do a lot more than OOP, and you should use common sense in choosing the appropriate paradigm for the job. If you decide that your program is best represented as a collection of objects, then sure, go ahead and use the design patterns, but don't be afraid to do something completely different if it's called for.</p>
| 1
|
2009-02-13T16:07:07Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,521
|
<p>The use of Java or C# is probably due to the mainstream popularity of the language. </p>
<p>But design principle and/or design patterns apply irrespective of the language you use. The implementation of the same design pattern in Python would obviously be different than in Java or C#. </p>
| 0
|
2009-02-13T16:07:58Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,569
|
<p>yes, of course they apply. But as noted above, many patterns are built into the language, or made irrelevant by higher level features of the language.</p>
| 1
|
2009-02-13T16:19:05Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,612
|
<p>Design patterns are little more than duct-tape to fix a languages deficiencies.</p>
| 4
|
2009-02-13T16:30:20Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 546,657
|
<p>On further thought, some patterns, such as Borg, may be more specific to Python (though similar things can be said about other patterns and languages).</p>
<p>The iterator pattern is also used in Python, albeit in a slightly different form.</p>
<p>Duncan Booth has written <a href="http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html" rel="nofollow">an article on patterns in python</a>.</p>
| 3
|
2009-02-13T16:40:54Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 549,327
|
<p><strong>Short answer:</strong> Yes; Python is an OO language.</p>
<p><strong>Slightly longer answer:</strong> Yes; you can <em>design</em> using OO principles and then <em>implement</em> in any language (even assembler).</p>
<blockquote>
<p>The benefit of using an OO language is that it incorporates support for many common OO concepts, so you don't risk unnecessary bugs having to simulate them by convention. Of course there will always be language-specific details with greater or lesser applicability; you asked about "design principles", which should be expressed above that level of detail.</p>
</blockquote>
<p><strong>Long, verbose, boring answer:</strong> (The development of programming languages <strong>isn't</strong> a simple linear progression, but let me oversimplify and ignore that fact to make an observation that spans about 40 years' of programming experience.)</p>
<blockquote>
<p>There's always going to be a role for language features vs. design principles and patterns. At every stage, attentive practitioners have noticed:</p>
<ul>
<li><p>"Here's a problem we keep solving by hand in our current language(s)."</p></li>
<li><p>"Here's a bug we keep writing in our current language(s)."</p></li>
<li><p>"Here are some good practices we keep observing in our best programs."</p></li>
</ul>
<p>And so the next generation of language(s) tend provide support for observed good behavior, tend to incorporate concepts so they don't have to be done by convention/agreement (or accidentally broken by the same), and enforce practices that prevent easily avoidable errors.</p>
<p>Regardless of how sophisticated, specialized, or generalized our tools, there are always programmers who "just turn the crank" and others who keep looking watching for how the "best and brightest" (<em>in the mind of the beholder</em>) use the tools. They then describe and promote those practices. Correctly defined (and whether called "style", "guidelines", "patterns", "principles", etc.), those practices end up forming "the next level" that we're always trying to reach, regardless of where we are currently standing.</p>
</blockquote>
| 4
|
2009-02-14T16:26:51Z
|
[
"python",
"oop"
] |
Do OO design principles apply to Python?
| 546,479
|
<p>It seems like many OO discussions use Java or C# as examples (e.g. Head First Design Patterns).</p>
<p>Do these patterns apply equally to Python? Or if I follow the design patterns, will I just end up writing Java in Python (which apparently is a very bad thing)?</p>
| 24
|
2009-02-13T16:00:06Z
| 2,106,180
|
<p>Yes, you can use plenty of design patterns in Python. A design pattern is just a repeatable implementation of a higher level task. The reason why Python & design patterns don't work the same as other languages is because Python includes most of the basic patterns built in. This means that patterns that emerge in Python are likely to be higher level design patterns instead of the menial tasks for which patterns are usually needed.</p>
| 0
|
2010-01-21T00:51:02Z
|
[
"python",
"oop"
] |
How can I split a file in python?
| 546,508
|
<p>Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible? </p>
| 8
|
2009-02-13T16:06:29Z
| 546,535
|
<p>Sure it's possible:</p>
<pre><code>open input file
open output file 1
count = 0
for each line in file:
write to output file
count = count + 1
if count > maxlines:
close output file
open next output file
count = 0
</code></pre>
| 2
|
2009-02-13T16:10:36Z
|
[
"python"
] |
How can I split a file in python?
| 546,508
|
<p>Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible? </p>
| 8
|
2009-02-13T16:06:29Z
| 546,561
|
<p>This one splits a file up by newlines and writes it back out. You can change the delimiter easily. This can also handle uneven amounts as well, if you don't have a multiple of splitLen lines (20 in this example) in your input file.</p>
<pre><code>splitLen = 20 # 20 lines per file
outputBase = 'output' # output.1.txt, output.2.txt, etc.
# This is shorthand and not friendly with memory
# on very large files (Sean Cavanagh), but it works.
input = open('input.txt', 'r').read().split('\n')
at = 1
for lines in range(0, len(input), splitLen):
# First, get the list slice
outputData = input[lines:lines+splitLen]
# Now open the output file, join the new slice with newlines
# and write it out. Then close the file.
output = open(outputBase + str(at) + '.txt', 'w')
output.write('\n'.join(outputData))
output.close()
# Increment the counter
at += 1
</code></pre>
| 13
|
2009-02-13T16:17:41Z
|
[
"python"
] |
How can I split a file in python?
| 546,508
|
<p>Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible? </p>
| 8
|
2009-02-13T16:06:29Z
| 6,389,813
|
<p>Solution to split binary files into chapters .000, .001, etc.:</p>
<pre><code>FILE = 'scons-conversion.7z'
MAX = 500*1024*1024 # 500Mb - max chapter size
BUF = 50*1024*1024 # 50GB - memory buffer size
chapters = 0
uglybuf = ''
with open(FILE, 'rb') as src:
while True:
tgt = open(FILE+'.%03d' % chapters, 'wb')
written = 0
while written < MAX:
tgt.write(uglybuf)
tgt.write(src.read(min(BUF, MAX-written)))
written += min(BUF, MAX-written)
uglybuf = src.read(1)
if len(uglybuf) == 0:
break
tgt.close()
if len(uglybuf) == 0:
break
chapters += 1
</code></pre>
| 5
|
2011-06-17T17:58:58Z
|
[
"python"
] |
How can I split a file in python?
| 546,508
|
<p>Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible? </p>
| 8
|
2009-02-13T16:06:29Z
| 13,345,290
|
<p>A better loop for sli's example, not hogging memory :</p>
<pre><code>splitLen = 20 # 20 lines per file
outputBase = 'output' # output.1.txt, output.2.txt, etc.
input = open('input.txt', 'r')
count = 0
at = 0
dest = None
for line in input:
if count % splitLen == 0:
if dest: dest.close()
dest = open(outputBase + str(at) + '.txt', 'w')
at += 1
dest.write(line)
count += 1
</code></pre>
| 8
|
2012-11-12T14:15:35Z
|
[
"python"
] |
How can I split a file in python?
| 546,508
|
<p>Is it possible to split a file? For example you have huge wordlist, I want to split it so that it becomes more than one file. How is this possible? </p>
| 8
|
2009-02-13T16:06:29Z
| 15,375,536
|
<pre><code>def split_file(file, prefix, max_size, buffer=1024):
"""
file: the input file
prefix: prefix of the output files that will be created
max_size: maximum size of each created file in bytes
buffer: buffer size in bytes
Returns the number of parts created.
"""
with open(file, 'r+b') as src:
suffix = 0
while True:
with open(prefix + '.%s' % suffix, 'w+b') as tgt:
written = 0
while written < max_size:
data = src.read(buffer)
if data:
tgt.write(data)
written += buffer
else:
return suffix
suffix += 1
def cat_files(infiles, outfile, buffer=1024):
"""
infiles: a list of files
outfile: the file that will be created
buffer: buffer size in bytes
"""
with open(outfile, 'w+b') as tgt:
for infile in sorted(infiles):
with open(infile, 'r+b') as src:
while True:
data = src.read(buffer)
if data:
tgt.write(data)
else:
break
</code></pre>
| 2
|
2013-03-13T01:38:40Z
|
[
"python"
] |
Multiple-instance Django forum software
| 546,753
|
<p>Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?</p>
| 2
|
2009-02-13T17:01:22Z
| 546,816
|
<p>Check out <a href="http://djangoplugables.com/projects/diamanda/" rel="nofollow">diamanda</a>. I'm not sure it does what you need as far as the each user having its forums, but that's probably not too hard to hack on top. Probably as simple as adding a few ForeignKeys into auth.User to the diamanda models. In general <a href="http://djangoplugables.com/" rel="nofollow">django pluggables</a> and <a href="http://djangoapps.org/" rel="nofollow">djangoapps</a> are good places to look for django stuff that is already written. Also, check out <a href="http://cloud27.com/" rel="nofollow">pinax</a>.</p>
| 0
|
2009-02-13T17:16:50Z
|
[
"python",
"django",
"forum"
] |
Multiple-instance Django forum software
| 546,753
|
<p>Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?</p>
| 2
|
2009-02-13T17:01:22Z
| 548,988
|
<p>I once created a <a href="http://code.djangoproject.com/wiki/ForumAppsComparison" rel="nofollow">feature matrix of all Django forum apps I could find. It might be a bit outdated now, though (contributions welcome).</p>
<p>At least django-threadedcomments</a> uses generic foreign keys, so you can attach a message thread to any database object, including users. </p>
| 4
|
2009-02-14T11:45:31Z
|
[
"python",
"django",
"forum"
] |
Multiple-instance Django forum software
| 546,753
|
<p>Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?</p>
| 2
|
2009-02-13T17:01:22Z
| 552,302
|
<p>I believe the <a href="http://sct.sphene.net/wiki/show/Board/" rel="nofollow">Sphene Community Tools</a> can do this.</p>
| 0
|
2009-02-16T04:59:15Z
|
[
"python",
"django",
"forum"
] |
Multiple-instance Django forum software
| 546,753
|
<p>Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?</p>
| 2
|
2009-02-13T17:01:22Z
| 881,457
|
<p>Yep, the <a href="http://sct.sphene.net/" rel="nofollow">forum app of SCT</a> can be used for this - simply set it up and create multiple "community Groups" (these are similar to vhosts) and map them to subdomains - each community group would have separate forum categories, can have separate templates, separate user permissions, etc. (but they will obviously share the same django users and their profiles) - as an example.. the following websites are all hosted on the same instance: </p>
<ul>
<li><a href="http://sct.sphene.net/" rel="nofollow">SCT website</a></li>
<li><a href="http://herbert.poul.at/" rel="nofollow">My personal website/blog</a> (the blog is also based on SCTs forum)</li>
<li><a href="http://shelfshare-community.sphene.net/" rel="nofollow">ShelfShare Community</a></li>
</ul>
| 1
|
2009-05-19T07:52:41Z
|
[
"python",
"django",
"forum"
] |
Multiple-instance Django forum software
| 546,753
|
<p>Does anyone know of a django forum plugin that allows each member to have his own forum? If there isn't anything, than what would be the best way to accomplish this with a "regular" forum plugin for Django?</p>
| 2
|
2009-02-13T17:01:22Z
| 3,921,625
|
<p>Look at <a href="http://djangobb.org/" rel="nofollow">DjangoBB</a>.</p>
| 2
|
2010-10-13T07:38:35Z
|
[
"python",
"django",
"forum"
] |
Send Info from Script to Module Python
| 547,450
|
<p>Hi I wonder how you can send info over to a module </p>
<p>An Example
main.py Looks like this</p>
<pre><code>from module import *
print helloworld()
</code></pre>
<p>module.py looks like this</p>
<pre><code>def helloworld():
print "Hello world!"
</code></pre>
<p>Anyway i want to send over info from main.py to module.py is it possible?</p>
| 2
|
2009-02-13T19:59:51Z
| 547,462
|
<p>It is not clear what you mean by "send info", but if you but the typical way of passing a value would be with a function parameter.</p>
<p>main.py:</p>
<pre><code>helloworld("Hello world!")
</code></pre>
<p>module.py</p>
<pre><code>def helloworld(message):
print message
</code></pre>
<p>Is that what your looking for? Also the two uses of <code>print</code> in your example are redundant.</p>
<p>Addendum: It might be useful for you to read the <a href="http://docs.python.org/tutorial/controlflow.html#defining-functions" rel="nofollow">Python documentation regarding function declarations</a>, or, alternatively, most Python introductory tutorials would cover the same ground in fewer words. Anything you read there is going to apply equally regardless of whether the function is in the same module or another module.</p>
| 1
|
2009-02-13T20:05:05Z
|
[
"python"
] |
Send Info from Script to Module Python
| 547,450
|
<p>Hi I wonder how you can send info over to a module </p>
<p>An Example
main.py Looks like this</p>
<pre><code>from module import *
print helloworld()
</code></pre>
<p>module.py looks like this</p>
<pre><code>def helloworld():
print "Hello world!"
</code></pre>
<p>Anyway i want to send over info from main.py to module.py is it possible?</p>
| 2
|
2009-02-13T19:59:51Z
| 547,471
|
<p>Yes. You can either send over information when calling functions/classes in module, or you can assign values in module's namespace (not so preferable).</p>
<p>As an example:</p>
<pre><code># module.py
# good example
def helloworld(name):
print "Hello, %s" % name
# main.py
# good example
import module
module.helloworld("Jim")
</code></pre>
<p>And for the bad: don't do it:</p>
<pre><code># module.py
# bad example
def helloworld():
print "Hello, %s" % name
# main.py
# bad example
import module
module.name = "Jim"
module.helloworld()
</code></pre>
| 1
|
2009-02-13T20:08:24Z
|
[
"python"
] |
dead simple Django file uploading not working :-((
| 547,743
|
<p>I am trying desperately to do a very simple file upload with Django, without (for now) bothering with templating & co.</p>
<p>My HTML is:</p>
<pre><code> <form
id="uploader"
action="bytes/"
enctype="multipart/form-data"
method="post"
>
<input type="file" name="uploaded"/>
<input type="submit" value="upload"/>
</form>
</code></pre>
<p>My Python is (knowing it is a POST):</p>
<pre><code>if path=="bytes/":
if 'uploaded' in request.FILES:
return HttpResponse("you uploaded a file")
else:
return HttpResponse("did not get the file")
</code></pre>
<p>I don't understand why I'm always getting the "did not get the file" message...</p>
<p>Can anyone help me, please???</p>
| 5
|
2009-02-13T21:19:39Z
| 548,175
|
<p>Try changing "<code>if 'uploaded' in request.FILES:</code>" to "<code>if request.FILES</code>".</p>
<p>You might want to take a look at the documentation as well; there's an example-- <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/file-uploads/</a></p>
| 6
|
2009-02-14T00:04:35Z
|
[
"python",
"django",
"upload"
] |
Python using result of function for Regular Expression Substitution
| 547,798
|
<p>I have a block of text, and for every regex match, I want to substitute that match with the return value from another function. The argument to this function is of course the matched text.</p>
<p>I have been having trouble trying to come up with a one pass solution to this problem. It feels like it should be pretty simple.</p>
| 5
|
2009-02-13T21:38:30Z
| 547,817
|
<p>Right from <a href="http://docs.python.org/library/re.html#re.sub">the documentation</a>:</p>
<pre><code>>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
</code></pre>
| 14
|
2009-02-13T21:45:58Z
|
[
"python",
"regex"
] |
Python using result of function for Regular Expression Substitution
| 547,798
|
<p>I have a block of text, and for every regex match, I want to substitute that match with the return value from another function. The argument to this function is of course the matched text.</p>
<p>I have been having trouble trying to come up with a one pass solution to this problem. It feels like it should be pretty simple.</p>
| 5
|
2009-02-13T21:38:30Z
| 547,822
|
<p>Python-agnostic: Match everything before and everything after your text to replace.</p>
<pre><code>/^(.*?)(your regexp to match)(.*)$/
</code></pre>
<p>Then you have the next before and after the text you're going to replace. The rest is easy -- just insert the result of your function between the two strings.</p>
| 0
|
2009-02-13T21:47:22Z
|
[
"python",
"regex"
] |
How to dynamically load a Python class
| 547,829
|
<p>Given a string of a Python class, e.g. <code>my_package.my_module.MyClass</code>, what is the best possible way to load it?</p>
<p>In other words I am looking for a equivalent <code>Class.forName()</code> in Java, function in Python. It needs to work on Google App Engine.</p>
<p>Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:</p>
<pre><code>my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
</code></pre>
| 74
|
2009-02-13T21:49:04Z
| 547,865
|
<pre><code>module = __import__("my_package/my_module")
the_class = getattr(module, "MyClass")
obj = the_class()
</code></pre>
| -3
|
2009-02-13T22:01:44Z
|
[
"python",
"reflection",
"python-import"
] |
How to dynamically load a Python class
| 547,829
|
<p>Given a string of a Python class, e.g. <code>my_package.my_module.MyClass</code>, what is the best possible way to load it?</p>
<p>In other words I am looking for a equivalent <code>Class.forName()</code> in Java, function in Python. It needs to work on Google App Engine.</p>
<p>Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:</p>
<pre><code>my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
</code></pre>
| 74
|
2009-02-13T21:49:04Z
| 547,867
|
<p>From the python documentation, here's the function you want:</p>
<pre><code>def my_import(name):
components = name.split('.')
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
</code></pre>
<p>The reason a simple <code>__import__</code> won't work is because any import of anything past the first dot in a package string is an attribute of the module you're importing. Thus, something like this won't work:</p>
<pre><code>__import__('foo.bar.baz.qux')
</code></pre>
<p>You'd have to call the above function like so:</p>
<pre><code>my_import('foo.bar.baz.qux')
</code></pre>
<p>Or in the case of your example:</p>
<pre><code>klass = my_import('my_package.my_module.my_class')
some_object = klass()
</code></pre>
<p><strong>EDIT</strong>: I was a bit off on this. What you're basically wanting to do is this:</p>
<pre><code>from my_package.my_module import my_class
</code></pre>
<p>The above function is only necessary if you have a <em>empty</em> fromlist. Thus, the appropriate call would be like this:</p>
<pre><code>mod = __import__('my_package.my_module', fromlist=['my_class'])
klass = getattr(mod, 'my_class')
</code></pre>
| 109
|
2009-02-13T22:02:57Z
|
[
"python",
"reflection",
"python-import"
] |
How to dynamically load a Python class
| 547,829
|
<p>Given a string of a Python class, e.g. <code>my_package.my_module.MyClass</code>, what is the best possible way to load it?</p>
<p>In other words I am looking for a equivalent <code>Class.forName()</code> in Java, function in Python. It needs to work on Google App Engine.</p>
<p>Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:</p>
<pre><code>my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
</code></pre>
| 74
|
2009-02-13T21:49:04Z
| 8,255,024
|
<pre><code>def import_class(cl):
d = cl.rfind(".")
classname = cl[d+1:len(cl)]
m = __import__(cl[0:d], globals(), locals(), [classname])
return getattr(m, classname)
</code></pre>
| 23
|
2011-11-24T09:49:03Z
|
[
"python",
"reflection",
"python-import"
] |
How to dynamically load a Python class
| 547,829
|
<p>Given a string of a Python class, e.g. <code>my_package.my_module.MyClass</code>, what is the best possible way to load it?</p>
<p>In other words I am looking for a equivalent <code>Class.forName()</code> in Java, function in Python. It needs to work on Google App Engine.</p>
<p>Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:</p>
<pre><code>my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
</code></pre>
| 74
|
2009-02-13T21:49:04Z
| 19,228,066
|
<pre><code>import importlib
module = importlib.import_module('my_package.my_module')
my_class = getattr(module, 'MyClass')
my_instance = my_class()
</code></pre>
| 28
|
2013-10-07T14:55:19Z
|
[
"python",
"reflection",
"python-import"
] |
How to dynamically load a Python class
| 547,829
|
<p>Given a string of a Python class, e.g. <code>my_package.my_module.MyClass</code>, what is the best possible way to load it?</p>
<p>In other words I am looking for a equivalent <code>Class.forName()</code> in Java, function in Python. It needs to work on Google App Engine.</p>
<p>Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:</p>
<pre><code>my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
</code></pre>
| 74
|
2009-02-13T21:49:04Z
| 24,815,361
|
<p>If you don't want to roll your own, there is a function available in the <code>pydoc</code> module that does exactly this:</p>
<pre><code>from pydoc import locate
my_class = locate('my_package.my_module.MyClass')
</code></pre>
<p>The advantage of this approach over the others listed here is that <code>locate</code> will find <em>any</em> python object at the provided dotted path, not just an object directly within a module. e.g. <code>my_package.my_module.MyClass.attr</code>.</p>
<p>If you're curious what their recipe is, here's the function:</p>
<pre><code>def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
else:
object = __builtin__
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
</code></pre>
<p>It relies on <code>pydoc.safeimport</code> function. Here are the docs for that:</p>
<pre><code>"""Import a module; handle errors; return None if the module isn't found.
If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised. Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning. If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""
</code></pre>
| 44
|
2014-07-17T23:52:06Z
|
[
"python",
"reflection",
"python-import"
] |
How to dynamically load a Python class
| 547,829
|
<p>Given a string of a Python class, e.g. <code>my_package.my_module.MyClass</code>, what is the best possible way to load it?</p>
<p>In other words I am looking for a equivalent <code>Class.forName()</code> in Java, function in Python. It needs to work on Google App Engine.</p>
<p>Preferably this would be a function that accepts the FQN of the class as a string, and returns a reference to the class:</p>
<pre><code>my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
</code></pre>
| 74
|
2009-02-13T21:49:04Z
| 26,277,655
|
<p>In Google App Engine there is a <code>webapp2</code> function called <code>import_string</code>. For more info see here:<a href="https://webapp-improved.appspot.com/api/webapp2.html" rel="nofollow">https://webapp-improved.appspot.com/api/webapp2.html</a></p>
<p>So,</p>
<pre><code>import webapp2
my_class = webapp2.import_string('my_package.my_module.MyClass')
</code></pre>
<p>For example this is used in the <code>webapp2.Route</code> where you can either use a handler or a string.</p>
| -1
|
2014-10-09T11:47:00Z
|
[
"python",
"reflection",
"python-import"
] |
Creating an inheritable Python type with PyCxx
| 548,442
|
<p>A friend and I have been toying around with various Python C++ wrappers lately, trying to find one that meets the needs of both some professional and hobby projects. We've both honed in on <a href="http://cxx.sourceforge.net/" rel="nofollow">PyCxx</a> as a good balance between being lightweight and easy to interface with while hiding away some of the ugliest bits of the Python C api. PyCxx is not terribly robust when it comes to exposing types, however (ie: it instructs you to create type factories rather than implement constructors), and we have been working on filling in the gaps in order to expose our types in a more functional manner. In order to fill these gaps we turn to the C api.</p>
<p>This has left us with some questions, however, that the api documentation doesn't seem to cover in much depth (and when it does, the answers are occasionally contradictory). The basic overarching question is simply this: What must be defined for a Python type to function as a base type? We've found that for the PyCxx class to function as a type we need to define tp_new and tp_dealloc explicitly and set the type as a module attribute, and that we need to have Py_TPFLAGS_BASETYPE set on [our type]->tp_flags, but beyond that we're still groping in the dark.</p>
<p>Here is our code thus far:</p>
<pre><code>class kitty : public Py::PythonExtension<kitty> {
public:
kitty() : Py::PythonExtension<kitty>() {}
virtual ~kitty() {}
static void init_type() {
behaviors().name("kitty");
add_varargs_method("speak", &kitty::speak);
}
static PyObject* tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) {
return static_cast<PyObject*>(new kitty());
}
static void tp_dealloc(PyObject *obj) {
kitty* k = static_cast<kitty*>(obj);
delete k;
}
private:
Py::Object speak(const Py::Tuple &args) {
cout << "Meow!" << endl;
return Py::None();
}
};
// cat Module
class cat_module : public Py::ExtensionModule<cat_module> {
public:
cat_module() : Py::ExtensionModule<cat_module>("cat") {
kitty::init_type();
// Set up additional properties on the kitty type object
PyTypeObject* kittyType = kitty::type_object();
kittyType->tp_new = &kitty::tp_new;
kittyType->tp_dealloc = &kitty::tp_dealloc;
kittyType->tp_flags |= Py_TPFLAGS_BASETYPE;
// Expose the kitty type through the module
module().setAttr("kitty", Py::Object((PyObject*)kittyType));
initialize();
}
virtual ~cat_module() {}
};
extern "C" void initcat() {
static cat_module* cat = new cat_module();
}
</code></pre>
<p>And our Python test code looks like this:</p>
<pre><code>import cat
class meanKitty(cat.kitty):
def scratch(self):
print "hiss! *scratch*"
myKitty = cat.kitty()
myKitty.speak()
meanKitty = meanKitty()
meanKitty.speak()
meanKitty.scratch()
</code></pre>
<p>The curious bit is that if you comment all the meanKitty bits out, the script runs and the cat meows just fine, but if you uncomment the meanKitty class suddenly Python gives us this:</p>
<pre><code>AttributeError: 'kitty' object has no attribute 'speak'
</code></pre>
<p>Which confuses the crap out of me. It's as if inheriting from it hides the base class entirely! If anyone could provide some insight into what we are missing, it would be appreciated! Thanks!</p>
<p><hr /></p>
<p>EDIT: Okay, so about five seconds after posting this I recalled something that we had wanted to try earlier. I added the following code to kitty -</p>
<pre><code>virtual Py::Object getattr( const char *name ) {
return getattr_methods( name );
}
</code></pre>
<p>And now we're meowing on both kitties in Python! still not fully there, however, because now I get this:</p>
<pre><code>Traceback (most recent call last):
File "d:\Development\Junk Projects\PythonCxx\Toji.py", line 12, in <module>
meanKitty.scratch()
AttributeError: scratch
</code></pre>
<p>So still looking for some help! Thanks!</p>
| 3
|
2009-02-14T03:44:08Z
| 551,927
|
<p>I've only done a tiny bit of work with PyCxx, and I'm not at a compiler, but I suspect what you're seeing is similar to the following situation, as expressed in pure Python:</p>
<pre><code>>>> class C(object):
... def __getattribute__(self, key):
... print 'C', key
...
>>> class D(C):
... def __init__(self):
... self.foo = 1
...
>>> D().foo
C foo
>>>
</code></pre>
<p>My best guess is that the C++ <code>getattr</code> method should check <code>this.ob_type->tp_dict</code> (which will of course be the subclass' dict, if <code>this</code> an instance of the subclass) and only call <code>getattr_methods</code> if you fail to find <code>name</code> in there (see the PyDict_ API functions).</p>
<p>Also, I don't think you should set <code>tp_dealloc</code> yourself: I don't see how your implementation improves on PyCxx's default <code>extension_object_deallocator</code>.</p>
| 1
|
2009-02-16T00:35:00Z
|
[
"python",
"python-c-api",
"pycxx"
] |
Creating an inheritable Python type with PyCxx
| 548,442
|
<p>A friend and I have been toying around with various Python C++ wrappers lately, trying to find one that meets the needs of both some professional and hobby projects. We've both honed in on <a href="http://cxx.sourceforge.net/" rel="nofollow">PyCxx</a> as a good balance between being lightweight and easy to interface with while hiding away some of the ugliest bits of the Python C api. PyCxx is not terribly robust when it comes to exposing types, however (ie: it instructs you to create type factories rather than implement constructors), and we have been working on filling in the gaps in order to expose our types in a more functional manner. In order to fill these gaps we turn to the C api.</p>
<p>This has left us with some questions, however, that the api documentation doesn't seem to cover in much depth (and when it does, the answers are occasionally contradictory). The basic overarching question is simply this: What must be defined for a Python type to function as a base type? We've found that for the PyCxx class to function as a type we need to define tp_new and tp_dealloc explicitly and set the type as a module attribute, and that we need to have Py_TPFLAGS_BASETYPE set on [our type]->tp_flags, but beyond that we're still groping in the dark.</p>
<p>Here is our code thus far:</p>
<pre><code>class kitty : public Py::PythonExtension<kitty> {
public:
kitty() : Py::PythonExtension<kitty>() {}
virtual ~kitty() {}
static void init_type() {
behaviors().name("kitty");
add_varargs_method("speak", &kitty::speak);
}
static PyObject* tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds) {
return static_cast<PyObject*>(new kitty());
}
static void tp_dealloc(PyObject *obj) {
kitty* k = static_cast<kitty*>(obj);
delete k;
}
private:
Py::Object speak(const Py::Tuple &args) {
cout << "Meow!" << endl;
return Py::None();
}
};
// cat Module
class cat_module : public Py::ExtensionModule<cat_module> {
public:
cat_module() : Py::ExtensionModule<cat_module>("cat") {
kitty::init_type();
// Set up additional properties on the kitty type object
PyTypeObject* kittyType = kitty::type_object();
kittyType->tp_new = &kitty::tp_new;
kittyType->tp_dealloc = &kitty::tp_dealloc;
kittyType->tp_flags |= Py_TPFLAGS_BASETYPE;
// Expose the kitty type through the module
module().setAttr("kitty", Py::Object((PyObject*)kittyType));
initialize();
}
virtual ~cat_module() {}
};
extern "C" void initcat() {
static cat_module* cat = new cat_module();
}
</code></pre>
<p>And our Python test code looks like this:</p>
<pre><code>import cat
class meanKitty(cat.kitty):
def scratch(self):
print "hiss! *scratch*"
myKitty = cat.kitty()
myKitty.speak()
meanKitty = meanKitty()
meanKitty.speak()
meanKitty.scratch()
</code></pre>
<p>The curious bit is that if you comment all the meanKitty bits out, the script runs and the cat meows just fine, but if you uncomment the meanKitty class suddenly Python gives us this:</p>
<pre><code>AttributeError: 'kitty' object has no attribute 'speak'
</code></pre>
<p>Which confuses the crap out of me. It's as if inheriting from it hides the base class entirely! If anyone could provide some insight into what we are missing, it would be appreciated! Thanks!</p>
<p><hr /></p>
<p>EDIT: Okay, so about five seconds after posting this I recalled something that we had wanted to try earlier. I added the following code to kitty -</p>
<pre><code>virtual Py::Object getattr( const char *name ) {
return getattr_methods( name );
}
</code></pre>
<p>And now we're meowing on both kitties in Python! still not fully there, however, because now I get this:</p>
<pre><code>Traceback (most recent call last):
File "d:\Development\Junk Projects\PythonCxx\Toji.py", line 12, in <module>
meanKitty.scratch()
AttributeError: scratch
</code></pre>
<p>So still looking for some help! Thanks!</p>
| 3
|
2009-02-14T03:44:08Z
| 554,810
|
<p>You must declare <code>kitty</code> as <code>class new_style_class: public Py::PythonClass< new_style_class ></code>. See <code>simple.cxx</code> and the Python test case at <a href="http://cxx.svn.sourceforge.net/viewvc/cxx/trunk/CXX/Demo/Python3/" rel="nofollow">http://cxx.svn.sourceforge.net/viewvc/cxx/trunk/CXX/Demo/Python3/</a>.</p>
<p>Python 2.2 introduced new-style classes which among other things allow the user to subclass built-in types (like your new built-in type). Inheritance didn't work in your example because it defines an old-style class.</p>
| 3
|
2009-02-16T22:17:13Z
|
[
"python",
"python-c-api",
"pycxx"
] |
jcc.initVM() doesn't return when mod_wsgi is configured as daemon mode
| 548,493
|
<p>I am using mod-wsgi with django, and in django I use pylucene to do full text search.</p>
<p>While mod-wsgi is configured to be embedded mode, there is no problem at all.
But when mod-wsgi is configured to be daemon mode, the apache just gets stuck,
and the browser just keep loading but nothing appears.</p>
<p>Then I identity the problem to be the jcc.initVM().
Here is my wsgi script:</p>
<pre><code>import os, sys, jcc
sys.stderr.write('jcc.initVM\n')
jcc.initVM()
sys.stderr.write('finished jcc.initVM\n')
....
</code></pre>
<p>After I restart my apache, and make a request from my browser, I find that /var/log/apache2/error.log
only has:</p>
<pre><code>jcc.initVM
</code></pre>
<p>Meaning that it gets stuck at the line jcc.initVM(). (If the mod_wsgi is configured as embedded mode, there is no problem.)</p>
<p>And here is my /etc/apache2/sites-available/default:</p>
<pre><code>WSGIDaemonProcess site user=ross group=ross threads=1
WSGIProcessGroup site
WSGIScriptAlias / /home/ross/apache/django.wsgi
<Directory /home/ross/apache/>
Order deny,allow
Allow from all
</Directory>
</code></pre>
<p>And finally, I find out that in the source code of jcc (jcc.cpp), it hangs at the function:</p>
<pre><code>JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args)
</code></pre>
<p>How to solve the problem?</p>
<p>Program versions:</p>
<pre><code>libapache2-mod-wsgi 2.3-1
jcc 2.1
python 2.5
Apache 2.2.9-8ubuntu3
Ubuntu 8.10
</code></pre>
| 3
|
2009-02-14T04:39:28Z
| 555,382
|
<p>Please refer to <a href="http://code.google.com/p/modwsgi/issues/detail?id=131" rel="nofollow">http://code.google.com/p/modwsgi/issues/detail?id=131</a> for the discussion details. </p>
<p>In short, the
mod_wsgi will block signals for the daemon program, which may make initVM doesn't work. Furthermore according to
Andi from jcc, initVM can only be called from the main thread, and it may cause further problem as well.</p>
<p>Therefore I decided to move the search code with initVM() to a totally separate process and solved the problem.</p>
| 1
|
2009-02-17T02:45:56Z
|
[
"python",
"apache",
"mod-wsgi",
"pylucene",
"jcc"
] |
jcc.initVM() doesn't return when mod_wsgi is configured as daemon mode
| 548,493
|
<p>I am using mod-wsgi with django, and in django I use pylucene to do full text search.</p>
<p>While mod-wsgi is configured to be embedded mode, there is no problem at all.
But when mod-wsgi is configured to be daemon mode, the apache just gets stuck,
and the browser just keep loading but nothing appears.</p>
<p>Then I identity the problem to be the jcc.initVM().
Here is my wsgi script:</p>
<pre><code>import os, sys, jcc
sys.stderr.write('jcc.initVM\n')
jcc.initVM()
sys.stderr.write('finished jcc.initVM\n')
....
</code></pre>
<p>After I restart my apache, and make a request from my browser, I find that /var/log/apache2/error.log
only has:</p>
<pre><code>jcc.initVM
</code></pre>
<p>Meaning that it gets stuck at the line jcc.initVM(). (If the mod_wsgi is configured as embedded mode, there is no problem.)</p>
<p>And here is my /etc/apache2/sites-available/default:</p>
<pre><code>WSGIDaemonProcess site user=ross group=ross threads=1
WSGIProcessGroup site
WSGIScriptAlias / /home/ross/apache/django.wsgi
<Directory /home/ross/apache/>
Order deny,allow
Allow from all
</Directory>
</code></pre>
<p>And finally, I find out that in the source code of jcc (jcc.cpp), it hangs at the function:</p>
<pre><code>JNI_CreateJavaVM(&vm, (void **) &vm_env, &vm_args)
</code></pre>
<p>How to solve the problem?</p>
<p>Program versions:</p>
<pre><code>libapache2-mod-wsgi 2.3-1
jcc 2.1
python 2.5
Apache 2.2.9-8ubuntu3
Ubuntu 8.10
</code></pre>
| 3
|
2009-02-14T04:39:28Z
| 1,042,036
|
<p>The fix for this problem was included in mod_wsgi 2.4.</p>
| 1
|
2009-06-25T03:31:51Z
|
[
"python",
"apache",
"mod-wsgi",
"pylucene",
"jcc"
] |
SQLAlchemy and empty columns
| 548,952
|
<p>When I try to insert a new record into the database using SQLAlchemy and I don't fill out all values, it tries to insert them as "None" (instead of omitting them). It then complains about "can't be null" errors. Is there a way to have it just omit columns from the sql query if I also omitted them when declaring the instance?</p>
| 9
|
2009-02-14T11:14:06Z
| 548,958
|
<p>This is a database schema issue, not an SQLAlchemy issue. If your database schema has a column which cannot be NULL, you must put something (i.e. not None) into there. Or change your schema to allow NULL in those columns.</p>
<p>Wikipedia has an article <a href="http://en.wikipedia.org/wiki/Null_(SQL)">about NULL</a> and an article which describes <a href="http://en.wikipedia.org/wiki/Check_Constraint#NOT_NULL_Constraint">non-NULL constraints</a></p>
| 12
|
2009-02-14T11:26:35Z
|
[
"python",
"database-design",
"sqlalchemy"
] |
SQLAlchemy and empty columns
| 548,952
|
<p>When I try to insert a new record into the database using SQLAlchemy and I don't fill out all values, it tries to insert them as "None" (instead of omitting them). It then complains about "can't be null" errors. Is there a way to have it just omit columns from the sql query if I also omitted them when declaring the instance?</p>
| 9
|
2009-02-14T11:14:06Z
| 549,022
|
<p>To add to the answer from Ali A, this means you need to have <code>nullable=True</code> in your column definition, so that NULL is allowed in the column. For example:</p>
<pre><code>email_address = Column(String, nullable=True)
</code></pre>
<p><a href="http://sqlalchemy.readthedocs.org/en/rel_1_0/core/metadata.html#accessing-tables-and-columns">SQLAlchemy docs for Tables and Columns</a></p>
| 25
|
2009-02-14T12:11:20Z
|
[
"python",
"database-design",
"sqlalchemy"
] |
Delete Chars in Python
| 549,130
|
<p>does anybody know how to delete all characters behind a specific character??</p>
<p>like this:</p>
<pre><code>http://google.com/translate_t
</code></pre>
<p>into </p>
<pre><code>http://google.com
</code></pre>
| 2
|
2009-02-14T13:46:31Z
| 549,133
|
<pre><code>str="http://google.com/translate_t"
shortened=str[0:str.rfind("/")]
</code></pre>
<p>Should do it. str[a:b] returns a substring in python. And rfind is used to find the index of a character sequence, starting at the end of the string.</p>
| 2
|
2009-02-14T13:50:19Z
|
[
"python",
"text-processing"
] |
Delete Chars in Python
| 549,130
|
<p>does anybody know how to delete all characters behind a specific character??</p>
<p>like this:</p>
<pre><code>http://google.com/translate_t
</code></pre>
<p>into </p>
<pre><code>http://google.com
</code></pre>
| 2
|
2009-02-14T13:46:31Z
| 549,138
|
<p>If you know the position of the character then you can use the slice syntax to to create a new string:</p>
<pre><code>In [2]: s1 = "abc123"
In [3]: s2 = s1[:3]
In [4]: print s2
abc
</code></pre>
<p>To find the position you can use the <code>find()</code> or <code>index()</code> methods of strings.
The <code>split()</code> and <code>partition()</code> methods may be useful, too.
Those methods are documented in the <a href="http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange" rel="nofollow">Python docs for sequences</a>.</p>
<p>To remove a part of a string is imposible because strings are immutable.</p>
<p>If you want to process URLs then you should definitely use the <a href="http://docs.python.org/library/urlparse.html" rel="nofollow">urlparse library</a>. It lets you split an URL into its parts. If you just want remove a part of the file path then you will have to do that still by yourself.</p>
| 2
|
2009-02-14T13:54:11Z
|
[
"python",
"text-processing"
] |
Delete Chars in Python
| 549,130
|
<p>does anybody know how to delete all characters behind a specific character??</p>
<p>like this:</p>
<pre><code>http://google.com/translate_t
</code></pre>
<p>into </p>
<pre><code>http://google.com
</code></pre>
| 2
|
2009-02-14T13:46:31Z
| 549,140
|
<p>if you're asking about an abstract string and not url you could go with:</p>
<pre><code>>>> astring ="http://google.com/translate_t"
>>> astring.rpartition('/')[0]
http://google.com
</code></pre>
| 6
|
2009-02-14T13:54:24Z
|
[
"python",
"text-processing"
] |
Delete Chars in Python
| 549,130
|
<p>does anybody know how to delete all characters behind a specific character??</p>
<p>like this:</p>
<pre><code>http://google.com/translate_t
</code></pre>
<p>into </p>
<pre><code>http://google.com
</code></pre>
| 2
|
2009-02-14T13:46:31Z
| 549,184
|
<p>For urls, using <a href="http://docs.python.org/library/urlparse.html" rel="nofollow">urlparse</a>:</p>
<pre><code>>>> import urlparse
>>> parts = urlparse.urlsplit('http://google.com/path/to/resource?query=spam#anchor')
>>> parts
('http', 'google.com', '/path/to/resource', 'query=spam', 'anchor')
>>> urlparse.urlunsplit((parts[0], parts[1], '', '', ''))
'http://google.com'
</code></pre>
<p>For arbitrary strings, using <a href="http://docs.python.org/library/re.html" rel="nofollow">re</a>:</p>
<pre><code>>>> import re
>>> re.split(r'\b/\b', 'http://google.com/path/to/resource', 1)
['http://google.com', 'path/to/resource']
</code></pre>
| 5
|
2009-02-14T14:32:38Z
|
[
"python",
"text-processing"
] |
In the windows python console, how to make Tab = four spaces?
| 549,340
|
<p>Hello I would like that when I am in the python
console tabbing will give me four spaces. Any ideas? </p>
| 0
|
2009-02-14T16:38:44Z
| 549,362
|
<ol>
<li>Download and install <a href="http://www.autohotkey.com" rel="nofollow">AutoHotkey</a></li>
<li><p>Write this script:</p>
<pre><code>SetTitleMatchMode 2
#IfWinActive python
tab::
Send, {SPACE}
Send, {SPACE}
Send, {SPACE}
Send, {SPACE}
</code></pre></li>
</ol>
<p>Save it as tab-to-space.ahk, and doubleclick on the file.</p>
<p>Note: you might have to captalize "Python" to match your window tite. Or you can have "yhton" and it will match Jython too.</p>
| 5
|
2009-02-14T16:54:08Z
|
[
"python",
"windows"
] |
Python 3.0 smtplib
| 549,391
|
<p>I have a very simple piece of code that I used in previous versions of Python without issues (version 2.5 and prior). Now with 3.0, the following code give the error on the login line "argument 1 must be string or buffer, not str".</p>
<pre><code>import smtplib
smtpserver = 'mail.somedomain.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'admin@somedomain.com' # for SMTP AUTH, set SMTP username here
smtppass = 'somepassword' # for SMTP AUTH, set SMTP password here
msg = "Some message to send"
RECIPIENTS = ['admin@somedomain.com']
SENDER = 'someone@someotherdomain.net'
session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, msg)
</code></pre>
<p>Google shows there are some issues with that error not being clear, but I still can't figure out what I need to try to make it work. Suggestions included defining the username as b"username", but that doesn't seem to work either.</p>
| 3
|
2009-02-14T17:20:58Z
| 549,491
|
<pre><code>Traceback (most recent call last):
File "smtptest.py", line 18, in <module>
session.login(smtpuser, smtppass)
File "c:\Python30\lib\smtplib.py", line 580, in login
AUTH_PLAIN + " " + encode_plain(user, password))
File "c:\Python30\lib\smtplib.py", line 545, in encode_plain
return encode_base64("\0%s\0%s" % (user, password))
File "c:\Python30\lib\email\base64mime.py", line 96, in body_encode
enc = b2a_base64(s[i:i + max_unencoded]).decode("ascii")
TypeError: b2a_base64() argument 1 must be bytes or buffer, not str
</code></pre>
<p>Your code is correct. This is a bug in <strong>smtplib</strong> or in the <strong>base64mime.py</strong>.
You can track the issue here:
<a href="http://bugs.python.org/issue5259" rel="nofollow">http://bugs.python.org/issue5259</a></p>
<p>Hopefully the devs will post a patch soon.</p>
| 3
|
2009-02-14T18:21:05Z
|
[
"python",
"python-3.x"
] |
Python 3.0 smtplib
| 549,391
|
<p>I have a very simple piece of code that I used in previous versions of Python without issues (version 2.5 and prior). Now with 3.0, the following code give the error on the login line "argument 1 must be string or buffer, not str".</p>
<pre><code>import smtplib
smtpserver = 'mail.somedomain.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'admin@somedomain.com' # for SMTP AUTH, set SMTP username here
smtppass = 'somepassword' # for SMTP AUTH, set SMTP password here
msg = "Some message to send"
RECIPIENTS = ['admin@somedomain.com']
SENDER = 'someone@someotherdomain.net'
session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, msg)
</code></pre>
<p>Google shows there are some issues with that error not being clear, but I still can't figure out what I need to try to make it work. Suggestions included defining the username as b"username", but that doesn't seem to work either.</p>
| 3
|
2009-02-14T17:20:58Z
| 549,643
|
<p><strong>UPDATE</strong>: just noticed from a look at the bug tracker there's a suggested fix also: </p>
<p>Edit smtplib.py and replace the existing <code>encode_plain()</code> definition with this: </p>
<pre><code>def encode_plain(user, password):
s = "\0%s\0%s" % (user, password)
return encode_base64(s.encode('ascii'), eol='')
</code></pre>
<p>Tested here on my installation and it works properly. </p>
| 4
|
2009-02-14T19:29:28Z
|
[
"python",
"python-3.x"
] |
Python 3.0 smtplib
| 549,391
|
<p>I have a very simple piece of code that I used in previous versions of Python without issues (version 2.5 and prior). Now with 3.0, the following code give the error on the login line "argument 1 must be string or buffer, not str".</p>
<pre><code>import smtplib
smtpserver = 'mail.somedomain.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'admin@somedomain.com' # for SMTP AUTH, set SMTP username here
smtppass = 'somepassword' # for SMTP AUTH, set SMTP password here
msg = "Some message to send"
RECIPIENTS = ['admin@somedomain.com']
SENDER = 'someone@someotherdomain.net'
session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, msg)
</code></pre>
<p>Google shows there are some issues with that error not being clear, but I still can't figure out what I need to try to make it work. Suggestions included defining the username as b"username", but that doesn't seem to work either.</p>
| 3
|
2009-02-14T17:20:58Z
| 594,026
|
<p>As a variation on Jay's answer, rather than edit smtplib.py you could "monkey patch" it at run time.</p>
<p>Put this somewhere in your code:</p>
<pre><code>
def encode_plain(user, password):
s = "\0%s\0%s" % (user, password)
return encode_base64(s.encode('ascii'), eol='')
import smtplib
encode_plain.func_globals = vars(smtplib)
smtplib.encode_plain = encode_plain
</code></pre>
<p>This is kind of ugly but useful if you want to deploy your code onto other systems without making changes to their python libraries.</p>
| 2
|
2009-02-27T08:58:02Z
|
[
"python",
"python-3.x"
] |
Python 3.0 smtplib
| 549,391
|
<p>I have a very simple piece of code that I used in previous versions of Python without issues (version 2.5 and prior). Now with 3.0, the following code give the error on the login line "argument 1 must be string or buffer, not str".</p>
<pre><code>import smtplib
smtpserver = 'mail.somedomain.com'
AUTHREQUIRED = 1 # if you need to use SMTP AUTH set to 1
smtpuser = 'admin@somedomain.com' # for SMTP AUTH, set SMTP username here
smtppass = 'somepassword' # for SMTP AUTH, set SMTP password here
msg = "Some message to send"
RECIPIENTS = ['admin@somedomain.com']
SENDER = 'someone@someotherdomain.net'
session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, msg)
</code></pre>
<p>Google shows there are some issues with that error not being clear, but I still can't figure out what I need to try to make it work. Suggestions included defining the username as b"username", but that doesn't seem to work either.</p>
| 3
|
2009-02-14T17:20:58Z
| 1,062,307
|
<p>This issue has been addressed in Python3.1. Get the update at <a href="http://www.python.org/download/releases/3.1/" rel="nofollow">http://www.python.org/download/releases/3.1/</a></p>
| 0
|
2009-06-30T07:52:24Z
|
[
"python",
"python-3.x"
] |
Simple unique non-priority queue system
| 549,536
|
<p>I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid infinite looping). Can anyone give me or point me to a simple queue example that I could run off of?</p>
| 1
|
2009-02-14T18:44:53Z
| 549,543
|
<p>I'd just use a set, it doesn't maintain order but it will help you maintain uniqueness:</p>
<pre><code>>>> q = set([9, 8, 7, 7, 8, 5, 4, 1])
>>> q.pop()
1
>>> q.pop()
4
>>> q.pop()
5
>>> q.add(3)
>>> q.add(3)
>>> q.add(3)
>>> q.add(3)
>>> q
set([3, 7, 8, 9]
</code></pre>
| 4
|
2009-02-14T18:48:41Z
|
[
"python",
"queue"
] |
Simple unique non-priority queue system
| 549,536
|
<p>I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid infinite looping). Can anyone give me or point me to a simple queue example that I could run off of?</p>
| 1
|
2009-02-14T18:44:53Z
| 549,555
|
<p>Why not use a list if you need order (or even a heapq, as was formerly suggested by zacherates before a set was suggested instead) and also use a set to check for duplicates?</p>
| 1
|
2009-02-14T18:54:19Z
|
[
"python",
"queue"
] |
Simple unique non-priority queue system
| 549,536
|
<p>I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid infinite looping). Can anyone give me or point me to a simple queue example that I could run off of?</p>
| 1
|
2009-02-14T18:44:53Z
| 549,564
|
<p>A very simple example would be to stuff each item's URL into a dict, but as the key, not as the value. Then only process the next item if it's url is not in that dict's keys:</p>
<pre><code>visited = {}
# grab next url from somewhere
if url not in visited.keys():
# process url
visited[url] = 1 # or whatever, the value is unimportant
# repeat with next url
</code></pre>
<p>You can get more efficient, of course, but this would be simple.</p>
| 2
|
2009-02-14T18:57:16Z
|
[
"python",
"queue"
] |
Simple unique non-priority queue system
| 549,536
|
<p>I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid infinite looping). Can anyone give me or point me to a simple queue example that I could run off of?</p>
| 1
|
2009-02-14T18:44:53Z
| 549,591
|
<p>If I understand correctly, you want to visit each page only once. I think the best way to do this would be to keep a queue of pages still to visit, and a set of visited pages. The problem with the other posted solution is that once you pop a page from the queue, you no longer have a record of whether or not you've been there.</p>
<p>I'd use a combination of a set and a list:</p>
<pre><code>visited = set()
to_visit = []
def queue_page(url):
if url not in visited:
to_visit.append(url)
def visit(url):
visited.add(url)
... # some processing
# Add all found links to the queue
for link in links:
queue_page(link)
def page_iterator(start_url):
visit(start_url)
try:
yield to_visit.pop(0)
except IndexError:
raise StopIteration
for page in page_iterator(start):
visit(page)
</code></pre>
<p>Of course this a bit of a contrived example, and you'd probably be best off encapsulating this in some way, but it illustrates the concept.</p>
| 2
|
2009-02-14T19:10:31Z
|
[
"python",
"queue"
] |
Simple unique non-priority queue system
| 549,536
|
<p>I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid infinite looping). Can anyone give me or point me to a simple queue example that I could run off of?</p>
| 1
|
2009-02-14T18:44:53Z
| 549,823
|
<p>I would extend the list class to add unique-testing code to whatever methods of the list you are using. This could range from simply adding a <code>.append_unique(item)</code> to the class, or overriding all of <code>append</code>, <code>insert</code>, <code>extend</code>, <code>__setitem__</code>, <code>__setslice__</code>, etc, to throw an exception (or be silent, if you wish) in the case of a non-unique item.</p>
<p>For example, if you just wanted to make sure the append method maintained uniqueness:</p>
<pre><code>class UniqueList(list):
def append(self, item):
if item not in self:
list.append(self, item)
</code></pre>
| 0
|
2009-02-14T21:17:40Z
|
[
"python",
"queue"
] |
Skipping Iterations in Python
| 549,674
|
<p>I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my <code>except:</code> clause to just skip the rest of the current iteration?</p>
| 42
|
2009-02-14T19:48:04Z
| 549,680
|
<p>Something like this?</p>
<pre><code>for i in xrange( someBigNumber ):
try:
doSomethingThatMightFail()
except SomeException, e:
continue
doSomethingWhenNothingFailed()
</code></pre>
| 10
|
2009-02-14T19:50:18Z
|
[
"python",
"iteration",
"skip"
] |
Skipping Iterations in Python
| 549,674
|
<p>I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my <code>except:</code> clause to just skip the rest of the current iteration?</p>
| 42
|
2009-02-14T19:48:04Z
| 549,682
|
<p>You are lookin for <a href="http://docs.python.org/tutorial/controlflow.html">continue</a>.</p>
| 94
|
2009-02-14T19:50:46Z
|
[
"python",
"iteration",
"skip"
] |
Skipping Iterations in Python
| 549,674
|
<p>I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my <code>except:</code> clause to just skip the rest of the current iteration?</p>
| 42
|
2009-02-14T19:48:04Z
| 549,683
|
<p>I think you're looking for <a href="http://www.network-theory.co.uk/docs/pytut/breakandcontinueStatements.html">continue</a></p>
| 5
|
2009-02-14T19:51:02Z
|
[
"python",
"iteration",
"skip"
] |
Skipping Iterations in Python
| 549,674
|
<p>I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my <code>except:</code> clause to just skip the rest of the current iteration?</p>
| 42
|
2009-02-14T19:48:04Z
| 549,688
|
<pre><code>for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
</code></pre>
| 26
|
2009-02-14T19:52:29Z
|
[
"python",
"iteration",
"skip"
] |
Skipping Iterations in Python
| 549,674
|
<p>I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my <code>except:</code> clause to just skip the rest of the current iteration?</p>
| 42
|
2009-02-14T19:48:04Z
| 35,441,469
|
<p>For this specific use-case using <code>try..except..else</code> is the cleanest solution, the <code>else</code> clause will be executed if no exception was raised. </p>
<p>NOTE: The <code>else</code> clause must follow all <code>except</code> clauses</p>
<pre><code>for i in iterator:
try:
# Do something.
except:
# Handle exception
else:
# Continue doing something
</code></pre>
| 0
|
2016-02-16T19:31:13Z
|
[
"python",
"iteration",
"skip"
] |
Fully transparent windows in Pygame?
| 550,001
|
<p>Is it possible to get a fully transparent window in Pygame (see the desktop through it)? I've found how to create a window without a frame, but there doesn't seem to be any obvious way to make it transparent.</p>
<p>I'd be willing to tie into system-specific technology/frameworks as long as there are solutions for both Windows and Mac OS X, but I'm not sure which direction to be looking.</p>
<p>The only topic I was able to find <a href="http://stackoverflow.com/questions/396791/desktop-graphics-or-skinned-windows">recommended using wxPython</a>, which isn't something I can do for this particular project (needs to be Pygame).</p>
| 4
|
2009-02-14T23:40:50Z
| 550,007
|
<p>PyGame uses SDL, which does not support transparent windows. Although at least on Linux making it transparent is done by the window manager, not the application. </p>
| 7
|
2009-02-14T23:48:12Z
|
[
"python",
"graphics",
"sdl",
"pygame"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,018
|
<p>if you can be reasonably sure that lines containing these email addresses start with whitespace followed by "From:" you can simply do this:</p>
<pre><code>addresslines = []
for line in open("text.txt"):
if line.strip().startswith("From:"):
addresslines.append(line)
</code></pre>
<p>then later - or on adding them to the list - you can refine the addresslines items to give out exactly what you want</p>
| 0
|
2009-02-14T23:59:11Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,033
|
<p>"[stuff]@[stuff][stuff1-4 letters]" is about right, but if you wanted to you could decode the regular expression using a trick I just found out about, <a href="http://stackoverflow.com/questions/101268/hidden-features-of-python">here</a>. Do the compile() in an interactive Python session like this:</p>
<pre><code>mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}', 128)
</code></pre>
<p>It will print out the following:</p>
<pre><code>in
category category_word
literal 45
max_repeat 1 65535
in
category category_word
literal 45
literal 46
literal 64
in
category category_word
literal 45
max_repeat 1 65535
in
category category_word
literal 45
literal 46
max_repeat 1 4
in
range (97, 122)
range (65, 90)
</code></pre>
<p>Which, if you can kind of get used to it, shows you exactly how the RE works.</p>
| 0
|
2009-02-15T00:13:05Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,036
|
<p>Try this out:</p>
<pre><code>>>> from email.utils import parseaddr
>>> parseaddr('From: vg@m.com')
('', 'vg@m.com')
>>> parseaddr('From: Van Gale <vg@m.com>')
('Van Gale', 'vg@m.com')
>>> parseaddr(' From: Van Gale <vg@m.com> ')
('Van Gale', 'vg@m.com')
>>> parseaddr('blah abdf From: Van Gale <vg@m.com> and this')
('Van Gale', 'vg@m.com')
</code></pre>
<p>Unfortunately it only finds the first email in each line because it's expecting header lines, but maybe that's ok?</p>
| 31
|
2009-02-15T00:15:07Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,044
|
<p>I'd do it by expanding the regular expression you're using to include the extra text you want to match. So first, let me explain what that regex does:</p>
<pre><code>[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}
</code></pre>
<ul>
<li><code>[\w\-]</code> matches any "word" character (letter, number, or underscore), <em>or</em> a hyphen</li>
<li><code>[\w\-\.]+</code> matches (any word character <em>or</em> hyphen <em>or</em> period) one or more times</li>
<li><code>@</code> matches a literal '@'</li>
<li><code>[\w\-]</code> matches a word character or hyphen</li>
<li><code>[\w\-\.]+</code> matches one or more word characters, hyphens, and/or periods</li>
<li><code>[a-zA-Z]{1,4}</code> matches 1, 2, 3, or 4 lowercase or uppercase letters</li>
</ul>
<p>Now, to modify this for your purposes, let's add regex parts to match "From", the name, and the angle brackets:</p>
<pre><code>From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})>
</code></pre>
<ul>
<li><code>From: </code> matches the literal text "From: "</li>
<li><code>[\w\s]+?</code> matches one or more consecutive word characters <em>or</em> space characters. The question mark makes the match non-greedy, so it will match as few characters as possible while still allowing the whole regular expression to match (in this case, it's probably not necessary, but it does make the match more efficient since the thing that comes immediately afterwards is not a word character or space character).</li>
<li><code><</code> matches a literal less-than sign (opening angle bracket)</li>
<li>The same regular expression you had before is now surrounded by parentheses. This makes it a <em>capturing group</em>, so you can call <code>m.group(1)</code> to get the text matched by that part of the regex.</li>
<li><code>></code> matches a literal greater-than sign</li>
</ul>
<p>Since the regex now uses capturing groups, your code will need to change a little as well:</p>
<pre><code>import re
foundemail = []
mailsrch = re.compile(r'From: [\w\s]+?<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})>')
for line in open("text.txt"):
foundemail.extend([m.group(1) for m in mailsrch.finditer(line)])
print foundemail
</code></pre>
<p>The code <code>[m.group(1) for m in mailsrch.finditer(line)]</code> produces a list out of the first capturing group (remember, that was the part in parentheses) from each match found by the regular expression.</p>
| 1
|
2009-02-15T00:20:01Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,068
|
<pre><code>mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
</code></pre>
<p>Expression breakdown:</p>
<p><code>[\w-]</code>: any word character (alphanumeric, plus underscore) or a dash</p>
<p><code>[\w-.]+</code>: any word character, a dash, or a period/dot, one or more times</p>
<p><code>@</code>: literal @ symbol</p>
<p><code>[\w-][\w-.]+</code>: any word char or dash, followed by any word char, dash, or period one or more times.</p>
<p><code>[a-zA-Z]{1,4}</code>: any alphabetic character 1-4 times.</p>
<p>To make this match only lines starting with <code>From:</code>, and wrapped in < and > symbols: </p>
<pre><code>import re
foundemail = []
mailsrch = re.compile(r'^From:\s+.*<([\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4})>', re.I | re.M)
foundemail.extend(mailsrch.findall(open('text.txt').read()))
print foundemail
</code></pre>
| 2
|
2009-02-15T00:37:27Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,089
|
<p>Use the email and mailbox packages to parse the plain text version of the email. This will convert it to an object that will enable to extract all the addresses in the 'From' field.</p>
<p>You can also do a lot of other analysis on the message, if you need to process other header fields, or the message body.</p>
<p>As a quick example, the following (untested) code should read all the message in a unix style mailbox, and print all the 'from' headers.</p>
<pre><code>import mailbox
import email
mbox = mailbox.PortableUnixMailbox(open(filename, 'rU'), email.message_from_file)
for msg in mbox:
from = msg['From']
print from
</code></pre>
| 2
|
2009-02-15T00:52:29Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,105
|
<pre><code>import email
msg = email.message_from_string(str)
# or
# f = open(file)
# msg = email.message_from_file(f)
msg['from']
# and optionally
from email.utils import parseaddr
addr = parseaddr(msg['from'])
</code></pre>
| 8
|
2009-02-15T01:14:59Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
Parsing "From" addresses from email text
| 550,009
|
<p>I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses that are preceeded by "From:" and a few wildcard characters, and ending with ">" (because the emails are set up as From [name]<[email]>). </p>
<p>Here's the code now:</p>
<pre><code>import re #allows program to use regular expressions
foundemail = []
#this is an empty list
mailsrch = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
#do not currently know exact meaning of this expression but assuming
#it means something like "[stuff]@[stuff][stuff1-4 letters]"
# "line" is a variable is set to a single line read from the file
# ("text.txt"):
for line in open("text.txt"):
foundemail.extend(mailsrch.findall(line))
# this extends the previously named list via the "mailsrch" variable
#which was named before
print foundemail
</code></pre>
| 9
|
2009-02-14T23:49:22Z
| 550,132
|
<p>Roughly speaking, you can:</p>
<pre><code>from email.utils import parseaddr
foundemail = []
for line in open("text.txt"):
if not line.startswith("From:"): continue
n, e = parseaddr(line)
foundemail.append(e)
print foundemail
</code></pre>
<p>This utilizes the built-in python parseaddr function to parse the address out of the from line (as demonstrated by other answers), without the overhead necessarily of parsing the entire message (e.g. by using the more full featured email and mailbox packages). The script here simply skips any lines that do not begin with "From:". Whether the overhead matters to you depends on how big your input is and how often you will be doing this operation.</p>
| 1
|
2009-02-15T01:39:29Z
|
[
"python",
"string",
"email",
"parsing",
"text"
] |
What causes Python socket error?
| 550,032
|
<pre><code> File "C:\Python25\lib\SocketServer.py", line 330, in __init__
self.server_bind()
File "C:\Python25\lib\BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python25\lib\SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
socket.error: (10013, 'Permission denied')
</code></pre>
<p>I tried to start up the Google App Engine development server and received this error the first time I tried to run it. Any ideas? I'm new to python.</p>
| 10
|
2009-02-15T00:12:53Z
| 550,034
|
<p>It might be possible that you are trying to run on a port the current user account does not have permission to bind to. This could be port 80 or something. Try increasing the portnumber or use a user with sufficient privileges.</p>
<p>Hope this helps</p>
| 20
|
2009-02-15T00:14:39Z
|
[
"python",
"sockets",
"permissions"
] |
What causes Python socket error?
| 550,032
|
<pre><code> File "C:\Python25\lib\SocketServer.py", line 330, in __init__
self.server_bind()
File "C:\Python25\lib\BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python25\lib\SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
socket.error: (10013, 'Permission denied')
</code></pre>
<p>I tried to start up the Google App Engine development server and received this error the first time I tried to run it. Any ideas? I'm new to python.</p>
| 10
|
2009-02-15T00:12:53Z
| 1,082,830
|
<blockquote>
<p>I wonder why the error is not "Port
already in use". I kind of know the
answer but I should not need to use SO
to know it. :) â Oscar Reyes May 13 at
19:09</p>
</blockquote>
<p>The port is not in use, (in UNIX) you need to be superuser to listen on any port < 1024.</p>
| 3
|
2009-07-04T19:24:57Z
|
[
"python",
"sockets",
"permissions"
] |
What causes Python socket error?
| 550,032
|
<pre><code> File "C:\Python25\lib\SocketServer.py", line 330, in __init__
self.server_bind()
File "C:\Python25\lib\BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python25\lib\SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
socket.error: (10013, 'Permission denied')
</code></pre>
<p>I tried to start up the Google App Engine development server and received this error the first time I tried to run it. Any ideas? I'm new to python.</p>
| 10
|
2009-02-15T00:12:53Z
| 4,505,094
|
<p>I am assuming your are using the default port assigned by gae sdk so you might want to ensure that it is not used by any other programs.</p>
| 0
|
2010-12-22T00:01:43Z
|
[
"python",
"sockets",
"permissions"
] |
What causes Python socket error?
| 550,032
|
<pre><code> File "C:\Python25\lib\SocketServer.py", line 330, in __init__
self.server_bind()
File "C:\Python25\lib\BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python25\lib\SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
socket.error: (10013, 'Permission denied')
</code></pre>
<p>I tried to start up the Google App Engine development server and received this error the first time I tried to run it. Any ideas? I'm new to python.</p>
| 10
|
2009-02-15T00:12:53Z
| 39,647,858
|
<p>run it as follow. This should work</p>
<pre><code>python -m 8888
</code></pre>
<p>if this does not work. Try other numbers like 8080.</p>
| 0
|
2016-09-22T19:57:26Z
|
[
"python",
"sockets",
"permissions"
] |
Removing the TK icon on a Tkinter window
| 550,050
|
<p>Does anybody know how to make the icon not show up? I'm looking for a way to have no icon at all.</p>
| 16
|
2009-02-15T00:27:10Z
| 550,071
|
<p>As far as I know, the closest you will get to a "blank" icon is using one that's the same color as the window title bar. But then again a lot of users use different color themes, so it won't go over very well.</p>
<p>However if you use py2exe you can use something like <a href="http://angusj.com/resourcehacker/" rel="nofollow">Resource Hacker</a> to swap the icon. But in the python programs text state, the best you can do is replace. Sort of how Jar files use the java icon, tkinter apps will have the TK icon. After all...like java, your app is being translated by an intermediate program. Since another program is running your code, you have to modify that other program. Luckily python/tk is a bit more flexible than the JVM in terms of icons so you can replace the icon. But removing it entirely isn't currently an option.</p>
<p>-John</p>
| 1
|
2009-02-15T00:38:56Z
|
[
"python",
"python-3.x",
"tkinter",
"tk"
] |
Removing the TK icon on a Tkinter window
| 550,050
|
<p>Does anybody know how to make the icon not show up? I'm looking for a way to have no icon at all.</p>
| 16
|
2009-02-15T00:27:10Z
| 754,736
|
<h3>On Windows</h3>
<p><strong>Step One:</strong></p>
<p>Create a transparent icon using either an icon editor, or a site like <a href="http://www.rw-designer.com/online_icon_maker.php" rel="nofollow">rw-designer</a>. Save it as <code>transparent.ico</code>.</p>
<p><strong>Step Two:</strong></p>
<pre><code>from tkinter import *
tk = Tk()
tk.iconbitmap(default='transparent.ico')
lab = Label(tk, text='Window with transparent icon.')
lab.pack()
tk.mainloop()
</code></pre>
<h3>On Unix</h3>
<p>Something similar, but using an <code>xbm</code> icon. </p>
| 30
|
2009-04-16T04:11:48Z
|
[
"python",
"python-3.x",
"tkinter",
"tk"
] |
Removing the TK icon on a Tkinter window
| 550,050
|
<p>Does anybody know how to make the icon not show up? I'm looking for a way to have no icon at all.</p>
| 16
|
2009-02-15T00:27:10Z
| 18,277,350
|
<p>Similar to the accepted answer (with the con of being uglier):</p>
<pre><code>import tkinter
import tempfile
ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64
_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, 'wb') as icon_file:
icon_file.write(ICON)
tk = tkinter.Tk()
tk.iconbitmap(default=ICON_PATH)
label = tkinter.Label(tk, text="Window with transparent icon.")
label.pack()
tk.mainloop()
</code></pre>
<p>It just creates the file on the fly instead, so you don't have to carry an extra file around. Using the same method, you could also do an '.xbm' icon for Unix.</p>
<p>Edit: The <code>ICON</code> can be shortened even further thanks to <a href="http://stackoverflow.com/a/29509705/1546993">@Magnus Hoff</a>:</p>
<pre><code>import base64, zlib
ICON = zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy'
'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))
</code></pre>
| 5
|
2013-08-16T15:48:34Z
|
[
"python",
"python-3.x",
"tkinter",
"tk"
] |
Removing the TK icon on a Tkinter window
| 550,050
|
<p>Does anybody know how to make the icon not show up? I'm looking for a way to have no icon at all.</p>
| 16
|
2009-02-15T00:27:10Z
| 37,566,507
|
<p>Based on previous responses i used this solution:</p>
<pre><code>from PIL import ImageTk
import zlib,base64
import Tkinter
icon=zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy'
'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))
root=Tkinter.Tk()
image=ImageTk.PhotoImage(data=icon)
root.tk.call('wm', 'iconphoto', root._w, image)
root.mainloop()
</code></pre>
| 0
|
2016-06-01T10:47:50Z
|
[
"python",
"python-3.x",
"tkinter",
"tk"
] |
Does python have something like C++'s using keyword?
| 550,148
|
<p>In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example: </p>
<pre><code>void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>becomes</p>
<pre><code>void foo()
{
using namespace std; // limited in scope to foo
vector< map <int, string> > crazyVector;
cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>Does something similar exist for python, or do I have to fully qualify everything?</p>
<p>I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope. </p>
| 6
|
2009-02-15T01:50:34Z
| 550,156
|
<pre><code>import X
</code></pre>
<p>or</p>
<pre><code>from X import *
</code></pre>
<p>or </p>
<pre><code>from X import a, b, c
</code></pre>
<p>Where X is the Python module you want to use.</p>
<p>It would be helpful for you to give us a Python code sample that you think needs cleaned up.</p>
| 6
|
2009-02-15T01:54:18Z
|
[
"python",
"namespaces",
"using"
] |
Does python have something like C++'s using keyword?
| 550,148
|
<p>In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example: </p>
<pre><code>void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>becomes</p>
<pre><code>void foo()
{
using namespace std; // limited in scope to foo
vector< map <int, string> > crazyVector;
cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>Does something similar exist for python, or do I have to fully qualify everything?</p>
<p>I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope. </p>
| 6
|
2009-02-15T01:50:34Z
| 550,160
|
<p>Sure, python's dynamism makes this trivial. If you had a class buried deep in a namespace: foo.bar.baz.blah, you can do:</p>
<pre><code>def foo:
f = foo.bar.baz.blah
f1 = f()
</code></pre>
| 5
|
2009-02-15T01:56:14Z
|
[
"python",
"namespaces",
"using"
] |
Does python have something like C++'s using keyword?
| 550,148
|
<p>In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example: </p>
<pre><code>void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>becomes</p>
<pre><code>void foo()
{
using namespace std; // limited in scope to foo
vector< map <int, string> > crazyVector;
cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>Does something similar exist for python, or do I have to fully qualify everything?</p>
<p>I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope. </p>
| 6
|
2009-02-15T01:50:34Z
| 550,161
|
<p>As Bill said, Python does have the construction</p>
<pre><code>from X import *
</code></pre>
<p>but you can also explicitly specify which names you want imported from the module (namespace):</p>
<pre><code>from X import foo, bar, blah
</code></pre>
<p>This tends to make the code even more readable/easier to understand, since someone seeing an identifier in the source doesn't need to hunt through all imported modules to see where it comes from. Here's a related question: <a href="http://stackoverflow.com/questions/539578/namespace-specification-in-absence-of-ambuguity">http://stackoverflow.com/questions/539578/namespace-specification-in-absence-of-ambuguity</a></p>
<p><em>EDIT</em>: in response to Pax's comment, I'll mention that you can also write things like</p>
<pre><code>import X.foo
</code></pre>
<p>but then you'll need to write</p>
<pre><code>X.foo.moo()
</code></pre>
<p>instead of just</p>
<pre><code>foo.moo()
</code></pre>
<p>This is not necessarily a bad thing, of course. I usually use a mixture of the <code>from X import y</code> and <code>import X.y</code> forms, whatever I feel makes my code clearest. It's certainly a subjective thing to some extent.</p>
| 17
|
2009-02-15T01:58:04Z
|
[
"python",
"namespaces",
"using"
] |
Does python have something like C++'s using keyword?
| 550,148
|
<p>In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example: </p>
<pre><code>void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>becomes</p>
<pre><code>void foo()
{
using namespace std; // limited in scope to foo
vector< map <int, string> > crazyVector;
cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>Does something similar exist for python, or do I have to fully qualify everything?</p>
<p>I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope. </p>
| 6
|
2009-02-15T01:50:34Z
| 550,367
|
<p>Note that </p>
<pre><code>from foo import bar
</code></pre>
<p>works even if <code>bar</code> is a module in the <code>foo</code> package. This lets you limit your namespace pollution without having to name each function/class in <code>foo.bar</code> that you might care to use. It also aids readers of your code, because they'll see a call to <code>bar.baz()</code> and have a better idea where <code>baz</code> came from.</p>
| 0
|
2009-02-15T05:23:17Z
|
[
"python",
"namespaces",
"using"
] |
Does python have something like C++'s using keyword?
| 550,148
|
<p>In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example: </p>
<pre><code>void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>becomes</p>
<pre><code>void foo()
{
using namespace std; // limited in scope to foo
vector< map <int, string> > crazyVector;
cout << crazyVector[0].begin()->first;
}
</code></pre>
<p>Does something similar exist for python, or do I have to fully qualify everything?</p>
<p>I'll add the disclaimer that I know that using has its pitfalls and it should be appropriately limited in scope. </p>
| 6
|
2009-02-15T01:50:34Z
| 8,754,770
|
<p>In addition to David's answer:</p>
<ol>
<li>One should use round brackets in <code>from X import (foo, bar, blah)</code> for a sake of <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>. </li>
<li>Full syntax allows renaming (rebinding) package names to their new identifiers within the scope of the current module as in <code>from foo import bar as baz</code>.</li>
</ol>
<p>I recommend to look up the manual for the <a href="http://docs.python.org/reference/simple_stmts.html#import" rel="nofollow">import keyword</a>, the <code>__import__</code> built-in and explanation for <strong>sys.modules</strong> as further reading.</p>
| 1
|
2012-01-06T07:35:28Z
|
[
"python",
"namespaces",
"using"
] |
Django Model API reverse lookup of many to many relationship through intermediary table
| 550,300
|
<p>I have a Resident and can not seem to get the set of SSA's the resident belongs to. I've tried <code>res.ssa_set.all()</code> <code>.ssas_set.all()</code> and <code>.ssa_resident_set.all()</code>. Can't seem to manage it. What's the syntax for a reverse m2m lookup through another table? </p>
<p>EDIT: I'm getting an 'QuerySet as no attribute' error. Erm?</p>
<pre><code>class SSA(models.Model):
name = models.CharField(max_length=100)
cost_center = models.IntegerField(max_length=4)
street_num = models.CharField(max_length=9)
street_name = models.CharField(max_length=40)
suburb = models.CharField(max_length=40)
post_code = models.IntegerField(max_length=4, blank=True, null=True)
def __unicode__(self):
return self.name
class Resident(models.Model):
cris_id = models.CharField(max_length=10, primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
ssas = models.ManyToManyField('SSA', through='SSA_Resident', verbose_name="SSAs")
def __unicode__(self):
return self._get_full_name()
def _get_full_name(self):
return u"%s %s" %(self.first_name, self.last_name)
full_name = property(_get_full_name)
class SSA_Resident(models.Model):
id = models.AutoField(primary_key=True)
resident = models.ForeignKey('Resident')
ssa = models.ForeignKey('SSA', verbose_name="SSA")
active = models.BooleanField(default=True)
def __unicode__(self):
return u"%s - %s" %(self.resident.full_name, self.ssa.name)
</code></pre>
| 4
|
2009-02-15T04:03:13Z
| 550,308
|
<p>I was trying to evaluate a query set object, not the object itself. Executing a get on the query set and then a lookup of the relation set worked fine. I'm changing to community wiki and leaving this here just incase someone else is as stupid as I was.</p>
<p>A working example:</p>
<pre><code>resident = Resident.objects.filter(name='Johnny')
resident.ssa_set.all() # fail
resident = resident.get() # will fail if more than one returned by filter
resident.ssa_set.all() # works, since we're operating on an instance, not a queryset
</code></pre>
| 1
|
2009-02-15T04:07:41Z
|
[
"python",
"django",
"django-models",
"many-to-many"
] |
How can I provide safety template for user to modify with python?
| 550,337
|
<p>I am building a multi-user web application. Each user can have their own site under my application. I am considering how to allow user to modify template without security problem? I have evaluated some python template engine. For example, genshi, it is a pretty wonderful template engine, but however it might be dangerous to allow user to modify genshi template. It have a syntax like this:</p>
<pre><code><?python
?>
</code></pre>
<p>This syntax allow you run whatever you want python can do. I notice that it seems can be shutdown by passing some parameter. But there are still a lots of potential problems. For example, user can access build-in functions, and methods of passed variables. For example, if I pass a ORM object to template. It might contain some method and variable that I don't want to allow user touch it. May like this:</p>
<pre><code>site.metadata.connection.execute("drop table xxx")
</code></pre>
<p>So my question is how can I allow user to modify template of their site without security problems? Any python template engine can be used.</p>
<p>Thanks.</p>
| 0
|
2009-02-15T04:44:31Z
| 550,344
|
<p>The short answer is probably "you can't".</p>
<p>The best you can probably do is to trap the individual users in virtual machines or sandboxes.</p>
| -1
|
2009-02-15T04:49:51Z
|
[
"python",
"website",
"templates"
] |
How can I provide safety template for user to modify with python?
| 550,337
|
<p>I am building a multi-user web application. Each user can have their own site under my application. I am considering how to allow user to modify template without security problem? I have evaluated some python template engine. For example, genshi, it is a pretty wonderful template engine, but however it might be dangerous to allow user to modify genshi template. It have a syntax like this:</p>
<pre><code><?python
?>
</code></pre>
<p>This syntax allow you run whatever you want python can do. I notice that it seems can be shutdown by passing some parameter. But there are still a lots of potential problems. For example, user can access build-in functions, and methods of passed variables. For example, if I pass a ORM object to template. It might contain some method and variable that I don't want to allow user touch it. May like this:</p>
<pre><code>site.metadata.connection.execute("drop table xxx")
</code></pre>
<p>So my question is how can I allow user to modify template of their site without security problems? Any python template engine can be used.</p>
<p>Thanks.</p>
| 0
|
2009-02-15T04:44:31Z
| 550,364
|
<p>Look at <a href="http://docs.djangoproject.com/en/dev/topics/templates/#topics-templates" rel="nofollow">Django templte engine</a>. It does not support execution of arbitrary python code and all accessible variables must be passed into template explicity. This should be pretty good foundation for building user-customizable pages. Beware that you'll still need to handle occasional syntax errors from your users.</p>
| 1
|
2009-02-15T05:18:01Z
|
[
"python",
"website",
"templates"
] |
How can I provide safety template for user to modify with python?
| 550,337
|
<p>I am building a multi-user web application. Each user can have their own site under my application. I am considering how to allow user to modify template without security problem? I have evaluated some python template engine. For example, genshi, it is a pretty wonderful template engine, but however it might be dangerous to allow user to modify genshi template. It have a syntax like this:</p>
<pre><code><?python
?>
</code></pre>
<p>This syntax allow you run whatever you want python can do. I notice that it seems can be shutdown by passing some parameter. But there are still a lots of potential problems. For example, user can access build-in functions, and methods of passed variables. For example, if I pass a ORM object to template. It might contain some method and variable that I don't want to allow user touch it. May like this:</p>
<pre><code>site.metadata.connection.execute("drop table xxx")
</code></pre>
<p>So my question is how can I allow user to modify template of their site without security problems? Any python template engine can be used.</p>
<p>Thanks.</p>
| 0
|
2009-02-15T04:44:31Z
| 550,369
|
<p>In rails there's something called <a href="http://www.liquidmarkup.org/" rel="nofollow">liquid</a>. You might take a look at that to get some ideas. Another idea: at the very least, one thing you <em>could</em> do is to convert your objects into simple dictionary - something like a json representation, and then pass to your template.</p>
| 0
|
2009-02-15T05:25:28Z
|
[
"python",
"website",
"templates"
] |
How can I provide safety template for user to modify with python?
| 550,337
|
<p>I am building a multi-user web application. Each user can have their own site under my application. I am considering how to allow user to modify template without security problem? I have evaluated some python template engine. For example, genshi, it is a pretty wonderful template engine, but however it might be dangerous to allow user to modify genshi template. It have a syntax like this:</p>
<pre><code><?python
?>
</code></pre>
<p>This syntax allow you run whatever you want python can do. I notice that it seems can be shutdown by passing some parameter. But there are still a lots of potential problems. For example, user can access build-in functions, and methods of passed variables. For example, if I pass a ORM object to template. It might contain some method and variable that I don't want to allow user touch it. May like this:</p>
<pre><code>site.metadata.connection.execute("drop table xxx")
</code></pre>
<p>So my question is how can I allow user to modify template of their site without security problems? Any python template engine can be used.</p>
<p>Thanks.</p>
| 0
|
2009-02-15T04:44:31Z
| 550,438
|
<p>Jinja2 is a Django-ish templating system that has a sandboxing feature. I've never attempted to use the sandboxing, but I quite like Jinja2 as an alternative to Django's templates. It still promotes separation of template from business logic, but has more Pythonic calling conventions, namespacing, etc. </p>
<p><a href="http://jinja.pocoo.org/2/documentation/sandbox" rel="nofollow">Jinja2 Sandbox</a></p>
| 4
|
2009-02-15T06:56:10Z
|
[
"python",
"website",
"templates"
] |
py2exe to generate dlls?
| 550,446
|
<p>Is there a way using py2exe or some other method to generate dll files instead of exe files?</p>
<p>I would want to basically create a normal win32 dll with normal functions but these functions would be coded in python instead of c++.</p>
| 10
|
2009-02-15T07:06:26Z
| 550,472
|
<p>I am not aware of <code>py2exe</code> being able to do that, as I believe that it does not actually make object symbols out of your Python code, but just embeds the compiled byte-code in an executable with the Python runtime).</p>
<p>Creating a native library may require a bit more work (to define the C/C++ interface to things) with the Python-C API. It may be somewhat easier using <a href="http://elmer.sourceforge.net/" rel="nofollow">Elmer</a> for that.</p>
| 4
|
2009-02-15T07:27:15Z
|
[
"python",
"windows",
"dll",
"py2exe"
] |
py2exe to generate dlls?
| 550,446
|
<p>Is there a way using py2exe or some other method to generate dll files instead of exe files?</p>
<p>I would want to basically create a normal win32 dll with normal functions but these functions would be coded in python instead of c++.</p>
| 10
|
2009-02-15T07:06:26Z
| 551,368
|
<p>I doubt that py2exe does this, as it's architectured around providing a bootstrapping .exe that rolls out the python interpreter and runs it.</p>
<p>But why not just embed Python in C code, and compile that code as a DLL?</p>
| 4
|
2009-02-15T18:36:51Z
|
[
"python",
"windows",
"dll",
"py2exe"
] |
py2exe to generate dlls?
| 550,446
|
<p>Is there a way using py2exe or some other method to generate dll files instead of exe files?</p>
<p>I would want to basically create a normal win32 dll with normal functions but these functions would be coded in python instead of c++.</p>
| 10
|
2009-02-15T07:06:26Z
| 598,780
|
<p>I think you could solve this by doing some hacking:</p>
<ul>
<li>Take a look at the zipextimporter module in py2exe . It helps with importing pyd-files from a zip. </li>
<li>Using that, you might be able to load py2exe's output file in your own app/dll using raw python-api. (Use boost::python if you can and want)</li>
<li>And, since py2exe's outputfile is a zip, you could attach it at the end of your dll, making the whole thing even more integrated. (Old trick that works with jar-files too.)</li>
</ul>
<p>Not tested, but I think the theory is sound. </p>
<p>Essentially, you reimplement py2exe's output executable's main() in your dll.</p>
| 6
|
2009-02-28T22:13:25Z
|
[
"python",
"windows",
"dll",
"py2exe"
] |
py2exe to generate dlls?
| 550,446
|
<p>Is there a way using py2exe or some other method to generate dll files instead of exe files?</p>
<p>I would want to basically create a normal win32 dll with normal functions but these functions would be coded in python instead of c++.</p>
| 10
|
2009-02-15T07:06:26Z
| 24,002,701
|
<p>It looks like it is possible to generate a COM DLL from py2exe:</p>
<p><a href="http://www.py2exe.org/index.cgi/Py2exeAndCtypesComDllServer" rel="nofollow">http://www.py2exe.org/index.cgi/Py2exeAndCtypesComDllServer</a></p>
<pre><code> 23 my_com_server_target = Target(
24 description = "my com server",
25 # use module name for ctypes.com dll server
26 modules = ["dir.my_com_server"],
27 # the following line embeds the typelib within the dll
28 other_resources = [("TYPELIB", 1, open(r"dir\my_com_server.tlb", "rb").read())],
29 # we only want the inproc (dll) server
30 create_exe = False
31 )
</code></pre>
| 0
|
2014-06-02T20:27:03Z
|
[
"python",
"windows",
"dll",
"py2exe"
] |
py2exe to generate dlls?
| 550,446
|
<p>Is there a way using py2exe or some other method to generate dll files instead of exe files?</p>
<p>I would want to basically create a normal win32 dll with normal functions but these functions would be coded in python instead of c++.</p>
| 10
|
2009-02-15T07:06:26Z
| 26,163,024
|
<p>For posterity, I was able to use <a href="https://wiki.python.org/moin/elmer" rel="nofollow">Elmer</a> to successfully generate a usable DLL recently. Their site <a href="http://elmer.sourceforge.net/examples.html" rel="nofollow">has an example of building a DLL wrapper that loads python code</a>. It is pretty cool because you can change the python code on the fly to change the DLL behavior for debugging.</p>
<p>Unfortunately, for me, I wanted a portable DLL that would work without installing python. That part didn't didn't quite work out of the box. Rather than repeating all the steps, here is a link to the answer with the steps I took: <a href="http://stackoverflow.com/a/24811840/3841168">http://stackoverflow.com/a/24811840/3841168</a>.
I did have to distribute python27.dll, elmer.dll and a couple of .pyd's along with my .dll; an appropriated .net runtime was also needed since the python27.dll is not usually statically linked. There may be some way around including a boatload of dll's, but I didn't mind distributing multiple DLLs, so I didn't dig into it too much.</p>
| 1
|
2014-10-02T14:25:54Z
|
[
"python",
"windows",
"dll",
"py2exe"
] |
Quick primer on implementing a COM object that implement some custom IDLs in python?
| 550,450
|
<p>Does anyone have experience using python to create a COM object that implements some custom IDLs? </p>
<p>Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?</p>
| 0
|
2009-02-15T07:08:18Z
| 550,466
|
<p>The tutorial you are looking for is in the <a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">Python Programming On Win32</a> book, by Mark Hammond and Andy Robinson. A bit old, and the COM object creation info is distributed across some chapters.</p>
<p>A more recent example, <a href="http://techarttiki.blogspot.com/2008/03/calling-python-from-maxscript.html" rel="nofollow">simple COM server using Python</a>, can give you a quick start.</p>
| 3
|
2009-02-15T07:25:01Z
|
[
"python",
"com"
] |
Quick primer on implementing a COM object that implement some custom IDLs in python?
| 550,450
|
<p>Does anyone have experience using python to create a COM object that implements some custom IDLs? </p>
<p>Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?</p>
| 0
|
2009-02-15T07:08:18Z
| 550,666
|
<p>There is also <a href="http://pypi.python.org/pypi/comtypes" rel="nofollow">comtypes</a>, which allows to access and implement custom interfaces. An article on <a href="http://www.codeproject.com/KB/COM/python-comtypes-interop.aspx" rel="nofollow">codeproject</a> has a nice tutorial.</p>
| 2
|
2009-02-15T10:31:59Z
|
[
"python",
"com"
] |
Quick primer on implementing a COM object that implement some custom IDLs in python?
| 550,450
|
<p>Does anyone have experience using python to create a COM object that implements some custom IDLs? </p>
<p>Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?</p>
| 0
|
2009-02-15T07:08:18Z
| 831,096
|
<p>You should also check <a href="http://oreilly.com/catalog/pythonwin32/chapter/ch12.html" rel="nofollow">Advance COM</a> a free chapter from Python Programming On Win32 mentioned by gimel.</p>
| 1
|
2009-05-06T18:46:01Z
|
[
"python",
"com"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.