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 |
|---|---|---|---|---|---|---|---|---|---|
What's wrong with my Python SOAPpy webservice call?
| 679,302
|
<p>I am playing around trying to call a simple SOAP webservice using the following code in the Python interpreter:</p>
<pre><code>from SOAPpy import WSDL
wsdl = "http://www.webservicex.net/whois.asmx?wsdl"
proxy = WSDL.Proxy(wsdl)
proxy.soapproxy.config.dumpSOAPOut=1
proxy.soapproxy.config.dumpSOAPIn=1
proxy.GetWhoIS(HostName="google.com")
</code></pre>
<p>(Yep, I'm new to Python, doing the diveintopython thing...)</p>
<p>The call to the GetWhoIS method fails - otherwise I wouldn't be asking here, I guess.
Here's my outgoing SOAP:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<GetWhoIS SOAP-ENC:root="1">
<HostName xsi:type="xsd:string">google.com</HostName>
</GetWhoIS>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>And here's the incoming response.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>
System.Web.Services.Protocols.SoapException:
Server was unable to process request. ---&gt;
System.ArgumentNullException: Value cannot be null.
at whois.whois.GetWhoIS(String HostName)
--- End of inner exception stack trace ---
</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>(manually formatted for easier reading)</p>
<p>Can anyone tell me what am I doing wrong? </p>
<p>Ideally both in terms of use of SOAPpy, and why the SOAP message is incorrect.</p>
<p>Thanks!</p>
| 1
|
2009-03-24T21:23:21Z
| 679,464
|
<p>Your call seems all right to me, i think this could be a soappy problem or misconfigured server (although i have not checked this thoroughly).</p>
<p>This document also suggests incompatibilities between soappy and webservicex.net:
<a href="http://users.jyu.fi/~mweber/teaching/ITKS545/exercises/ex5.pdf" rel="nofollow">http://users.jyu.fi/~mweber/teaching/ITKS545/exercises/ex5.pdf</a></p>
<p>How i would work around this in this specific case?</p>
<pre><code>import urllib
url_handle = urllib.urlopen( "http://www.webservicex.net/whois.asmx/GetWhoIS?HostName=%s" \
% ("www.google.com") )
print url_handle.read()
</code></pre>
| 3
|
2009-03-24T22:12:05Z
|
[
"python",
"wsdl",
"soappy"
] |
What's wrong with my Python SOAPpy webservice call?
| 679,302
|
<p>I am playing around trying to call a simple SOAP webservice using the following code in the Python interpreter:</p>
<pre><code>from SOAPpy import WSDL
wsdl = "http://www.webservicex.net/whois.asmx?wsdl"
proxy = WSDL.Proxy(wsdl)
proxy.soapproxy.config.dumpSOAPOut=1
proxy.soapproxy.config.dumpSOAPIn=1
proxy.GetWhoIS(HostName="google.com")
</code></pre>
<p>(Yep, I'm new to Python, doing the diveintopython thing...)</p>
<p>The call to the GetWhoIS method fails - otherwise I wouldn't be asking here, I guess.
Here's my outgoing SOAP:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<GetWhoIS SOAP-ENC:root="1">
<HostName xsi:type="xsd:string">google.com</HostName>
</GetWhoIS>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>And here's the incoming response.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>
System.Web.Services.Protocols.SoapException:
Server was unable to process request. ---&gt;
System.ArgumentNullException: Value cannot be null.
at whois.whois.GetWhoIS(String HostName)
--- End of inner exception stack trace ---
</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>(manually formatted for easier reading)</p>
<p>Can anyone tell me what am I doing wrong? </p>
<p>Ideally both in terms of use of SOAPpy, and why the SOAP message is incorrect.</p>
<p>Thanks!</p>
| 1
|
2009-03-24T21:23:21Z
| 679,581
|
<p>As mentioned by @ChristopheD, SOAPpy seems to be buggy for certain configurations of WDSL.</p>
<p>I tried using suds (sudo easy_install suds on Ubuntu) instead, worked first time.</p>
<pre><code>from suds.client import Client
client = Client('http://www.webservicex.net/whois.asmx?wsdl')
client.service.run_GetWhoIS(HostName="google.com")
</code></pre>
<p>Job's a good 'un.</p>
| 2
|
2009-03-24T22:56:40Z
|
[
"python",
"wsdl",
"soappy"
] |
What's wrong with my Python SOAPpy webservice call?
| 679,302
|
<p>I am playing around trying to call a simple SOAP webservice using the following code in the Python interpreter:</p>
<pre><code>from SOAPpy import WSDL
wsdl = "http://www.webservicex.net/whois.asmx?wsdl"
proxy = WSDL.Proxy(wsdl)
proxy.soapproxy.config.dumpSOAPOut=1
proxy.soapproxy.config.dumpSOAPIn=1
proxy.GetWhoIS(HostName="google.com")
</code></pre>
<p>(Yep, I'm new to Python, doing the diveintopython thing...)</p>
<p>The call to the GetWhoIS method fails - otherwise I wouldn't be asking here, I guess.
Here's my outgoing SOAP:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<GetWhoIS SOAP-ENC:root="1">
<HostName xsi:type="xsd:string">google.com</HostName>
</GetWhoIS>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>And here's the incoming response.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>
System.Web.Services.Protocols.SoapException:
Server was unable to process request. ---&gt;
System.ArgumentNullException: Value cannot be null.
at whois.whois.GetWhoIS(String HostName)
--- End of inner exception stack trace ---
</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>(manually formatted for easier reading)</p>
<p>Can anyone tell me what am I doing wrong? </p>
<p>Ideally both in terms of use of SOAPpy, and why the SOAP message is incorrect.</p>
<p>Thanks!</p>
| 1
|
2009-03-24T21:23:21Z
| 1,501,307
|
<p>For some reason the client is sending the request using an outdated form that is almost never used anymore ("SOAP Section 5 encoding"). You can tell based on this:</p>
<pre><code>SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
</code></pre>
<p>But based on the WSDL, the service only accepts regular SOAP messages. So, most likely something is wrong in the WSDL parsing part of the SOAP library you are using.</p>
| 1
|
2009-10-01T00:15:26Z
|
[
"python",
"wsdl",
"soappy"
] |
What's wrong with my Python SOAPpy webservice call?
| 679,302
|
<p>I am playing around trying to call a simple SOAP webservice using the following code in the Python interpreter:</p>
<pre><code>from SOAPpy import WSDL
wsdl = "http://www.webservicex.net/whois.asmx?wsdl"
proxy = WSDL.Proxy(wsdl)
proxy.soapproxy.config.dumpSOAPOut=1
proxy.soapproxy.config.dumpSOAPIn=1
proxy.GetWhoIS(HostName="google.com")
</code></pre>
<p>(Yep, I'm new to Python, doing the diveintopython thing...)</p>
<p>The call to the GetWhoIS method fails - otherwise I wouldn't be asking here, I guess.
Here's my outgoing SOAP:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<GetWhoIS SOAP-ENC:root="1">
<HostName xsi:type="xsd:string">google.com</HostName>
</GetWhoIS>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>And here's the incoming response.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>
System.Web.Services.Protocols.SoapException:
Server was unable to process request. ---&gt;
System.ArgumentNullException: Value cannot be null.
at whois.whois.GetWhoIS(String HostName)
--- End of inner exception stack trace ---
</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>(manually formatted for easier reading)</p>
<p>Can anyone tell me what am I doing wrong? </p>
<p>Ideally both in terms of use of SOAPpy, and why the SOAP message is incorrect.</p>
<p>Thanks!</p>
| 1
|
2009-03-24T21:23:21Z
| 3,979,518
|
<p>Please check my answer to another question <a href="http://stackoverflow.com/questions/1768185/cant-call-a-webservice-method-using-soappy/2495261#2495261">here</a>. .net requires the soap action have the name space prepended.</p>
| 0
|
2010-10-20T15:26:19Z
|
[
"python",
"wsdl",
"soappy"
] |
Best way to profile/optimize a website on google's appengine
| 679,670
|
<p>I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.</p>
<p>Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler?</p>
| 15
|
2009-03-24T23:27:38Z
| 680,070
|
<p>The python site listed 3 profilers to choose from: <a href="http://docs.python.org/library/profile.html" rel="nofollow">http://docs.python.org/library/profile.html</a></p>
| 1
|
2009-03-25T02:59:14Z
|
[
"python",
"google-app-engine"
] |
Best way to profile/optimize a website on google's appengine
| 679,670
|
<p>I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.</p>
<p>Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler?</p>
| 15
|
2009-03-24T23:27:38Z
| 680,832
|
<p>I have found <a href="http://code.google.com/p/jrfonseca/wiki/Gprof2Dot" rel="nofollow">Gprof2Dot</a> extremely useful. The output of the profiling modules I've tried as pretty unintuitive to interpret.</p>
<p>Gprof2Dot turns the cProfile output into a pretty looking graph, with the slowest chain(?) highlighted, and a bit of information on each function (function name, percentage of time spend on this function, and number of calls).</p>
<p><a href="http://jrfonseca.googlecode.com/svn/wiki/gprof2dot.png" rel="nofollow">An example graph (1429x1896px)</a></p>
<p>I've not done much with the App Engine, but when profiling non-webapp scripts, I tend to profile the script that runs all the unittests, which may not be very accurate to real-world situations</p>
<p>One (better?) method would be to have a script that does a fake WSGI request, then profile that.</p>
<p>WSGI is really simple protocol, it's basically a function that takes two arguments, one with request info and the second with a callback function (which is used for setting headers, among other things). Perhaps something like the following (which is possible-working pseudo code)...</p>
<pre><code>class IndexHandler(webapp.RequestHandler):
"""Your site"""
def get(self):
self.response.out.write("hi")
if __name__ == '__main__':
application = webapp.WSGIApplication([
('.*', IndexHandler),
], debug=True)
# Start fake-request/profiling bit
urls = [
"/",
"/blog/view/hello",
"/admin/post/edit/hello",
"/makeanerror404",
"/makeanerror500"
]
def fake_wsgi_callback(response, headers):
"""Prints heads to stdout"""
print("\n".join(["%s: %s" % (n, v) for n, v in headers]))
print("\n")
for request_url in urls:
html = application({
'REQUEST_METHOD': 'GET',
'PATH_INFO': request_url},
fake_wsgi_callback
)
print html
</code></pre>
<p>Actually, the App Engine documentation explains a better way of profiling your application:</p>
<p>From <a href="http://code.google.com/appengine/kb/commontasks.html#profiling" rel="nofollow">http://code.google.com/appengine/kb/commontasks.html#profiling</a>:</p>
<blockquote>
<p>To profile your application's performance, first rename your application's <code>main()</code> function to <code>real_main()</code>. Then, add a new main function to your application, named <code>profile_main()</code> such as the one below:</p>
<pre><code>def profile_main():
# This is the main function for profiling
# We've renamed our original main() above to real_main()
import cProfile, pstats
prof = cProfile.Profile()
prof = prof.runctx("real_main()", globals(), locals())
print "<pre>"
stats = pstats.Stats(prof)
stats.sort_stats("time") # Or cumulative
stats.print_stats(80) # 80 = how many to print
# The rest is optional.
# stats.print_callees()
# stats.print_callers()
print "</pre>"
</code></pre>
<p>[...]</p>
<p>To enable the profiling with your application, set <code>main = profile_main</code>. To run your application as normal, simply set <code>main = real_main</code>.</p>
</blockquote>
| 13
|
2009-03-25T09:24:50Z
|
[
"python",
"google-app-engine"
] |
Best way to profile/optimize a website on google's appengine
| 679,670
|
<p>I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.</p>
<p>Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler?</p>
| 15
|
2009-03-24T23:27:38Z
| 1,079,870
|
<p>In case anyone is coming here late, check out <a href="http://firepython.binaryage.com/" rel="nofollow">FirePython</a>, it will handle generating the dot graphs with gprof2dot serverside and you can view them in FireBug.</p>
| 1
|
2009-07-03T15:30:30Z
|
[
"python",
"google-app-engine"
] |
Best way to profile/optimize a website on google's appengine
| 679,670
|
<p>I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.</p>
<p>Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler?</p>
| 15
|
2009-03-24T23:27:38Z
| 1,995,848
|
<p>For profiling the API calls, Guido van Rossum released a library called Appstats that will record and display a lot of good stuff about your app.</p>
<p>You can get the library here: <a href="https://sites.google.com/site/appengineappstats/" rel="nofollow">https://sites.google.com/site/appengineappstats/</a></p>
<p>I wrote an article about it on my blog (with some screenshots): <a href="http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats" rel="nofollow">http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats</a></p>
<p><a href="http://blog.dantup.com/2010/01/profiling-google-app-engine-with-appstats" rel="nofollow"><img src="http://blog.dantup.com/pi/appstats_4_thumb.png" alt="Appstats"></a></p>
| 3
|
2010-01-03T18:44:41Z
|
[
"python",
"google-app-engine"
] |
Best way to profile/optimize a website on google's appengine
| 679,670
|
<p>I'm currently trying to optimize my website, which run on the google's appengine. It's not an easy task, because I'm not using any powerful tool.</p>
<p>Does anyone have experience in optimizing python code for this purpose?
Have you find a good python profiler?</p>
| 15
|
2009-03-24T23:27:38Z
| 6,809,225
|
<p><a href="https://github.com/kamens/gae_mini_profiler">App Engine Mini Profiler</a> is a new, drop-in app engine performance tool that gives both API call perf information (via Appstats) and standard profiling data for all function calls (via cProfiler)</p>
<p><a href="https://github.com/kamens/gae_mini_profiler">https://github.com/kamens/gae_mini_profiler</a></p>
| 8
|
2011-07-24T19:49:08Z
|
[
"python",
"google-app-engine"
] |
min heap in python
| 679,731
|
<p>I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap?</p>
| 9
|
2009-03-24T23:52:58Z
| 679,742
|
<p>Yes, there is a way. Define a wrapping class that implements your custom comparator, and use a list of those instead of a list of your actual objects. That's about the best there is while still using the heapq module, since it provides no key= or cmp= arguments like the sorting functions/methods do.</p>
<pre><code>def gen_wrapper(cmp):
class Wrapper(object):
def __init__(self, value): self.value = value
def __cmp__(self, obj): return cmp(self.value, obj.value)
return Wrapper
</code></pre>
| 12
|
2009-03-25T00:01:28Z
|
[
"python",
"object",
"heap",
"min-heap"
] |
min heap in python
| 679,731
|
<p>I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap?</p>
| 9
|
2009-03-24T23:52:58Z
| 679,831
|
<p>Two options (aside from Devin Jeanpierre's suggestion):</p>
<ol>
<li><p>Decorate your data before using the heap. This is the equivalent of the <code>key=</code> option to sorting. e.g. if you (for some reason) wanted to heapify a list of numbers according to their sine:</p>
<pre><code>data = [ # list of numbers ]
heap = [(math.sin(x), x) for x in data]
heapq.heapify(heap)
# get the min element
item = heappop(heap)[1]
</code></pre></li>
<li><p>The <code>heapq</code> module is implemented in pure python. You could just copy it to your working directory and change the relevant bits. From a quick look, you would have to modify siftdown() and siftup(), and possibly nlargest and nsmallest if you need them.</p></li>
</ol>
| 15
|
2009-03-25T00:49:56Z
|
[
"python",
"object",
"heap",
"min-heap"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 679,814
|
<p>Look very closely at SQLAlchemy.</p>
<p>You can test and develop with SQLite.</p>
<p>You can go into production with MySQL -- making essentially no changes to your applications.</p>
<p>The DB-API, while widely adhered-to, has enough flexibility that (1) you aren't insulated from SQL variation in the underlying RDBMS and (2) there are still DB driver-specific features that are hard to hide.</p>
<p>Another good ORM layer is the ORM that's part of <a href="http://docs.djangoproject.com/en/dev/topics/db/models/">Django</a>. You can (with a little effort) use just the Django ORM without using the rest of the Django web framework.</p>
<p>Use an ORM Layer (SQLAlchemy or SQLObject) in preference to DB-API.</p>
<p>Why? Your model should be a solid, clear, well-thought-out OO model. The relational mapping should come second after the object model. SQLAlchemy makes this a reasonable approach.</p>
<p>A "DB Abstraction Layer" will happen in the normal course of events. Indeed, because of DB-API (as used by SQLAlchemy) you gave two abstraction layers: ORM and DB-API.</p>
| 18
|
2009-03-25T00:40:50Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 679,819
|
<p>Accessing a proper database from Python is almost always done using a DB-API 2.0-compliant adapter module. While all DB-API modules have identical APIs (or very similar; not all backends support all features), if you are writing the SQL yourself, you will probably be writing SQL in a product-specific dialect, so they are not as interchangeable in practice as they are in theory.</p>
<p>Honestly, SQLite sounds perfect for your use case. I wouldn't bother with "embedded MySQL"; that sounds like the worst of both worlds. Whether you want an ORM like SQLAlchemy is completely up to you; there are good arguments either way. Personally, I dislike ORMs, but then I have a math degree, so the fact that I appreciate SQL as a language probably isn't too surprising :)</p>
| 4
|
2009-03-25T00:43:57Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 679,963
|
<p>CouchDB is not a relational database, so it doesn't have a DB-API interface. It's a document database which means it wouldn't be as useful for Gramps because it would require some contortions to identify links between related people. On top of that it can only run in client/server mode.</p>
<p>Any ORM like SQLAlchemy, SQLObject, or the Django ORM are implemented on top of DB-API and I recommend using any of these over direct DB-API because it can give Gramps the flexibility to run sqlite in embedded mode for local desktop users and then also share, sometime down the road, a Postgresql/MySQL database connection with a web based version of Gramps.</p>
| 2
|
2009-03-25T02:02:43Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 680,135
|
<p>I really like <a href="https://storm.canonical.com/" rel="nofollow">Storm</a>:</p>
<blockquote>
<p>Storm is an object-relational mapper
(ORM) for Python developed at
Canonical. The project has been in
development for more than a year for
use in Canonical projects such as
Launchpad, and has recently been
released as an open-source product.</p>
</blockquote>
<p>In my opinion, Storm is much easier to learn than SQLAlchemy. Is similar to Django's ORM.</p>
| 2
|
2009-03-25T03:33:36Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 680,845
|
<p>If your project will ever have any real complexity, stay away from ORMs.</p>
<p><a href="http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx" rel="nofollow">http://blogs.tedneward.com/2006/06/26/The+Vietnam+Of+Computer+Science.aspx</a></p>
| 0
|
2009-03-25T09:28:29Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 689,202
|
<p>When I started converting a legacy app to use an ORM I looked into SQLObject and SQLAlchemy. At first I went with SQLObject because it looked familiar (past Django experience) and SQLAlchemy seemed complicated. After about 2 hours I started to hit walls with SQLObject. I then looked at SQLAlchemy again and was instantly rewarded. Not only did it understand and map every weird table in the database, it even could do the even weirder lookups I had to do later!</p>
| 0
|
2009-03-27T10:19:44Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 7,248,704
|
<p>I think that CouchDB would be best choice for such project as Gramps.</p>
<p>Useful CouchDB features for Gramps:</p>
<ul>
<li><p>No schema, no migrations.</p></li>
<li><p>Support for storing files directly to database, for example family photos, etc.: <a href="http://guide.couchdb.org/draft/api.html#attachments" rel="nofollow">http://guide.couchdb.org/draft/api.html#attachments</a></p></li>
<li><p>Ubuntu supports CouchDB via desktop-couch and it is integrated with Ubuntu One for easy sharing or backuping: <a href="http://www.freedesktop.org/wiki/Specifications/desktopcouch" rel="nofollow">http://www.freedesktop.org/wiki/Specifications/desktopcouch</a></p></li>
<li><p>You can easily replicate couchdb databases, join them to one big database, etc...</p></li>
<li><p>couchDB is very flexible.</p></li>
</ul>
| 0
|
2011-08-30T19:29:10Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
What are the viable database abstraction layers for Python
| 679,806
|
<p>I'm starting to get involved in an open source project <a href="http://www.gramps-project.org/wiki/index.php?title=Main%5FPage">Gramps</a> which is exploring switching their backend from BSDDB to a relational database. Either SQLite or MySQL we haven't fully decided and may even try to do both in some limited capacity. I'm a professional developer but I'm new to python so I'm not that familiar with the current selection of tools/libraries. I've been tasked with researching DB Abstraction Layers. <a href="http://www.gramps-project.org/wiki/index.php?title=GEPS%5F010:%5FSQL%5FBackend">There is currently a wiki discussion going on to compare them.</a> An object relational mapper might be nice but isn't absolutely necessary. though I know that is usually synonymous with a DB Abstraction Layer. If an ORM is included ad hock queries have to be available without to much wrestling.</p>
<p>Right now the list includes:</p>
<p><a href="http://code.google.com/p/couchdb-python/">CouchDB</a>
I haven't yet looked into this.</p>
<p><a href="http://wiki.python.org/moin/DatabaseProgramming/">DB-API</a>
this seems to be a standard python api and each db creates their own module that uses it. Even BSDDB seems to have one written but I haven't fully explored it. are the modules interchangeable?</p>
<p><a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
This seems to be the most popular right now? but I have very limited exposure to the python world.</p>
<p><a href="http://www.sqlobject.org/">SQLObject</a>
I haven't yet looked into this.</p>
<p>So what are peoples views and suggestions on database abstraction layers for python?</p>
| 11
|
2009-03-25T00:34:50Z
| 16,901,868
|
<p>web2py has a database abstraction layer that can be used in a standalone manner. We switched between sqlite3, Microsoft SQL Server, Oracle and MySQL with zero code changes. Impressed.</p>
| 0
|
2013-06-03T16:54:42Z
|
[
"python",
"sql",
"mysql",
"database",
"sqlite"
] |
Problem with python curl while submitting file
| 679,966
|
<pre><code>#!/usr/bin/python
import pycurl
import re
import StringIO
#CONSTANTS
URL = "http://www.imagehost.org"
FILE = "/datos/poop1.jpg"
POST_DATA = [("a", "upload"), ("file[]", (pycurl.FORM_FILE, FILE))]
buffer = StringIO.StringIO()
c = pycurl.Curl()
c.setopt( c.URL, URL )
c.setopt( c.POST, 1 )
c.setopt( c.POSTFIELDS, POST_DATA )
##c.setopt( c.HTTPPOST, POST_DATA )
c.setopt( c.USERAGENT,'Curl')
c.setopt( c.WRITEFUNCTION, buffer.write)
c.setopt(pycurl.VERBOSE, 1)
c.perform()
c.close()
#c.setopt(c.PROXY, proxyHostAndPort)
#c.setopt(c.PROXYUSERPWD, proxyAuthentication)
parse = buffer.getvalue()
pattern = re.compile('/<td nowrap="nowrap">(.+)<\/td>\s*<td class="link"><input.+value="([^"]+)" \/><\/td>/i')
result = re.search(pattern, parse)
print result
</code></pre>
<p>The problem is in the way on how to do the post.</p>
<p>c.setopt( c.POSTFIELDS, POST_DATA ) does not accept lists, so what should I do instead of adding a list? </p>
<p>And c.setopt( c.HTTPPOST, POST_DATA ) drops :</p>
<pre><code>Traceback (most recent call last):
File "pymage", line 26, in <module>
c.perform() pycurl.error: (26, 'failed creating formpost data')
</code></pre>
<p>Update:</p>
<p>-----------------------------15758382912173403811539561297\r\nContent-Disposition: form-data; name="a"\r\n\r\nupload\r\n-----------------------------15758382912173403811539561297\r\nContent-Disposition: form-data; name="file[]"; filename="Datos_Pegados_0a17.jpg"\r\nContent-Type: image/jpeg\r\n\r\nÿÃÿà </p>
<p>That's what I get using tamper data.</p>
<p>Interesting part of the postfield:</p>
<p>form-data; name="a"\r\n\r\nupload\r\n</p>
<p>form-data; name="file[]"</p>
<p>So... you say the POST_DATA should be 'a=upload&file[]=FILE'?</p>
<p>Update2:</p>
<pre><code><form method="post" action="/" enctype="multipart/form-data" onsubmit="javascript:Upload(); return true;">
<input type="hidden" name="a" value="upload" />
<td class="left">File:</td>
td class="right"><input name="file[]" type="file" size="20" /></td>
</code></pre>
<p>That's the code... </p>
<p>Now it's working the form-data configuration, but it's not uploading the file I believe</p>
<p>c.setopt( c.POSTFIELDS, 'a=upload&file[]=/datos/poop1.jpg' )</p>
<p>I'm getting this:</p>
<pre><code>* About to connect() to www.imagehost.org port 80 (#0)
* Trying 74.63.87.74... * connected
* Connected to www.imagehost.org (74.63.87.74) port 80 (#0)
> POST / HTTP/1.1
User-Agent: Curl
Host: www.imagehost.org
Accept: */*
Content-Length: 32
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Date: Wed, 25 Mar 2009 06:53:49 GMT
< Content-Type: text/html
< Server: nginx/0.7.11
< Set-Cookie: userhash=7c09b97cc70c8c133c850a3e744b416e; expires=Thu, 25-Mar-2010 06:53:49 GMT; path=/; domain=.imagehost.org; httponly
<
* Connection #0 to host www.imagehost.org left intact
* Closing connection #0
</code></pre>
| 2
|
2009-03-25T02:03:46Z
| 680,307
|
<p>I believe the argument for <code>POSTFIELDS</code> needs to be a simple URL encoded string, for example:</p>
<pre><code>POST_DATA = 'a=foo&b=bar'
</code></pre>
<p>Next, I'm not sure about your FILE stuff. Check out <a href="http://curl.haxx.se/mail/curlpython-2007-03/0003.html" rel="nofollow">this mail message</a> for an example.</p>
| 1
|
2009-03-25T05:17:28Z
|
[
"python",
"upload",
"curl"
] |
Problem with python curl while submitting file
| 679,966
|
<pre><code>#!/usr/bin/python
import pycurl
import re
import StringIO
#CONSTANTS
URL = "http://www.imagehost.org"
FILE = "/datos/poop1.jpg"
POST_DATA = [("a", "upload"), ("file[]", (pycurl.FORM_FILE, FILE))]
buffer = StringIO.StringIO()
c = pycurl.Curl()
c.setopt( c.URL, URL )
c.setopt( c.POST, 1 )
c.setopt( c.POSTFIELDS, POST_DATA )
##c.setopt( c.HTTPPOST, POST_DATA )
c.setopt( c.USERAGENT,'Curl')
c.setopt( c.WRITEFUNCTION, buffer.write)
c.setopt(pycurl.VERBOSE, 1)
c.perform()
c.close()
#c.setopt(c.PROXY, proxyHostAndPort)
#c.setopt(c.PROXYUSERPWD, proxyAuthentication)
parse = buffer.getvalue()
pattern = re.compile('/<td nowrap="nowrap">(.+)<\/td>\s*<td class="link"><input.+value="([^"]+)" \/><\/td>/i')
result = re.search(pattern, parse)
print result
</code></pre>
<p>The problem is in the way on how to do the post.</p>
<p>c.setopt( c.POSTFIELDS, POST_DATA ) does not accept lists, so what should I do instead of adding a list? </p>
<p>And c.setopt( c.HTTPPOST, POST_DATA ) drops :</p>
<pre><code>Traceback (most recent call last):
File "pymage", line 26, in <module>
c.perform() pycurl.error: (26, 'failed creating formpost data')
</code></pre>
<p>Update:</p>
<p>-----------------------------15758382912173403811539561297\r\nContent-Disposition: form-data; name="a"\r\n\r\nupload\r\n-----------------------------15758382912173403811539561297\r\nContent-Disposition: form-data; name="file[]"; filename="Datos_Pegados_0a17.jpg"\r\nContent-Type: image/jpeg\r\n\r\nÿÃÿà </p>
<p>That's what I get using tamper data.</p>
<p>Interesting part of the postfield:</p>
<p>form-data; name="a"\r\n\r\nupload\r\n</p>
<p>form-data; name="file[]"</p>
<p>So... you say the POST_DATA should be 'a=upload&file[]=FILE'?</p>
<p>Update2:</p>
<pre><code><form method="post" action="/" enctype="multipart/form-data" onsubmit="javascript:Upload(); return true;">
<input type="hidden" name="a" value="upload" />
<td class="left">File:</td>
td class="right"><input name="file[]" type="file" size="20" /></td>
</code></pre>
<p>That's the code... </p>
<p>Now it's working the form-data configuration, but it's not uploading the file I believe</p>
<p>c.setopt( c.POSTFIELDS, 'a=upload&file[]=/datos/poop1.jpg' )</p>
<p>I'm getting this:</p>
<pre><code>* About to connect() to www.imagehost.org port 80 (#0)
* Trying 74.63.87.74... * connected
* Connected to www.imagehost.org (74.63.87.74) port 80 (#0)
> POST / HTTP/1.1
User-Agent: Curl
Host: www.imagehost.org
Accept: */*
Content-Length: 32
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Date: Wed, 25 Mar 2009 06:53:49 GMT
< Content-Type: text/html
< Server: nginx/0.7.11
< Set-Cookie: userhash=7c09b97cc70c8c133c850a3e744b416e; expires=Thu, 25-Mar-2010 06:53:49 GMT; path=/; domain=.imagehost.org; httponly
<
* Connection #0 to host www.imagehost.org left intact
* Closing connection #0
</code></pre>
| 2
|
2009-03-25T02:03:46Z
| 4,943,261
|
<p>The pycurl documentation is not so clear on this, but the HTTPPOST option can take a list of tuples, each exactly two elements long. Each tuple's first argument is the form field name, the second is the value.</p>
<p>However, the value may be a tuple as well. This tuple must contains pairs of data relating to that field: ( form_option, option_value, form_option, option_value, etc., etc.)</p>
<p>For example, a multi-part form with three fields, the last being a file upload - we can set the filename and the mime type:</p>
<pre><code>c = pycurl.Curl()
c.setopt(c.URL, base_url + 'upload.cgi')
c.setopt(c.HTTPPOST,[ ("fieldname1", "value1"),
("fieldname2", "value2"),
("uploadfieldname",
(c.FORM_FILE, local_filename,
c.FORM_CONTENTTYPE, "application/x-gzip"))
])
</code></pre>
<p>You can find the options in the documentation for the C API for curl_formadd():
<a href="http://curl.haxx.se/libcurl/c/curl_formadd.html">http://curl.haxx.se/libcurl/c/curl_formadd.html</a>
however, from the pycurl source, it looks like only FORM_FILE, FORM_FILENAME, FORM_CONTENTTYPE and FORM_COPYCONTENTS are supported.</p>
| 6
|
2011-02-09T09:55:40Z
|
[
"python",
"upload",
"curl"
] |
Problem with python curl while submitting file
| 679,966
|
<pre><code>#!/usr/bin/python
import pycurl
import re
import StringIO
#CONSTANTS
URL = "http://www.imagehost.org"
FILE = "/datos/poop1.jpg"
POST_DATA = [("a", "upload"), ("file[]", (pycurl.FORM_FILE, FILE))]
buffer = StringIO.StringIO()
c = pycurl.Curl()
c.setopt( c.URL, URL )
c.setopt( c.POST, 1 )
c.setopt( c.POSTFIELDS, POST_DATA )
##c.setopt( c.HTTPPOST, POST_DATA )
c.setopt( c.USERAGENT,'Curl')
c.setopt( c.WRITEFUNCTION, buffer.write)
c.setopt(pycurl.VERBOSE, 1)
c.perform()
c.close()
#c.setopt(c.PROXY, proxyHostAndPort)
#c.setopt(c.PROXYUSERPWD, proxyAuthentication)
parse = buffer.getvalue()
pattern = re.compile('/<td nowrap="nowrap">(.+)<\/td>\s*<td class="link"><input.+value="([^"]+)" \/><\/td>/i')
result = re.search(pattern, parse)
print result
</code></pre>
<p>The problem is in the way on how to do the post.</p>
<p>c.setopt( c.POSTFIELDS, POST_DATA ) does not accept lists, so what should I do instead of adding a list? </p>
<p>And c.setopt( c.HTTPPOST, POST_DATA ) drops :</p>
<pre><code>Traceback (most recent call last):
File "pymage", line 26, in <module>
c.perform() pycurl.error: (26, 'failed creating formpost data')
</code></pre>
<p>Update:</p>
<p>-----------------------------15758382912173403811539561297\r\nContent-Disposition: form-data; name="a"\r\n\r\nupload\r\n-----------------------------15758382912173403811539561297\r\nContent-Disposition: form-data; name="file[]"; filename="Datos_Pegados_0a17.jpg"\r\nContent-Type: image/jpeg\r\n\r\nÿÃÿà </p>
<p>That's what I get using tamper data.</p>
<p>Interesting part of the postfield:</p>
<p>form-data; name="a"\r\n\r\nupload\r\n</p>
<p>form-data; name="file[]"</p>
<p>So... you say the POST_DATA should be 'a=upload&file[]=FILE'?</p>
<p>Update2:</p>
<pre><code><form method="post" action="/" enctype="multipart/form-data" onsubmit="javascript:Upload(); return true;">
<input type="hidden" name="a" value="upload" />
<td class="left">File:</td>
td class="right"><input name="file[]" type="file" size="20" /></td>
</code></pre>
<p>That's the code... </p>
<p>Now it's working the form-data configuration, but it's not uploading the file I believe</p>
<p>c.setopt( c.POSTFIELDS, 'a=upload&file[]=/datos/poop1.jpg' )</p>
<p>I'm getting this:</p>
<pre><code>* About to connect() to www.imagehost.org port 80 (#0)
* Trying 74.63.87.74... * connected
* Connected to www.imagehost.org (74.63.87.74) port 80 (#0)
> POST / HTTP/1.1
User-Agent: Curl
Host: www.imagehost.org
Accept: */*
Content-Length: 32
Content-Type: application/x-www-form-urlencoded
< HTTP/1.1 200 OK
< Transfer-Encoding: chunked
< Date: Wed, 25 Mar 2009 06:53:49 GMT
< Content-Type: text/html
< Server: nginx/0.7.11
< Set-Cookie: userhash=7c09b97cc70c8c133c850a3e744b416e; expires=Thu, 25-Mar-2010 06:53:49 GMT; path=/; domain=.imagehost.org; httponly
<
* Connection #0 to host www.imagehost.org left intact
* Closing connection #0
</code></pre>
| 2
|
2009-03-25T02:03:46Z
| 7,036,556
|
<p>Error 26 (in "pycurl.error: (26, 'failed creating formpost data')") means that the filename you specified to upload does not exist. I was running into this same error, and that was definitely the problem. See the curl source code for the location that it generates error 26.</p>
| 1
|
2011-08-12T06:50:18Z
|
[
"python",
"upload",
"curl"
] |
Python: How to extract variable name of a dictionary entry?
| 680,032
|
<p>I'm wondering how I would go about finding the variable name of a dictionary element:</p>
<p>For example:</p>
<pre><code> >>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
</code></pre>
<p>How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.</p>
<p>If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.</p>
<p>But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?</p>
<p>I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)</p>
<p>Any help is appreciated, thanks!</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name">python, can i print original var name?</a></li>
<li><a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python">How can you print a variable name in python?</a></li>
</ul>
<p><hr /></p>
<p>Update: Here's why I wanted this to work:</p>
<p>I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:</p>
<pre><code>dict_1={}
dict_2={}
dict_3={}
dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]
dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3
</code></pre>
<p>SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.</p>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<pre><code>WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>instead of having to do:</p>
<pre><code>dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'
</code></pre>
<p><hr /></p>
<p>Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.</p>
| 2
|
2009-03-25T02:36:07Z
| 680,051
|
<p>A variable name is just a name--it has no real meaning as far as the program is concerned, except as a convenience to the programmer (this isn't quite true in Python, but bear with me). As far as the Python interpreter is concerned, the name <code>dict1</code> is just the programmer's way of telling Python to look at memory address <code>0x1234</code>.</p>
<p>Furthermore, the very idea of turning a memory address (<code>0x1234</code>) back into a variable name (<code>dict1</code>) doesn't make sense, especially considering that more than one variable name can reference the same object:</p>
<pre><code>dict1 = {...}
dictCopy = dict1
</code></pre>
<p>Now <code>dictCopy</code> is just as much the name of the dictionary as <code>dict1</code> is--they both reference the same thing. If the function you're looking for existed, which name should Python choose?</p>
| 9
|
2009-03-25T02:47:39Z
|
[
"python",
"dictionary",
"variables",
"lookup"
] |
Python: How to extract variable name of a dictionary entry?
| 680,032
|
<p>I'm wondering how I would go about finding the variable name of a dictionary element:</p>
<p>For example:</p>
<pre><code> >>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
</code></pre>
<p>How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.</p>
<p>If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.</p>
<p>But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?</p>
<p>I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)</p>
<p>Any help is appreciated, thanks!</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name">python, can i print original var name?</a></li>
<li><a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python">How can you print a variable name in python?</a></li>
</ul>
<p><hr /></p>
<p>Update: Here's why I wanted this to work:</p>
<p>I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:</p>
<pre><code>dict_1={}
dict_2={}
dict_3={}
dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]
dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3
</code></pre>
<p>SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.</p>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<pre><code>WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>instead of having to do:</p>
<pre><code>dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'
</code></pre>
<p><hr /></p>
<p>Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.</p>
| 2
|
2009-03-25T02:36:07Z
| 680,101
|
<p>To add what zenazn said:</p>
<blockquote>
<p>But how can I turn that id back into a variable name?</p>
</blockquote>
<p>The short answer is that you don't want really want to. If you think you need to, there's something very wrong with the design of your program. If you told us more concretely what problem you were trying to solve, we could help you work out a better way to accomplish it.</p>
| 7
|
2009-03-25T03:11:28Z
|
[
"python",
"dictionary",
"variables",
"lookup"
] |
Python: How to extract variable name of a dictionary entry?
| 680,032
|
<p>I'm wondering how I would go about finding the variable name of a dictionary element:</p>
<p>For example:</p>
<pre><code> >>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
</code></pre>
<p>How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.</p>
<p>If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.</p>
<p>But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?</p>
<p>I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)</p>
<p>Any help is appreciated, thanks!</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name">python, can i print original var name?</a></li>
<li><a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python">How can you print a variable name in python?</a></li>
</ul>
<p><hr /></p>
<p>Update: Here's why I wanted this to work:</p>
<p>I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:</p>
<pre><code>dict_1={}
dict_2={}
dict_3={}
dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]
dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3
</code></pre>
<p>SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.</p>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<pre><code>WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>instead of having to do:</p>
<pre><code>dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'
</code></pre>
<p><hr /></p>
<p>Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.</p>
| 2
|
2009-03-25T02:36:07Z
| 680,205
|
<blockquote>
<p>How can I go about making it tell me
that dict2['nth_dict_item'] is or is
referencing "dict1" ?</p>
</blockquote>
<pre><code>>>> print dict2['nth_dict_item'] is dict1
True
</code></pre>
| 0
|
2009-03-25T04:21:11Z
|
[
"python",
"dictionary",
"variables",
"lookup"
] |
Python: How to extract variable name of a dictionary entry?
| 680,032
|
<p>I'm wondering how I would go about finding the variable name of a dictionary element:</p>
<p>For example:</p>
<pre><code> >>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
</code></pre>
<p>How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.</p>
<p>If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.</p>
<p>But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?</p>
<p>I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)</p>
<p>Any help is appreciated, thanks!</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name">python, can i print original var name?</a></li>
<li><a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python">How can you print a variable name in python?</a></li>
</ul>
<p><hr /></p>
<p>Update: Here's why I wanted this to work:</p>
<p>I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:</p>
<pre><code>dict_1={}
dict_2={}
dict_3={}
dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]
dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3
</code></pre>
<p>SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.</p>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<pre><code>WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>instead of having to do:</p>
<pre><code>dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'
</code></pre>
<p><hr /></p>
<p>Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.</p>
| 2
|
2009-03-25T02:36:07Z
| 680,221
|
<p>You need to rethink your design.</p>
<p>A quick hack would be to actually put the variable name in ...</p>
<pre><code>dict2['item_n'] = 'dict1'
</code></pre>
<p>or maybe use a tuple ..</p>
<pre><code>dict2['item_n'] = ('dict1', dict1)
</code></pre>
<p>There's a function called <code>locals()</code> which gives a dictionary of local variable names, maybe you can consider it when you rethink about your design.</p>
<p>Here, have a look at how <code>locals()</code> works:</p>
<pre><code>>>> x = 10
>>> y = 20
>>> c = "kmf"
>>> olk = 12
>>> km = (1,6,"r",x)
>>> from pprint import pprint
>>> pprint( locals() )
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__name__': '__main__',
'c': 'kmf',
'km': (1, 6, 'r', 10),
'olk': 12,
'pprint': <function pprint at 0x016A0EB0>,
'x': 10,
'y': 20}
</code></pre>
<p><hr /></p>
<p><strong>UPDATE</strong></p>
<blockquote>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<p><code>WhichDict= dict_database[SomeUniqueIdentifier1]</code><br />
<code>WhichDict[WhichDict.keys()[0]][2]='newcomment'</code></p>
</blockquote>
<p>Well, this is trivial</p>
<p>dict_databse[identifier][2] = the_new_comment</p>
| 1
|
2009-03-25T04:31:30Z
|
[
"python",
"dictionary",
"variables",
"lookup"
] |
Python: How to extract variable name of a dictionary entry?
| 680,032
|
<p>I'm wondering how I would go about finding the variable name of a dictionary element:</p>
<p>For example:</p>
<pre><code> >>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
</code></pre>
<p>How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.</p>
<p>If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.</p>
<p>But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?</p>
<p>I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)</p>
<p>Any help is appreciated, thanks!</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name">python, can i print original var name?</a></li>
<li><a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python">How can you print a variable name in python?</a></li>
</ul>
<p><hr /></p>
<p>Update: Here's why I wanted this to work:</p>
<p>I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:</p>
<pre><code>dict_1={}
dict_2={}
dict_3={}
dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]
dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3
</code></pre>
<p>SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.</p>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<pre><code>WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>instead of having to do:</p>
<pre><code>dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'
</code></pre>
<p><hr /></p>
<p>Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.</p>
| 2
|
2009-03-25T02:36:07Z
| 680,259
|
<p>The trivial answer: instead of</p>
<pre><code>WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>use:</p>
<pre><code>WhichDict.values()[0][2]='newcomment'
</code></pre>
<p>But using a dictionary to represent a single movie is grossly inappropriate. Why not use a class instead?</p>
<pre><code>class Movie(object):
def __init__(self, filename, movie_duration, movie_type, comments):
self.filename = filename
self.movie_duration = movie_duration
self.movie_type = movie_type
self.comments = comments
database = dict()
database['unique_id_1'] = Movie("FooBar1.avi", duration, type, comments)
# ...
some_movie = database[some_id]
some_movie.comment = 'newcomment'
</code></pre>
| 4
|
2009-03-25T04:49:49Z
|
[
"python",
"dictionary",
"variables",
"lookup"
] |
Python: How to extract variable name of a dictionary entry?
| 680,032
|
<p>I'm wondering how I would go about finding the variable name of a dictionary element:</p>
<p>For example:</p>
<pre><code> >>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
</code></pre>
<p>How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.</p>
<p>If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.</p>
<p>But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?</p>
<p>I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)</p>
<p>Any help is appreciated, thanks!</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name">python, can i print original var name?</a></li>
<li><a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python">How can you print a variable name in python?</a></li>
</ul>
<p><hr /></p>
<p>Update: Here's why I wanted this to work:</p>
<p>I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:</p>
<pre><code>dict_1={}
dict_2={}
dict_3={}
dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]
dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3
</code></pre>
<p>SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.</p>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<pre><code>WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>instead of having to do:</p>
<pre><code>dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'
</code></pre>
<p><hr /></p>
<p>Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.</p>
| 2
|
2009-03-25T02:36:07Z
| 680,270
|
<p>Right now, for each movie, you're doing:</p>
<pre><code>dict_n = {}
dict_n["000n"] = [movie_duration,movie_type,comments]
</code></pre>
<p>with only one entry per dict. Then you're storing multiple movie dicts in a central one:</p>
<pre><code>dict_database = {}
dict_database["0001"] = dict_1
dict_database["0002"] = dict_2
dict_database["0003"] = dict_3
dict_database["000n"] = dict_n
</code></pre>
<p><strong>Edit:</strong> This is probably what you had in mind.</p>
<p>For each movie, there's a dict going from property names to values.</p>
<pre><code>movie_n = {}
movie_n["movie_duration"] = 333
movie_n["movie_type"] = "Fantasy"
movie_n["comments"] = ""
</code></pre>
<p>Then <code>movies["any_file.avi"]</code> gives you that dict. To add the movie to the directory and then add a comment, you enter:</p>
<pre><code>movies["any_file.avi"] = movie_n
movies["any_file.avi"]["comments"] = "new comment"
</code></pre>
<p>If you have to choose between the number of that movie and the filename, I'd go with the filename because it's simply more relevant when you're actually trying to access a movie. Plus, if necessary you can enumerate your movies (albeit out of order) through <code>movies.keys()</code> or something similar. If you want to use both a number and the filename, add the filename as another key for each movie.</p>
<pre><code>movie_n["filename"] = "any_file.avi"
</code></pre>
<p>or</p>
<pre><code>movies["000n"]["filename"] = "any_file.avi"
</code></pre>
| 1
|
2009-03-25T04:56:36Z
|
[
"python",
"dictionary",
"variables",
"lookup"
] |
Python: How to extract variable name of a dictionary entry?
| 680,032
|
<p>I'm wondering how I would go about finding the variable name of a dictionary element:</p>
<p>For example:</p>
<pre><code> >>>dict1={}
>>>dict2={}
>>>dict1['0001']='0002'
>>>dict2['nth_dict_item']=dict1
>>>print dict2
{'nth_dict_item': {'0001': '0002'}}
>>>print dict2['nth_dict_item']
{'001': '002'}
</code></pre>
<p>How can I go about making it tell me that dict2['nth_dict_item'] is or is referencing "dict1" ? I want the name of the data structure it's referencing and not the data itself.</p>
<p>If I compare the output of id(dict1) to id(dict2['nth_dict_item']) I can find they are the same.</p>
<p>But how can I turn that id back into a variable name? Is there a more direct/cleaner method of getting the information that I want to know?</p>
<p>I'm sure I'm just overlooking a function that would make my life easy but I'm pretty new to Python :)</p>
<p>Any help is appreciated, thanks!</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/544919/python-can-i-print-original-var-name">python, can i print original var name?</a></li>
<li><a href="http://stackoverflow.com/questions/592746/how-can-you-print-a-variable-name-in-python">How can you print a variable name in python?</a></li>
</ul>
<p><hr /></p>
<p>Update: Here's why I wanted this to work:</p>
<p>I'm trying to make an app that uses a dictionary kinda like a database. I wanted the functionality of this psuedocode to function:</p>
<pre><code>dict_1={}
dict_2={}
dict_3={}
dict_1["FooBar1.avi"]=[movie_duration,movie_type,comments]
dict_2["FooBar2.avi"]=[movie_duration,movie_type,comments]
dict_3["FooBar3.avi"]=[movie_duration,movie_type,comments]
dict_database[SomeUniqueIdentifier1]=dict_1
dict_database[SomeUniqueIdentifier2]=dict_2
dict_database[SomeUniqueIdentifier3]=dict_3
</code></pre>
<p>SomeUniqueIdentifier# would be a unique value that I'm using as a database key/unqiueID to look up entries.</p>
<p>I want to be able to update the "comments" field of FooBar1.avi by:</p>
<pre><code>WhichDict= dict_database[SomeUniqueIdentifier1]
WhichDict[WhichDict.keys()[0]][2]='newcomment'
</code></pre>
<p>instead of having to do:</p>
<pre><code>dict_database['SomeUniqueIdentifier1'][dict_database['SomeUniqueIdentifier1'].keys()[0]][2]='newcomment'
</code></pre>
<p><hr /></p>
<p>Thanks everyone. I now understand I was misunderstanding a LOT of basics (total brain fart). Will go back and fix the design. Thanks to you all!.</p>
| 2
|
2009-03-25T02:36:07Z
| 681,124
|
<p>Use <a href="http://guppy-pe.sourceforge.net/" rel="nofollow">Guppy</a>.</p>
<pre><code>from guppy import hpy
h=hpy()
h.iso(dict2['nth_dict_item']).sp
0: h.Root.i0_modules['__main__'].__dict__['dict1']
</code></pre>
| 0
|
2009-03-25T11:12:35Z
|
[
"python",
"dictionary",
"variables",
"lookup"
] |
How do I tell which Python interpreter I'm using?
| 680,207
|
<p>I am using Python 2.5.2. How can I tell whether it is <code>CPython</code> or <code>IronPython</code> or <code>Jython</code>?</p>
<p>Another question: how can I <strong>use a DLL</strong> developed in VB.NET in my project?</p>
| 1
|
2009-03-25T04:23:52Z
| 680,222
|
<p>If you downloaded it as the default thing from python.org, it's CPython. That's the ânormalâ version of Python, the one you get when you use the command âpythonâ, and the one you'll have unless you specifically went looking for the projects targeting Java/CIL.</p>
<p>And it's CPython because neither of the other projects have reached version number 2.5.2.</p>
<blockquote>
<p>How can i use a dll developed in VB.NET in to my project?</p>
</blockquote>
<p>From CPython, using <a href="http://pythonnet.sourceforge.net/">Python-for-.NET</a>(*) and clr.AddReference.</p>
<p>(*: actually a bit of a misnomer, as with CPython in control it is more like .NET-for-Python.)</p>
| 5
|
2009-03-25T04:31:54Z
|
[
"python"
] |
How do I tell which Python interpreter I'm using?
| 680,207
|
<p>I am using Python 2.5.2. How can I tell whether it is <code>CPython</code> or <code>IronPython</code> or <code>Jython</code>?</p>
<p>Another question: how can I <strong>use a DLL</strong> developed in VB.NET in my project?</p>
| 1
|
2009-03-25T04:23:52Z
| 680,226
|
<pre><code>import sys
print sys.version
</code></pre>
| 0
|
2009-03-25T04:33:09Z
|
[
"python"
] |
How do I tell which Python interpreter I'm using?
| 680,207
|
<p>I am using Python 2.5.2. How can I tell whether it is <code>CPython</code> or <code>IronPython</code> or <code>Jython</code>?</p>
<p>Another question: how can I <strong>use a DLL</strong> developed in VB.NET in my project?</p>
| 1
|
2009-03-25T04:23:52Z
| 680,227
|
<p>If you are typing "python" to launch it, it is probably CPython. IronPython's executable name is "ipy".</p>
| 3
|
2009-03-25T04:34:18Z
|
[
"python"
] |
How do I tell which Python interpreter I'm using?
| 680,207
|
<p>I am using Python 2.5.2. How can I tell whether it is <code>CPython</code> or <code>IronPython</code> or <code>Jython</code>?</p>
<p>Another question: how can I <strong>use a DLL</strong> developed in VB.NET in my project?</p>
| 1
|
2009-03-25T04:23:52Z
| 680,233
|
<p>Well since the first part of your question has been answered, I'll tackle the second part. .NET dll's can be accessed from python in various ways. If you are using ironpython it makes this especially easy, since all .NET languages can interact with eachother fairly seamlessly. In this case you would access your dll from ironpython just as you would any other .NET dll you made with ironpython. If you want to call a native dll you can use <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>.</p>
| 1
|
2009-03-25T04:37:13Z
|
[
"python"
] |
Using MultipartPostHandler to POST form-data with Python
| 680,305
|
<p>Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<a href="http://code.activestate.com/recipes/146306/">http://code.activestate.com/recipes/146306/</a></p>
<p>To get around this limitation some sharp coders created a library called MultipartPostHandler which creates an OpenerDirector you can use with urllib2 to mostly automatically POST with multipart/form-data. A copy of this library is here:
<a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
<p>I am new to Python and am unable to get this library to work. I wrote out essentially the following code. When I capture it in a local HTTP proxy, I can see that the data is still URL encoded and not multi-part MIME encoded. Please help me figure out what I am doing wrong or a better way to get this done. Thanks :-)</p>
<pre><code>FROM_ADDR = 'my@email.com'
try:
data = open(file, 'rb').read()
except:
print "Error: could not open file %s for reading" % file
print "Check permissions on the file or folder it resides in"
sys.exit(1)
# Build the POST request
url = "http://somedomain.com/?action=analyze"
post_data = {}
post_data['analysisType'] = 'file'
post_data['executable'] = data
post_data['notification'] = 'email'
post_data['email'] = FROM_ADDR
# MIME encode the POST payload
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
request = urllib2.Request(url, post_data)
request.set_proxy('127.0.0.1:8080', 'http') # For testing with Burp Proxy
# Make the request and capture the response
try:
response = urllib2.urlopen(request)
print response.geturl()
except urllib2.URLError, e:
print "File upload failed..."
</code></pre>
<p>EDIT1: Thanks for your response. I'm aware of the ActiveState httplib solution to this (I linked to it above). I'd rather abstract away the problem and use a minimal amount of code to continue using urllib2 how I have been. Any idea why the opener isn't being installed and used?</p>
| 44
|
2009-03-25T05:14:37Z
| 681,182
|
<p>Found this recipe to post multipart using <code>httplib</code> directly (no external libraries involved)</p>
<pre><code>import httplib
import mimetypes
def post_multipart(host, selector, fields, files):
content_type, body = encode_multipart_formdata(fields, files)
h = httplib.HTTP(host)
h.putrequest('POST', selector)
h.putheader('content-type', content_type)
h.putheader('content-length', str(len(body)))
h.endheaders()
h.send(body)
errcode, errmsg, headers = h.getreply()
return h.file.read()
def encode_multipart_formdata(fields, files):
LIMIT = '----------lImIt_of_THE_fIle_eW_$'
CRLF = '\r\n'
L = []
for (key, value) in fields:
L.append('--' + LIMIT)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for (key, filename, value) in files:
L.append('--' + LIMIT)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(value)
L.append('--' + LIMIT + '--')
L.append('')
body = CRLF.join(L)
content_type = 'multipart/form-data; boundary=%s' % LIMIT
return content_type, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
</code></pre>
| 29
|
2009-03-25T11:29:54Z
|
[
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] |
Using MultipartPostHandler to POST form-data with Python
| 680,305
|
<p>Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<a href="http://code.activestate.com/recipes/146306/">http://code.activestate.com/recipes/146306/</a></p>
<p>To get around this limitation some sharp coders created a library called MultipartPostHandler which creates an OpenerDirector you can use with urllib2 to mostly automatically POST with multipart/form-data. A copy of this library is here:
<a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
<p>I am new to Python and am unable to get this library to work. I wrote out essentially the following code. When I capture it in a local HTTP proxy, I can see that the data is still URL encoded and not multi-part MIME encoded. Please help me figure out what I am doing wrong or a better way to get this done. Thanks :-)</p>
<pre><code>FROM_ADDR = 'my@email.com'
try:
data = open(file, 'rb').read()
except:
print "Error: could not open file %s for reading" % file
print "Check permissions on the file or folder it resides in"
sys.exit(1)
# Build the POST request
url = "http://somedomain.com/?action=analyze"
post_data = {}
post_data['analysisType'] = 'file'
post_data['executable'] = data
post_data['notification'] = 'email'
post_data['email'] = FROM_ADDR
# MIME encode the POST payload
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
request = urllib2.Request(url, post_data)
request.set_proxy('127.0.0.1:8080', 'http') # For testing with Burp Proxy
# Make the request and capture the response
try:
response = urllib2.urlopen(request)
print response.geturl()
except urllib2.URLError, e:
print "File upload failed..."
</code></pre>
<p>EDIT1: Thanks for your response. I'm aware of the ActiveState httplib solution to this (I linked to it above). I'd rather abstract away the problem and use a minimal amount of code to continue using urllib2 how I have been. Any idea why the opener isn't being installed and used?</p>
| 44
|
2009-03-25T05:14:37Z
| 688,193
|
<p>It seems that the easiest and most compatible way to get around this problem is to use the 'poster' module.</p>
<pre><code># test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
# Register the streaming http handlers with urllib2
register_openers()
# Start the multipart/form-data encoding of the file "DSC0001.jpg"
# "image1" is the name of the parameter, which is normally set
# via the "name" parameter of the HTML <input> tag.
# headers contains the necessary Content-Type and Content-Length
# datagen is a generator object that yields the encoded parameters
datagen, headers = multipart_encode({"image1": open("DSC0001.jpg")})
# Create the Request object
request = urllib2.Request("http://localhost:5000/upload_image", datagen, headers)
# Actually do the request, and get the response
print urllib2.urlopen(request).read()
</code></pre>
<p>This worked perfect and I didn't have to muck with httplib. The module is available here:
<a href="http://atlee.ca/software/poster/index.html">http://atlee.ca/software/poster/index.html</a></p>
| 55
|
2009-03-27T01:31:25Z
|
[
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] |
Using MultipartPostHandler to POST form-data with Python
| 680,305
|
<p>Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<a href="http://code.activestate.com/recipes/146306/">http://code.activestate.com/recipes/146306/</a></p>
<p>To get around this limitation some sharp coders created a library called MultipartPostHandler which creates an OpenerDirector you can use with urllib2 to mostly automatically POST with multipart/form-data. A copy of this library is here:
<a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
<p>I am new to Python and am unable to get this library to work. I wrote out essentially the following code. When I capture it in a local HTTP proxy, I can see that the data is still URL encoded and not multi-part MIME encoded. Please help me figure out what I am doing wrong or a better way to get this done. Thanks :-)</p>
<pre><code>FROM_ADDR = 'my@email.com'
try:
data = open(file, 'rb').read()
except:
print "Error: could not open file %s for reading" % file
print "Check permissions on the file or folder it resides in"
sys.exit(1)
# Build the POST request
url = "http://somedomain.com/?action=analyze"
post_data = {}
post_data['analysisType'] = 'file'
post_data['executable'] = data
post_data['notification'] = 'email'
post_data['email'] = FROM_ADDR
# MIME encode the POST payload
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
request = urllib2.Request(url, post_data)
request.set_proxy('127.0.0.1:8080', 'http') # For testing with Burp Proxy
# Make the request and capture the response
try:
response = urllib2.urlopen(request)
print response.geturl()
except urllib2.URLError, e:
print "File upload failed..."
</code></pre>
<p>EDIT1: Thanks for your response. I'm aware of the ActiveState httplib solution to this (I linked to it above). I'd rather abstract away the problem and use a minimal amount of code to continue using urllib2 how I have been. Any idea why the opener isn't being installed and used?</p>
| 44
|
2009-03-25T05:14:37Z
| 18,120,930
|
<p>Just use <a href="http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow"><strong>python-requests</strong></a>, it will set proper headers and do upload for you:</p>
<pre><code>import requests
files = {"form_input_field_name": open("filename", "rb")}
requests.post("http://httpbin.org/post", files=files)
</code></pre>
| 24
|
2013-08-08T08:04:24Z
|
[
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] |
Using MultipartPostHandler to POST form-data with Python
| 680,305
|
<p>Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<a href="http://code.activestate.com/recipes/146306/">http://code.activestate.com/recipes/146306/</a></p>
<p>To get around this limitation some sharp coders created a library called MultipartPostHandler which creates an OpenerDirector you can use with urllib2 to mostly automatically POST with multipart/form-data. A copy of this library is here:
<a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
<p>I am new to Python and am unable to get this library to work. I wrote out essentially the following code. When I capture it in a local HTTP proxy, I can see that the data is still URL encoded and not multi-part MIME encoded. Please help me figure out what I am doing wrong or a better way to get this done. Thanks :-)</p>
<pre><code>FROM_ADDR = 'my@email.com'
try:
data = open(file, 'rb').read()
except:
print "Error: could not open file %s for reading" % file
print "Check permissions on the file or folder it resides in"
sys.exit(1)
# Build the POST request
url = "http://somedomain.com/?action=analyze"
post_data = {}
post_data['analysisType'] = 'file'
post_data['executable'] = data
post_data['notification'] = 'email'
post_data['email'] = FROM_ADDR
# MIME encode the POST payload
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
request = urllib2.Request(url, post_data)
request.set_proxy('127.0.0.1:8080', 'http') # For testing with Burp Proxy
# Make the request and capture the response
try:
response = urllib2.urlopen(request)
print response.geturl()
except urllib2.URLError, e:
print "File upload failed..."
</code></pre>
<p>EDIT1: Thanks for your response. I'm aware of the ActiveState httplib solution to this (I linked to it above). I'd rather abstract away the problem and use a minimal amount of code to continue using urllib2 how I have been. Any idea why the opener isn't being installed and used?</p>
| 44
|
2009-03-25T05:14:37Z
| 26,028,984
|
<p>I what a coincide, 2 years, 6 months ago I create the project </p>
<p><a href="https://pypi.python.org/pypi/MultipartPostHandler2" rel="nofollow">https://pypi.python.org/pypi/MultipartPostHandler2</a> , that fix MultipartPostHandler for utf-8 systems. I also have done some minor improvements , you are welcome to test it :) </p>
| 0
|
2014-09-25T01:18:06Z
|
[
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] |
Using MultipartPostHandler to POST form-data with Python
| 680,305
|
<p>Problem: When POSTing data with Python's urllib2, all data is URL encoded and sent as Content-Type: application/x-www-form-urlencoded. When uploading files, the Content-Type should instead be set to multipart/form-data and the contents be MIME encoded. A discussion of this problem is here:
<a href="http://code.activestate.com/recipes/146306/">http://code.activestate.com/recipes/146306/</a></p>
<p>To get around this limitation some sharp coders created a library called MultipartPostHandler which creates an OpenerDirector you can use with urllib2 to mostly automatically POST with multipart/form-data. A copy of this library is here:
<a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
<p>I am new to Python and am unable to get this library to work. I wrote out essentially the following code. When I capture it in a local HTTP proxy, I can see that the data is still URL encoded and not multi-part MIME encoded. Please help me figure out what I am doing wrong or a better way to get this done. Thanks :-)</p>
<pre><code>FROM_ADDR = 'my@email.com'
try:
data = open(file, 'rb').read()
except:
print "Error: could not open file %s for reading" % file
print "Check permissions on the file or folder it resides in"
sys.exit(1)
# Build the POST request
url = "http://somedomain.com/?action=analyze"
post_data = {}
post_data['analysisType'] = 'file'
post_data['executable'] = data
post_data['notification'] = 'email'
post_data['email'] = FROM_ADDR
# MIME encode the POST payload
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
request = urllib2.Request(url, post_data)
request.set_proxy('127.0.0.1:8080', 'http') # For testing with Burp Proxy
# Make the request and capture the response
try:
response = urllib2.urlopen(request)
print response.geturl()
except urllib2.URLError, e:
print "File upload failed..."
</code></pre>
<p>EDIT1: Thanks for your response. I'm aware of the ActiveState httplib solution to this (I linked to it above). I'd rather abstract away the problem and use a minimal amount of code to continue using urllib2 how I have been. Any idea why the opener isn't being installed and used?</p>
| 44
|
2009-03-25T05:14:37Z
| 29,332,627
|
<p>I ran into the same problem and I needed to do a multipart form post without using external libraries. I wrote a whole <a href="http://blog.thesparktree.com/post/114053773684/the-unfortunately-long-story-dealing-with" rel="nofollow">blogpost about the issues I ran into</a>.</p>
<p>I ended up using a modified version of <a href="http://code.activestate.com/recipes/146306/" rel="nofollow">http://code.activestate.com/recipes/146306/</a>. The code in that url actually just appends the content of the file as a string, which can cause problems with binary files. Here's my working code.</p>
<pre><code>import mimetools
import mimetypes
import io
import http
import json
form = MultiPartForm()
form.add_field("form_field", "my awesome data")
# Add a fake file
form.add_file(key, os.path.basename(filepath),
fileHandle=codecs.open("/path/to/my/file.zip", "rb"))
# Build the request
url = "http://www.example.com/endpoint"
schema, netloc, url, params, query, fragments = urlparse.urlparse(url)
try:
form_buffer = form.get_binary().getvalue()
http = httplib.HTTPConnection(netloc)
http.connect()
http.putrequest("POST", url)
http.putheader('Content-type',form.get_content_type())
http.putheader('Content-length', str(len(form_buffer)))
http.endheaders()
http.send(form_buffer)
except socket.error, e:
raise SystemExit(1)
r = http.getresponse()
if r.status == 200:
return json.loads(r.read())
else:
print('Upload failed (%s): %s' % (r.status, r.reason))
class MultiPartForm(object):
"""Accumulate the data to be used when posting a form."""
def __init__(self):
self.form_fields = []
self.files = []
self.boundary = mimetools.choose_boundary()
return
def get_content_type(self):
return 'multipart/form-data; boundary=%s' % self.boundary
def add_field(self, name, value):
"""Add a simple field to the form data."""
self.form_fields.append((name, value))
return
def add_file(self, fieldname, filename, fileHandle, mimetype=None):
"""Add a file to be uploaded."""
body = fileHandle.read()
if mimetype is None:
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
self.files.append((fieldname, filename, mimetype, body))
return
def get_binary(self):
"""Return a binary buffer containing the form data, including attached files."""
part_boundary = '--' + self.boundary
binary = io.BytesIO()
needsCLRF = False
# Add the form fields
for name, value in self.form_fields:
if needsCLRF:
binary.write('\r\n')
needsCLRF = True
block = [part_boundary,
'Content-Disposition: form-data; name="%s"' % name,
'',
value
]
binary.write('\r\n'.join(block))
# Add the files to upload
for field_name, filename, content_type, body in self.files:
if needsCLRF:
binary.write('\r\n')
needsCLRF = True
block = [part_boundary,
str('Content-Disposition: file; name="%s"; filename="%s"' % \
(field_name, filename)),
'Content-Type: %s' % content_type,
''
]
binary.write('\r\n'.join(block))
binary.write('\r\n')
binary.write(body)
# add closing boundary marker,
binary.write('\r\n--' + self.boundary + '--\r\n')
return binary
</code></pre>
| 0
|
2015-03-29T17:49:20Z
|
[
"python",
"file",
"upload",
"urllib2",
"multipartform-data"
] |
Python 2.5.2 continued
| 680,336
|
<p>This is a continuation of my question Python2.5.2
The code i developed is working fine with clr.Addreference().
Now thee problem is I have to load ny script which uses dll developed in .NET to another application.They had used QT for its implementation.There is a Script console in that application.When ii entered 'import clr' ,it was saying 'No module named clr' or 'Cannot import clr'.What shall i do?</p>
| 0
|
2009-03-25T05:34:45Z
| 680,367
|
<p>You won't be able to run your script in that application. The script console in that QT application doubtlessly uses plain ol' CPython instead of IronPython. There's no real good way to change that without significant surgery to the application that's hosting the python console.</p>
| 3
|
2009-03-25T05:50:48Z
|
[
"python",
"ironpython"
] |
python create slice object from string
| 680,826
|
<p>I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement</p>
<pre><code>class getslice:
def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
</code></pre>
<p>thanks in advance.</p>
<p><strong>Edit</strong>: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).</p>
| 5
|
2009-03-25T09:23:52Z
| 680,843
|
<p>use operator module:</p>
<p>in Python 2.5 or earlier: <a href="http://docs.python.org/library/operator.html#operator.getslice" rel="nofollow"><code>operator.getslice(obj,start,end)</code></a></p>
<p>in Python 2.6 or later: <a href="http://docs.python.org/library/operator.html#operator.getitem" rel="nofollow"><code>operator.getitem(obj,[start:end])</code></a> </p>
| 2
|
2009-03-25T09:27:51Z
|
[
"python",
"indexing",
"slice"
] |
python create slice object from string
| 680,826
|
<p>I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement</p>
<pre><code>class getslice:
def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
</code></pre>
<p>thanks in advance.</p>
<p><strong>Edit</strong>: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).</p>
| 5
|
2009-03-25T09:23:52Z
| 680,889
|
<p>If you want a slice object, why don't you just instantiate one?</p>
<pre><code>s = slice(start, stop, step)
</code></pre>
<p>What are you meaning by "creating it from a string"?</p>
| 4
|
2009-03-25T09:46:12Z
|
[
"python",
"indexing",
"slice"
] |
python create slice object from string
| 680,826
|
<p>I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement</p>
<pre><code>class getslice:
def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
</code></pre>
<p>thanks in advance.</p>
<p><strong>Edit</strong>: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).</p>
| 5
|
2009-03-25T09:23:52Z
| 681,895
|
<p>A slice object is usually created using subscript notation, this notation uses slice() internally, as stated on the <a href="http://docs.python.org/library/functions.html#slice" rel="nofollow">slice() documentation</a>. What you want to do is:</p>
<pre><code>your_string[start:end]
</code></pre>
<p>From <a href="http://docs.python.org/tutorial/introduction.html#strings" rel="nofollow">the python tutorial</a>:</p>
<blockquote>
<p>Strings can be subscripted (indexed);
like in C, the first character of a
string has subscript (index) 0. There
is no separate character type; a
character is simply a string of size
one. Like in Icon, substrings can be
specified with the slice notation: two
indices separated by a colon.</p>
</blockquote>
<pre><code>>>> word = 'Help' + 'A'
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
</code></pre>
<blockquote>
<p>Slice indices have useful defaults; an
omitted first index defaults to zero,
an omitted second index defaults to
the size of the string being sliced.</p>
</blockquote>
<pre><code>>>> word[:2] # The first two characters
'He'
>>> word[2:] # Everything except the first two characters
'lpA'
</code></pre>
| 0
|
2009-03-25T14:42:28Z
|
[
"python",
"indexing",
"slice"
] |
python create slice object from string
| 680,826
|
<p>I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement</p>
<pre><code>class getslice:
def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
</code></pre>
<p>thanks in advance.</p>
<p><strong>Edit</strong>: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).</p>
| 5
|
2009-03-25T09:23:52Z
| 681,949
|
<pre><code>slice(*[{True: lambda n: None, False: int}[x == ''](x) for x in (mystring.split(':') + ['', '', ''])[:3]])
</code></pre>
| 3
|
2009-03-25T14:51:40Z
|
[
"python",
"indexing",
"slice"
] |
python create slice object from string
| 680,826
|
<p>I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement</p>
<pre><code>class getslice:
def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
</code></pre>
<p>thanks in advance.</p>
<p><strong>Edit</strong>: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).</p>
| 5
|
2009-03-25T09:23:52Z
| 23,895,339
|
<p>I end up here because I wanted my script to accept a python-like splice argument and render it into a list of integers, I did it with a function that seems like it answers the OP's question:</p>
<pre><code># create a slice object from a string
def get_slice_obj(slicearg):
slice_ints = tuple([ int(n) for n in slicearg.split(':') ])
return apply(slice, slice_ints)
def ints_from_slicearg(slicearg):
slice_obj = get_slice_obj(slicearg)
return(range(slice_obj.start or 0, slice_obj.stop or -1, slice_obj.step or 1))
for t in ['1', '1:3', '4:9:2']:
print t, "=>", ints_from_slicearg(t)
</code></pre>
<p>Output:</p>
<pre><code>1 => [0]
1:3 => [1, 2]
4:9:2 => [4, 6, 8]
</code></pre>
| 1
|
2014-05-27T17:18:06Z
|
[
"python",
"indexing",
"slice"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 680,954
|
<p>you might find <a href="http://docs.python.org/library/functions.html?highlight=getattr#getattr"><code>getattr</code></a> useful, I guess</p>
<pre><code>import module
getattr(module, status.lower())(*args, **kwargs)
</code></pre>
| 35
|
2009-03-25T10:08:32Z
|
[
"python",
"factory"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 680,958
|
<p>assuming that these functions belong to some module:</p>
<pre><code>import module
return getattr(module, status.lower()).__call__(*args, **kwargs)
</code></pre>
| 15
|
2009-03-25T10:10:11Z
|
[
"python",
"factory"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 680,967
|
<p>The canonical way to do this is to use a dictionary to emulate <code>switch</code> or <code>if/elif</code>. You will find several questions to similar problems here on SO.</p>
<p>Put your functions into a dictionary with your status codes as keys:</p>
<pre><code>funcs = {
'CONNECT': connect,
'RAWFEED': rawfeed,
'RAWCONFIG' : rawconfig,
'TESTFEED': testfeed
}
funcs[status](*args, **kwargs)
</code></pre>
| 15
|
2009-03-25T10:13:15Z
|
[
"python",
"factory"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 680,980
|
<p>some change from previous one:</p>
<pre><code>funcs = {
'CONNECT': connect,
'RAWFEED': rawfeed,
'RAWCONFIG' : rawconfig,
'TESTFEED': testfeed
}
func = funcs.get('status')
if funcï¼
func(*args, **kwargs)
</code></pre>
| -1
|
2009-03-25T10:16:46Z
|
[
"python",
"factory"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 680,984
|
<p>it seams that you can use getattr in a slightly different (in my opinion more elegant way)</p>
<pre><code>import math
getattr(math, 'sin')(1)
</code></pre>
<p>or if function is imported like below</p>
<pre><code>from math import sin
</code></pre>
<p>sin is now in namespace so you can call it by</p>
<pre><code>vars()['sin'](1)
</code></pre>
| 5
|
2009-03-25T10:18:46Z
|
[
"python",
"factory"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 680,986
|
<p>Look at this: <a href="http://diveintopython.net/power_of_introspection/getattr.html#d0e9362" rel="nofollow">getattra as a function dispatcher</a></p>
| 3
|
2009-03-25T10:19:41Z
|
[
"python",
"factory"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 681,007
|
<p>I encountered the same problem previously. Have a look at this question, I think its what you are looking for.</p>
<p><a href="http://stackoverflow.com/questions/277965/dictionary-or-if-statements-jython">Dictionary or If Statements</a></p>
<p>Hope this is helpful</p>
<p>Eef</p>
| 1
|
2009-03-25T10:27:10Z
|
[
"python",
"factory"
] |
Python dynamic function names
| 680,941
|
<p>I'm looking for a better way to call functions based on a variable in Python vs using if/else statements like below. Each status code has a corresponding function</p>
<pre><code>if status == 'CONNECT':
return connect(*args, **kwargs)
elif status == 'RAWFEED':
return rawfeed(*args, **kwargs)
elif status == 'RAWCONFIG':
return rawconfig(*args, **kwargs)
elif status == 'TESTFEED':
return testfeed(*args, **kwargs)
...
</code></pre>
<p>I assume this will require some sort of factory function but unsure as to the syntax</p>
| 9
|
2009-03-25T10:04:26Z
| 681,028
|
<p>Some improvement to SilentGhost's answer:</p>
<pre><code>globals()[status.lower()](*args, **kwargs)
</code></pre>
<p>if you want to call the function defined in the current module.</p>
<p>Though it looks ugly. I'd use the solution with dictionary.</p>
| 4
|
2009-03-25T10:33:39Z
|
[
"python",
"factory"
] |
Whats the difference between list[-1:][0] and list[len(list)-1]?
| 681,123
|
<p>Lest say you want the last element of a python list: what is the difference between</p>
<pre><code>myList[-1:][0]
</code></pre>
<p>and</p>
<pre><code>myList[len(myList)-1]
</code></pre>
<p>I thought there was no difference but then I tried this </p>
<pre><code>>>> list = [0]
>>> list[-1:][0]
0
>>> list[-1:][0] += 1
>>> list
[0]
>>> list[len(list)-1] += 1
>>> list
[1]
</code></pre>
<p>I was a little surprised...</p>
| 7
|
2009-03-25T11:11:46Z
| 681,135
|
<p>if you use slicing [-1:], the returned list is a shallow-copy, not reference. so [-1:][0] modifies the new list. [len(list)-1] is reference to last object.</p>
| 14
|
2009-03-25T11:15:40Z
|
[
"python",
"list",
"slice"
] |
Whats the difference between list[-1:][0] and list[len(list)-1]?
| 681,123
|
<p>Lest say you want the last element of a python list: what is the difference between</p>
<pre><code>myList[-1:][0]
</code></pre>
<p>and</p>
<pre><code>myList[len(myList)-1]
</code></pre>
<p>I thought there was no difference but then I tried this </p>
<pre><code>>>> list = [0]
>>> list[-1:][0]
0
>>> list[-1:][0] += 1
>>> list
[0]
>>> list[len(list)-1] += 1
>>> list
[1]
</code></pre>
<p>I was a little surprised...</p>
| 7
|
2009-03-25T11:11:46Z
| 681,138
|
<p><code>list[-1:]</code> creates a new list. To get the same behaviour as <code>list[len(list)-1]</code> it would have to return a view of some kind of <code>list</code>, but as I said, it creates a new temporary list. You then proceed to edit the temporary list.</p>
<p>Anyway, you know you can use <code>list[-1]</code> for the same thing, right?</p>
| 9
|
2009-03-25T11:17:16Z
|
[
"python",
"list",
"slice"
] |
Whats the difference between list[-1:][0] and list[len(list)-1]?
| 681,123
|
<p>Lest say you want the last element of a python list: what is the difference between</p>
<pre><code>myList[-1:][0]
</code></pre>
<p>and</p>
<pre><code>myList[len(myList)-1]
</code></pre>
<p>I thought there was no difference but then I tried this </p>
<pre><code>>>> list = [0]
>>> list[-1:][0]
0
>>> list[-1:][0] += 1
>>> list
[0]
>>> list[len(list)-1] += 1
>>> list
[1]
</code></pre>
<p>I was a little surprised...</p>
| 7
|
2009-03-25T11:11:46Z
| 681,196
|
<p>Slicing creates copy (shallow copy). It's often used as an shallow copy idiom.</p>
<p>i.e.</p>
<pre><code>list2 = list1[:]
</code></pre>
<p>is equivalent to</p>
<pre><code>import copy
list2 = copy.copy(list1)
</code></pre>
| 3
|
2009-03-25T11:34:54Z
|
[
"python",
"list",
"slice"
] |
Game map from Code
| 681,310
|
<p>It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)</p>
<p>I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: <a href="http://woarl.com/map/turn%5F32%5Fnormal.html" rel="nofollow">WoA Map</a></p>
<p>The background image for the map is located here: <a href="http://woarl.com/map/images/theMap.jpg" rel="nofollow">Map background</a> and created in <a href="http://www.omnigroup.com/applications/omnigraffle/" rel="nofollow">Omnigraffle</a>. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.</p>
<p>The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>, I have looked at incorporating it with <a href="http://www.blender.org/" rel="nofollow">Blender</a>, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)</p>
<p>I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.</p>
<p>As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.</p>
<p>Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).</p>
<p>Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).</p>
<p>After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.</p>
<p>I will be making an editor for this as suggested by <a href="http://stackoverflow.com/users/66634/adam-smith">Adam Smith</a>. I don't know that graphs will be relevant <a href="http://stackoverflow.com/users/62014/xynth">Xynth</a> but I've not had a chance to look into them fully yet.</p>
<p>I really appreciate all those that answered my question, thanks.</p>
| 2
|
2009-03-25T12:16:19Z
| 681,340
|
<p>I'd store a game map in code as a <a href="http://en.wikipedia.org/wiki/Graph%5F%28mathematics%29" rel="nofollow">graph</a>. </p>
<p>Each node would represent a country/city and each edge would represent adjacency. Once you have a map like that, I'm sure you can find many resources on AI (pathfinding, strategy, etc.) online.</p>
<p>If you want to be able to build an image of the map programattically, consider adding an (x, y) coordinate and an image for each node. That way you can display all of the images at the given coordinates to build up a map view.</p>
| 5
|
2009-03-25T12:24:27Z
|
[
"python"
] |
Game map from Code
| 681,310
|
<p>It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)</p>
<p>I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: <a href="http://woarl.com/map/turn%5F32%5Fnormal.html" rel="nofollow">WoA Map</a></p>
<p>The background image for the map is located here: <a href="http://woarl.com/map/images/theMap.jpg" rel="nofollow">Map background</a> and created in <a href="http://www.omnigroup.com/applications/omnigraffle/" rel="nofollow">Omnigraffle</a>. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.</p>
<p>The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>, I have looked at incorporating it with <a href="http://www.blender.org/" rel="nofollow">Blender</a>, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)</p>
<p>I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.</p>
<p>As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.</p>
<p>Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).</p>
<p>Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).</p>
<p>After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.</p>
<p>I will be making an editor for this as suggested by <a href="http://stackoverflow.com/users/66634/adam-smith">Adam Smith</a>. I don't know that graphs will be relevant <a href="http://stackoverflow.com/users/62014/xynth">Xynth</a> but I've not had a chance to look into them fully yet.</p>
<p>I really appreciate all those that answered my question, thanks.</p>
| 2
|
2009-03-25T12:16:19Z
| 681,386
|
<p>IMO, the map should be rendered in the first place instead of being a bitmap. What you should be doing is to have separate objects each knowing its dimensions clearly such as a generic Area class and classes like City, Town etc derived from this class. Your objects should have all the information about their location, their terrain etc and should be rendered/painted etc. This way you will have exact knowledge of where everything lies.</p>
<p>Another option is to keep the bitmap as it is and keep this information in your objects as their data. By doing this the objects won't have a draw function but they will have precise information of their placement etc. This is sort of duplicating the data but if you want to go with the bitmap option, I can't think of any other way.</p>
| 1
|
2009-03-25T12:36:36Z
|
[
"python"
] |
Game map from Code
| 681,310
|
<p>It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)</p>
<p>I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: <a href="http://woarl.com/map/turn%5F32%5Fnormal.html" rel="nofollow">WoA Map</a></p>
<p>The background image for the map is located here: <a href="http://woarl.com/map/images/theMap.jpg" rel="nofollow">Map background</a> and created in <a href="http://www.omnigroup.com/applications/omnigraffle/" rel="nofollow">Omnigraffle</a>. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.</p>
<p>The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>, I have looked at incorporating it with <a href="http://www.blender.org/" rel="nofollow">Blender</a>, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)</p>
<p>I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.</p>
<p>As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.</p>
<p>Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).</p>
<p>Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).</p>
<p>After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.</p>
<p>I will be making an editor for this as suggested by <a href="http://stackoverflow.com/users/66634/adam-smith">Adam Smith</a>. I don't know that graphs will be relevant <a href="http://stackoverflow.com/users/62014/xynth">Xynth</a> but I've not had a chance to look into them fully yet.</p>
<p>I really appreciate all those that answered my question, thanks.</p>
| 2
|
2009-03-25T12:16:19Z
| 681,393
|
<p>If you just want to do e.g. 2D hit-testing on the map, then storing it yourself is fine. There are a few possibilities for how you can store the information:</p>
<ul>
<li>A polygon per island</li>
<li>Representing each island as union of a list rectangles (commonly used by windowing systems)</li>
<li>Creating a special (maybe greyscale) bitmap of the map which uses a unique solid colour for each island</li>
<li>Something more complex (perhaps whatever Omnigiraffe's internal representation is)</li>
</ul>
| 1
|
2009-03-25T12:39:28Z
|
[
"python"
] |
Game map from Code
| 681,310
|
<p>It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)</p>
<p>I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: <a href="http://woarl.com/map/turn%5F32%5Fnormal.html" rel="nofollow">WoA Map</a></p>
<p>The background image for the map is located here: <a href="http://woarl.com/map/images/theMap.jpg" rel="nofollow">Map background</a> and created in <a href="http://www.omnigroup.com/applications/omnigraffle/" rel="nofollow">Omnigraffle</a>. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.</p>
<p>The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>, I have looked at incorporating it with <a href="http://www.blender.org/" rel="nofollow">Blender</a>, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)</p>
<p>I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.</p>
<p>As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.</p>
<p>Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).</p>
<p>Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).</p>
<p>After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.</p>
<p>I will be making an editor for this as suggested by <a href="http://stackoverflow.com/users/66634/adam-smith">Adam Smith</a>. I don't know that graphs will be relevant <a href="http://stackoverflow.com/users/62014/xynth">Xynth</a> but I've not had a chance to look into them fully yet.</p>
<p>I really appreciate all those that answered my question, thanks.</p>
| 2
|
2009-03-25T12:16:19Z
| 681,401
|
<p>You're going to have to translate your map into an abstract representation of some kind. Either a grid (hex or square) or a graph as xynth suggests. That's the only way you're going to be able to apply things like pathfinding algorithms to it.</p>
| 2
|
2009-03-25T12:40:27Z
|
[
"python"
] |
Game map from Code
| 681,310
|
<p>It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)</p>
<p>I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: <a href="http://woarl.com/map/turn%5F32%5Fnormal.html" rel="nofollow">WoA Map</a></p>
<p>The background image for the map is located here: <a href="http://woarl.com/map/images/theMap.jpg" rel="nofollow">Map background</a> and created in <a href="http://www.omnigroup.com/applications/omnigraffle/" rel="nofollow">Omnigraffle</a>. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.</p>
<p>The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>, I have looked at incorporating it with <a href="http://www.blender.org/" rel="nofollow">Blender</a>, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)</p>
<p>I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.</p>
<p>As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.</p>
<p>Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).</p>
<p>Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).</p>
<p>After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.</p>
<p>I will be making an editor for this as suggested by <a href="http://stackoverflow.com/users/66634/adam-smith">Adam Smith</a>. I don't know that graphs will be relevant <a href="http://stackoverflow.com/users/62014/xynth">Xynth</a> but I've not had a chance to look into them fully yet.</p>
<p>I really appreciate all those that answered my question, thanks.</p>
| 2
|
2009-03-25T12:16:19Z
| 681,447
|
<p>The key thing to realize here is that you don't have to use just <strong>one</strong> map. You can use two maps:</p>
<ul>
<li>The one you already have which is drawn on screen</li>
<li>A hidden map which isn't drawn but which is used for path finding, collision detection etc.</li>
</ul>
<p>The natural next question then is where does this second map come from? Easy, you create your own tool which can load your first map, and display it. Your tool will then let you draw boundaries around you islands and place markers at your cities. These markers and boundaries (simple polygons e.g.) are stored as your second map and is used in your code to do path finding etc. </p>
<p>In fact you can have your tool emit python code which creates the graphs and polygons so that you don't have to load any data yourself. </p>
<p>I am just basically telling you to make a level editor. It isn't very hard to do. You just need some buttons to click on to define what you are adding. e.g. if you are adding a polygon. Then you can just add each mouse coordinate to an array each time you click on your mouse if you have toggled your add polygon button. You can have another button for adding cities so that each time you click on the map you will record that coordinate for the city and possibly a corresponding name that you can provide in a text box.</p>
| 3
|
2009-03-25T12:55:11Z
|
[
"python"
] |
Game map from Code
| 681,310
|
<p>It's a long one so you might want to get that cup of tea/coffee you've been holding off on ;)</p>
<p>I run a game called World of Arl, it's a turn based strategy game akin to Risk or Diplomacy. Each player has a set of cities, armies and whatnot. The question revolves around the display of these things. Currently the map is created using a background image with CSS positioning of team icons on top of that to represent cities. You can see how it looks here: <a href="http://woarl.com/map/turn%5F32%5Fnormal.html" rel="nofollow">WoA Map</a></p>
<p>The background image for the map is located here: <a href="http://woarl.com/map/images/theMap.jpg" rel="nofollow">Map background</a> and created in <a href="http://www.omnigroup.com/applications/omnigraffle/" rel="nofollow">Omnigraffle</a>. It's not designed to draw maps but I'm hopelessly incompetent with photoshop and this works for my purposes just fine.</p>
<p>The problem comes that I want to perform such fun things as pathfinding and for that I need to have the map somehow stored in code. I have tried using <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>, I have looked at incorporating it with <a href="http://www.blender.org/" rel="nofollow">Blender</a>, I tried going "old school" and creating tiles as from many older games and finally I tried to use SVG. I say this so you can see clearly that it's not through lack of trying that I have this problem ;)</p>
<p>I want to be able to store the map layout in code and both create an image from it and use it for things such as pathfinding. I'm using Python but I suspect that most answers will be generic. The cities other such things are stored already and easily drawn on, I want to store the layout of the landmass and features on the landmass.</p>
<p>As for pathfinding, each type of terrain has a movement cost and when the map is stored as just an image I can't access the terrain of a given area. In addition to pathfinding I wish to be able to know the terrain for various things related to the game, cities in mountains produce stone for example.</p>
<p>Is there a good way to do this and what terms should I have used in Google because the terms I tried all came up with unrelated stuff (mapping being something completely different most of the time).</p>
<p>Edit 2:
Armies can be placed anywhere on the map as can cities, well, anywhere but in the water where they'd sink, drown and probably complain (in that order).</p>
<p>After chatting to somebody on MSN who made me go over the really minute details and who has a better understanding of the game (owing to the fact that he's played it) it's occurring to me that tiles are the way to go but not the way I had initially thought. I put the bitmap down as it is now but also have a data layer of tiles, each tile has a given terrain type and thus pathfinding and suchlike can be done on it yet at the same time I still render using Omnigraffle which works pretty well.</p>
<p>I will be making an editor for this as suggested by <a href="http://stackoverflow.com/users/66634/adam-smith">Adam Smith</a>. I don't know that graphs will be relevant <a href="http://stackoverflow.com/users/62014/xynth">Xynth</a> but I've not had a chance to look into them fully yet.</p>
<p>I really appreciate all those that answered my question, thanks.</p>
| 2
|
2009-03-25T12:16:19Z
| 681,449
|
<p>Asuming the map is fixed (not created on the fly) its "correct" to use a bitmap as graphical representation - you want to make it as pretty as possible.</p>
<p>For any game related features such as pathfinding or whatever fancy stuff you want to add you should add adequate data structures, even if that means some data is redundant.</p>
<p>E.g. describe the boundaries of the isles as polygon splines (either manually or automatically created from the bitmap, thats up to you and how much effort you want to spend and is needed to get the functionality you want).</p>
<p>To sum it up: create data structures matching the problems you have to solve, the bitmap is fine for looks but avoid doing pathfining or other stuff on it.</p>
| 1
|
2009-03-25T12:55:45Z
|
[
"python"
] |
Nullable ForeignKeys and deleting a referenced model instance
| 681,497
|
<p>I have a ForeignKey which can be null in my model to model a loose coupling between the models. It looks somewhat like that:</p>
<pre><code>class Message(models.Model):
sender = models.ForeignKey(User, null=True, blank=True)
sender_name = models.CharField(max_length=255)
</code></pre>
<p>On save the senders name is written to the sender_name attribute. Now, I want to be able to delete the User instance referenced by the sender and leave the message in place.</p>
<p>Out of the box, this code always results in deleted messages as soon as I delete the User instance. So I thought a signal handler would be a good idea.</p>
<pre><code>def my_signal_handler(sender, instance, **kwargs):
instance.message_set.clear()
pre_delete.connect(my_signal_handler, sender=User)
</code></pre>
<p>Sadly, it is by no means a solution. Somehow Django first collects what it wants to delete and then fires the pre_delete handler. </p>
<p>Any ideas? Where is the knot in my brain?</p>
| 7
|
2009-03-25T13:06:42Z
| 681,614
|
<p>Django does indeed emulate SQL's <code>ON DELETE CASCADE</code> behaviour, and there's no out-of-the box documented way to change this. The docs where they mention this are near the end of this section: <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects">Deleting objects</a>.</p>
<p>You are right that Django's collects all related model instances, then calls the pre-delete handler for each. The sender of the signal will be the model class about to be deleted, in this case <code>Message</code>, rather than <code>User</code>, which makes it hard to detect the difference between a cascade delete triggered by User and a normal delete... especially since the signal for deleting the User class comes last, since that's the last deletion :-)</p>
<p>You can, however, get the list of objects that Django is proposing to delete in advance of calling the User.delete() function. Each model instance has a semi-private method called <code>_collect_sub_objects()</code> that compiles the list of instances with foreign keys pointing to it (it compiles this list without deleting the instances). You can see how this method is called by looking at <code>delete()</code> in <code>django.db.base</code>.</p>
<p>If this was one of your own objects, I'd recommend overriding the <code>delete()</code> method on your instance to run _collect_sub_objects(), and then break the ForeignKeys before calling the super class delete. Since you're using a built-in Django object that you may find too difficult to subclass (though it is possible to substitute your own User object for django's), you may have to rely on view logic to run <code>_collect_sub_objects</code> and break the FKs before deletion.</p>
<p>Here's a quick-and-dirty example:</p>
<pre><code>from django.db.models.query import CollectedObjects
u = User.objects.get(id=1)
instances_to_be_deleted = CollectedObjects()
u._collect_sub_objects(instances_to_be_deleted)
for k in instances_to_be_deleted.ordered_keys():
inst_dict = instances_to_be_deleted.data[k]
for i in inst_dict.values():
i.sender = None # You will need a more generic way for this
i.save()
u.delete()
</code></pre>
| 13
|
2009-03-25T13:31:54Z
|
[
"python",
"django",
"django-models"
] |
Nullable ForeignKeys and deleting a referenced model instance
| 681,497
|
<p>I have a ForeignKey which can be null in my model to model a loose coupling between the models. It looks somewhat like that:</p>
<pre><code>class Message(models.Model):
sender = models.ForeignKey(User, null=True, blank=True)
sender_name = models.CharField(max_length=255)
</code></pre>
<p>On save the senders name is written to the sender_name attribute. Now, I want to be able to delete the User instance referenced by the sender and leave the message in place.</p>
<p>Out of the box, this code always results in deleted messages as soon as I delete the User instance. So I thought a signal handler would be a good idea.</p>
<pre><code>def my_signal_handler(sender, instance, **kwargs):
instance.message_set.clear()
pre_delete.connect(my_signal_handler, sender=User)
</code></pre>
<p>Sadly, it is by no means a solution. Somehow Django first collects what it wants to delete and then fires the pre_delete handler. </p>
<p>Any ideas? Where is the knot in my brain?</p>
| 7
|
2009-03-25T13:06:42Z
| 5,663,303
|
<p>Having just discovered the ON DELETE CASCADE behaviour myself, I see that in Django 1.3 they have made the foreign key behaviour <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.on_delete" rel="nofollow">configurable</a>.</p>
| 0
|
2011-04-14T12:34:43Z
|
[
"python",
"django",
"django-models"
] |
How do you deploy django applications for windows?
| 681,565
|
<p>I'm working on a web application using <a href="http://code.google.com/p/isapi-wsgi/">isapi_wsgi</a> and <a href="http://code.google.com/p/django-pyodbc/">django-pyodbc</a>. I'd like to have a way to install all dependencies and push the files out to the webserver. Unfortunately, some of these are easier said than done. In particular, handling dependencies is a pain as some of them won't install correctly even under setuptools (pywin32 is especially difficult).</p>
<p>Most of the tools that I see for automating this kind of stuff (<a href="http://www.nongnu.org/fab/">fabric</a> and <a href="http://www.capify.org/">capistrano</a>) are made for use with unix-y systems. I would like to set up a continuous integration system, but that only solves part of the problem. Is there any way to make life easier for a Pythonista who's forced to use Windows/IIS?</p>
| 7
|
2009-03-25T13:22:36Z
| 681,642
|
<p>Have you looked into <a href="http://www.blueskyonmars.com/projects/paver/index.html" rel="nofollow">Paver</a>? It might not be the perfect solution, but maybe better then your current process.</p>
<p>And it has setuptools (and other useful wrappers) built-in.</p>
| 3
|
2009-03-25T13:38:03Z
|
[
"python",
"django",
"iis",
"deployment",
"isapi-wsgi"
] |
How do you deploy django applications for windows?
| 681,565
|
<p>I'm working on a web application using <a href="http://code.google.com/p/isapi-wsgi/">isapi_wsgi</a> and <a href="http://code.google.com/p/django-pyodbc/">django-pyodbc</a>. I'd like to have a way to install all dependencies and push the files out to the webserver. Unfortunately, some of these are easier said than done. In particular, handling dependencies is a pain as some of them won't install correctly even under setuptools (pywin32 is especially difficult).</p>
<p>Most of the tools that I see for automating this kind of stuff (<a href="http://www.nongnu.org/fab/">fabric</a> and <a href="http://www.capify.org/">capistrano</a>) are made for use with unix-y systems. I would like to set up a continuous integration system, but that only solves part of the problem. Is there any way to make life easier for a Pythonista who's forced to use Windows/IIS?</p>
| 7
|
2009-03-25T13:22:36Z
| 7,002,089
|
<p>BitNami provides free <a href="http://bitnami.org/stack/djangostack">Windows Django all-in-one installers</a> that include all dependencies to deploy a Django app on Windows. Disclaimer: I am one of the developers of this tool. If you are going for a hosted version, we also have free Windows Amazon Machine Images (look further down in that page) but in that case I would strongly recommend going with a Linux-based AMI.</p>
| 6
|
2011-08-09T19:51:46Z
|
[
"python",
"django",
"iis",
"deployment",
"isapi-wsgi"
] |
How is string.find implemented in CPython?
| 681,649
|
<p>I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so <a href="http://docs.python.org/library/stdtypes.html">http://docs.python.org/library/stdtypes.html</a> is of no help. Could someone please point me to the relevant source code?</p>
| 6
|
2009-03-25T13:41:42Z
| 681,666
|
<p>I suppose so:</p>
<blockquote>
<p><a href="http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=68811&view=markup">fast search/count implementation,
based on a mix between boyer-moore
and horspool, with a few more bells
and whistles on the top</a></p>
</blockquote>
| 15
|
2009-03-25T13:49:00Z
|
[
"python"
] |
How is string.find implemented in CPython?
| 681,649
|
<p>I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so <a href="http://docs.python.org/library/stdtypes.html">http://docs.python.org/library/stdtypes.html</a> is of no help. Could someone please point me to the relevant source code?</p>
| 6
|
2009-03-25T13:41:42Z
| 681,668
|
<p>You should be able to find it in Objects/stringlib/find.h, although the real code is in fastsearch.h.</p>
| 4
|
2009-03-25T13:49:25Z
|
[
"python"
] |
How is string.find implemented in CPython?
| 681,649
|
<p>I was wondering if the 'find' method on strings was implemented with a linear search, or if python did something more sophisticated. The Python documentation doesn't discuss implementation details, so <a href="http://docs.python.org/library/stdtypes.html">http://docs.python.org/library/stdtypes.html</a> is of no help. Could someone please point me to the relevant source code?</p>
| 6
|
2009-03-25T13:41:42Z
| 681,884
|
<p>Looks like the algorithm used originates from <a href="http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool%5Falgorithm" rel="nofollow">Boyer-Moore-Horspool algorithm</a></p>
| 1
|
2009-03-25T14:40:26Z
|
[
"python"
] |
Any alternatives to IronPython, Python for .NET for accessing CLR from python?
| 681,853
|
<p>Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available in CPython if you use IronPython. So are there any alternatives?</p>
| 3
|
2009-03-25T14:33:55Z
| 681,865
|
<p>What feature are you missing? There is a project called <a href="http://code.google.com/p/ironclad/" rel="nofollow">IronClad</a> that is helping to open access to CPython extensions from IronPython, it may be helpful. </p>
| 1
|
2009-03-25T14:36:19Z
|
[
".net",
"python",
"clr",
"ironpython"
] |
Any alternatives to IronPython, Python for .NET for accessing CLR from python?
| 681,853
|
<p>Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available in CPython if you use IronPython. So are there any alternatives?</p>
| 3
|
2009-03-25T14:33:55Z
| 681,875
|
<p>As far as I know you are not going to get anything more actively developed than IronPython .</p>
<p>IronPython is currently one of the .NET 5 being developed by the language team (C#, VB.NET, F#, IronPython and IronRuby) so I doubt that there's another open source .NET Python project that's gone anywhere near as far.</p>
| 1
|
2009-03-25T14:37:52Z
|
[
".net",
"python",
"clr",
"ironpython"
] |
Any alternatives to IronPython, Python for .NET for accessing CLR from python?
| 681,853
|
<p>Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available in CPython if you use IronPython. So are there any alternatives?</p>
| 3
|
2009-03-25T14:33:55Z
| 682,313
|
<p>Apart from Python for .NET (which works pretty well for me), the only other solution I'm aware of is exposing the .NET libraries via COM interop, so you can use them via the pywin32 extensions. </p>
<p>(I don't know much about .NET com interop yet, so hopefully someone else can provide further explanation on that.)</p>
| 3
|
2009-03-25T16:12:25Z
|
[
".net",
"python",
"clr",
"ironpython"
] |
Any alternatives to IronPython, Python for .NET for accessing CLR from python?
| 681,853
|
<p>Are there any alternatives to Python for .NET or IronPython for accessing .NET CLR? Both of these seem to have downsides in that Python for .NET is not under active development (as far as I can tell) and you lose some features available in CPython if you use IronPython. So are there any alternatives?</p>
| 3
|
2009-03-25T14:33:55Z
| 685,825
|
<p>Well it's a python derivative, but you always have <a href="http://boo.codehaus.org" rel="nofollow">Boo</a>.</p>
| 1
|
2009-03-26T13:36:59Z
|
[
".net",
"python",
"clr",
"ironpython"
] |
Python Class Decorator
| 681,953
|
<p>In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.</p>
<p>Looking for something like the following (which has a syntax error on 'class Foo:':</p>
<pre><code>def getId(self): return self.__id
class addID(original_class):
def __init__(self, id, *args, **kws):
self.__id = id
self.getId = getId
original_class.__init__(self, *args, **kws)
@addID
class Foo:
def __init__(self, value1):
self.value1 = value1
if __name__ == '__main__':
foo1 = Foo(5,1)
print foo1.value1, foo1.getId()
foo2 = Foo(15,2)
print foo2.value1, foo2.getId()
</code></pre>
<p>Thanks,
Rob</p>
<p><strong>Edit:</strong>
Rereading this question, I guess what I'm really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.</p>
| 89
|
2009-03-25T14:52:02Z
| 681,999
|
<p>That's not a good practice and there is no mechanism to do that because of that. The right way to accomplish what you want is inheritance.</p>
<p>Take a look into the <a href="http://docs.python.org/tutorial/classes.html#inheritance" rel="nofollow">class documentation</a>.</p>
<p>A little example:</p>
<pre><code>class Employee(object):
def __init__(self, age, sex, siblings=0):
self.age = age
self.sex = sex
self.siblings = siblings
def born_on(self):
today = datetime.date.today()
return today - datetime.timedelta(days=self.age*365)
class Boss(Employee):
def __init__(self, age, sex, siblings=0, bonus=0):
self.bonus = bonus
Employee.__init__(self, age, sex, siblings)
</code></pre>
<p>This way Boss has everything <code>Employee</code> has, with also his own <strong><code>__init__</code></strong> method and own members.</p>
| 11
|
2009-03-25T15:01:38Z
|
[
"python",
"decorator",
"python-2.5"
] |
Python Class Decorator
| 681,953
|
<p>In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.</p>
<p>Looking for something like the following (which has a syntax error on 'class Foo:':</p>
<pre><code>def getId(self): return self.__id
class addID(original_class):
def __init__(self, id, *args, **kws):
self.__id = id
self.getId = getId
original_class.__init__(self, *args, **kws)
@addID
class Foo:
def __init__(self, value1):
self.value1 = value1
if __name__ == '__main__':
foo1 = Foo(5,1)
print foo1.value1, foo1.getId()
foo2 = Foo(15,2)
print foo2.value1, foo2.getId()
</code></pre>
<p>Thanks,
Rob</p>
<p><strong>Edit:</strong>
Rereading this question, I guess what I'm really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.</p>
| 89
|
2009-03-25T14:52:02Z
| 682,052
|
<p>I would second the notion that you may wish to consider a subclass instead of the approach you've outlined. However, not knowing your specific scenario, YMMV :-)</p>
<p>What you're thinking of is a metaclass. The <code>__new__</code> function in a metaclass is passed the full proposed definition of the class, which it can then rewrite before the class is created. You can, at that time, sub out the constructor for a new one.</p>
<p>Example:</p>
<pre><code>def substitute_init(self, id, *args, **kwargs):
pass
class FooMeta(type):
def __new__(cls, name, bases, attrs):
attrs['__init__'] = substitute_init
return super(FooMeta, cls).__new__(cls, name, bases, attrs)
class Foo(object):
__metaclass__ = FooMeta
def __init__(self, value1):
pass
</code></pre>
<p>Replacing the constructor is perhaps a bit dramatic, but the language does provide support for this kind of deep introspection and dynamic modification.</p>
| 62
|
2009-03-25T15:14:34Z
|
[
"python",
"decorator",
"python-2.5"
] |
Python Class Decorator
| 681,953
|
<p>In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.</p>
<p>Looking for something like the following (which has a syntax error on 'class Foo:':</p>
<pre><code>def getId(self): return self.__id
class addID(original_class):
def __init__(self, id, *args, **kws):
self.__id = id
self.getId = getId
original_class.__init__(self, *args, **kws)
@addID
class Foo:
def __init__(self, value1):
self.value1 = value1
if __name__ == '__main__':
foo1 = Foo(5,1)
print foo1.value1, foo1.getId()
foo2 = Foo(15,2)
print foo2.value1, foo2.getId()
</code></pre>
<p>Thanks,
Rob</p>
<p><strong>Edit:</strong>
Rereading this question, I guess what I'm really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.</p>
| 89
|
2009-03-25T14:52:02Z
| 682,242
|
<p>Apart from the question whether class decorators are the right solution to your problem:</p>
<p>in Python 2.6 and higher, there are class decorators with the @-syntax, so you can write:</p>
<pre><code>@addID
class Foo:
pass
</code></pre>
<p>in older versions, you can do it another way:</p>
<pre><code>class Foo:
pass
Foo = addID(Foo)
</code></pre>
<p>Note however that this works the same as for function decorators, and that the decorator should return the new (or modified original) class, which is not what you're doing in the example. The addID decorator would look like this:</p>
<pre><code>def addID(original_class):
orig_init = original_class.__init__
# make copy of original __init__, so we can call it without recursion
def __init__(self, id, *args, **kws):
self.__id = id
self.getId = getId
orig_init(self, *args, **kws) # call the original __init__
original_class.__init__ = __init__ # set the class' __init__ to the new one
return original_class
</code></pre>
<p>You could then use the appropriate syntax for your python version as described above.</p>
<p>But I agree with others that inheritance is better suited if you want to override <code>__init__</code>.</p>
| 168
|
2009-03-25T15:58:22Z
|
[
"python",
"decorator",
"python-2.5"
] |
Python Class Decorator
| 681,953
|
<p>In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.</p>
<p>Looking for something like the following (which has a syntax error on 'class Foo:':</p>
<pre><code>def getId(self): return self.__id
class addID(original_class):
def __init__(self, id, *args, **kws):
self.__id = id
self.getId = getId
original_class.__init__(self, *args, **kws)
@addID
class Foo:
def __init__(self, value1):
self.value1 = value1
if __name__ == '__main__':
foo1 = Foo(5,1)
print foo1.value1, foo1.getId()
foo2 = Foo(15,2)
print foo2.value1, foo2.getId()
</code></pre>
<p>Thanks,
Rob</p>
<p><strong>Edit:</strong>
Rereading this question, I guess what I'm really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.</p>
| 89
|
2009-03-25T14:52:02Z
| 14,564,863
|
<p>There's actually a pretty good implementation of a class decorator here:</p>
<p><a href="https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py" rel="nofollow">https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py</a></p>
<p>I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like <code>isinstance</code> checks. </p>
<p>It has an added benefit: it's not uncommon for the <code>__init__</code> statement in a custom django Form to make modifications or additions to <code>self.fields</code> so it's better for changes to <code>self.fields</code> to happen <em>after</em> all of <code>__init__</code> has run for the class in question.</p>
<p>Very clever.</p>
<p>However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.</p>
| 3
|
2013-01-28T15:05:42Z
|
[
"python",
"decorator",
"python-2.5"
] |
Python Class Decorator
| 681,953
|
<p>In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.</p>
<p>Looking for something like the following (which has a syntax error on 'class Foo:':</p>
<pre><code>def getId(self): return self.__id
class addID(original_class):
def __init__(self, id, *args, **kws):
self.__id = id
self.getId = getId
original_class.__init__(self, *args, **kws)
@addID
class Foo:
def __init__(self, value1):
self.value1 = value1
if __name__ == '__main__':
foo1 = Foo(5,1)
print foo1.value1, foo1.getId()
foo2 = Foo(15,2)
print foo2.value1, foo2.getId()
</code></pre>
<p>Thanks,
Rob</p>
<p><strong>Edit:</strong>
Rereading this question, I guess what I'm really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.</p>
| 89
|
2009-03-25T14:52:02Z
| 18,938,008
|
<p>no-one has explained that you can dynamically define classes. so you can have a decorator that defines (and returns) a subclass:</p>
<pre><code>def addId(cls):
class AddId(cls):
def __init__(self, id, *args, **kargs):
super(AddId, self).__init__(*args, **kargs)
self.__id = id
def getId(self):
return self.__id
return AddId
</code></pre>
<p>which can be used in python 2 (the comment from Blckknght which explains why you should continue to do this in 2.6+) like this:</p>
<pre><code>class Foo:
pass
FooId = addId(Foo)
</code></pre>
<p>and in python 3 like this (but be careful to use <code>super()</code> in your classes):</p>
<pre><code>@addId
class Foo:
pass
</code></pre>
<p>so you can have your cake <em>and</em> eat it - inheritance <em>and</em> decorators!</p>
| 8
|
2013-09-21T21:47:44Z
|
[
"python",
"decorator",
"python-2.5"
] |
Which version of python added the else clause for for loops?
| 682,185
|
<p>Which was the first version of python to include the <a href="http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops">else clause for for loops</a>? </p>
<p>I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature.
(It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a programming website)</p>
| 11
|
2009-03-25T15:48:24Z
| 682,234
|
<p>It's been around since at least <a href="http://www.python.org/doc/1.4/ref/ref7.html#HDR2" rel="nofollow">1.4</a>, which is the <a href="http://www.python.org/doc/versions/" rel="nofollow">oldest version of the documentation</a> I know of.</p>
| 7
|
2009-03-25T15:57:15Z
|
[
"python",
"for-loop"
] |
Which version of python added the else clause for for loops?
| 682,185
|
<p>Which was the first version of python to include the <a href="http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops">else clause for for loops</a>? </p>
<p>I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature.
(It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a programming website)</p>
| 11
|
2009-03-25T15:48:24Z
| 684,134
|
<p>It's been present since the beginning. To see that, get the source from alt.sources, specifically the message titled "<a href="http://groups.google.com/group/alt.sources/browse_thread/thread/74a577bbcfc4be0a/cbaaec4fbfebbbb6">Python 0.9.1 part 17/21</a>". The date is Feb 21, 1991. This post included the grammar definition, which states:</p>
<pre><code>for_stmt: 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
</code></pre>
<p>You might be able to find the 0.9.0 sources if you try harder than I did, but as the first public release was 0.9.0 on 20 Feb, that would get you back one day. The 0.9.1 release was a minor patch that did not affect this part of the grammar.</p>
<p>(Is that a <a href="http://catb.org/jargon/html/U/UTSL.html">UTSL</a> reference or what? When was the last time <em>you</em> looked at a shar file? ;)</p>
<p>BTW, I reconstructed the original source and tweaked it a bit to compile under gcc-4.0 on my OS X 10.4 box. <a href="http://www.dalkescientific.com/writings/diary/archive/2009/03/27/python_0_9_1p1.html">Details</a> for those interested few, including <a href="http://dalkescientific.com/Python/python-0.9.1.tar.gz">python-0.9.1.tar.gz</a>.</p>
<p>The entire development history is available from version control, even after changing version control systems twice. "hg log -p -r 6:7" from the cpython Mercurial archive shows that the "for/else" was committed on Sun Oct 14 12:07:46 1990 +0000, and the previous commit was Sat Oct 13 19:23:40 1990 +0000. for/else has been part of Python since October 1990. </p>
| 28
|
2009-03-26T01:05:03Z
|
[
"python",
"for-loop"
] |
Which version of python added the else clause for for loops?
| 682,185
|
<p>Which was the first version of python to include the <a href="http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops">else clause for for loops</a>? </p>
<p>I find that the python docs usually does a good job of documenting when features were added, but I can't seem to find the info on this feature.
(It doesn't help that 'for' and 'else' are particularly difficult terms to google for on a programming website)</p>
| 11
|
2009-03-25T15:48:24Z
| 688,289
|
<p>Since version 1.0.1, at least..</p>
<pre><code>Python 1.0.1 (Mar 27 2009)
Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
>>> for x in range(2):
... print x
... else:
... print "loop done"
...
0
1
loop done
</code></pre>
| 1
|
2009-03-27T02:11:14Z
|
[
"python",
"for-loop"
] |
Splitting out the output of ps using Python
| 682,446
|
<p>On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.</p>
<pre><code>USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 09:58 0:05 /usr/sbin/httpd
</code></pre>
<p>I want to be able to read this in using Python and split out each row and then each column so they can be used as values.</p>
<p>For the most part, this is not a problem:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
</code></pre>
<p>I can now loop through processes to get each row and split it out by spaces, for example</p>
<pre><code>sep = re.compile('[\s]+')
for row in processes:
print sep.split(row)
</code></pre>
<p>However, the problem is that the last column, the command, sometimes has spaces in. In the example above this can be seen in command </p>
<pre><code>pickup -l -t fifo -u
</code></pre>
<p>which would be split out as</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup', '-l', '-t', 'fifo', '-u']
</code></pre>
<p>but I really want it as:</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup -l -t fifo -u']
</code></pre>
<p>So my question is, how can I split out the columns but when it comes to the command column, keep the whole string as one list element rather than split out by spaces?</p>
| 9
|
2009-03-25T16:50:57Z
| 682,464
|
<p>Use the second parameter to <code>split</code> which specifies the maximum number of fields to split the string into. I guess you can find the number by counting the number of fields in the first line, i.e. the column titles.</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
# this specifies the number of splits, so the splitted lines
# will have (nfields+1) elements
nfields = len(processes[0].split()) - 1
for row in processes[1:]:
print row.split(None, nfields)
</code></pre>
| 19
|
2009-03-25T16:53:31Z
|
[
"python",
"regex",
"linux"
] |
Splitting out the output of ps using Python
| 682,446
|
<p>On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.</p>
<pre><code>USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 09:58 0:05 /usr/sbin/httpd
</code></pre>
<p>I want to be able to read this in using Python and split out each row and then each column so they can be used as values.</p>
<p>For the most part, this is not a problem:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
</code></pre>
<p>I can now loop through processes to get each row and split it out by spaces, for example</p>
<pre><code>sep = re.compile('[\s]+')
for row in processes:
print sep.split(row)
</code></pre>
<p>However, the problem is that the last column, the command, sometimes has spaces in. In the example above this can be seen in command </p>
<pre><code>pickup -l -t fifo -u
</code></pre>
<p>which would be split out as</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup', '-l', '-t', 'fifo', '-u']
</code></pre>
<p>but I really want it as:</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup -l -t fifo -u']
</code></pre>
<p>So my question is, how can I split out the columns but when it comes to the command column, keep the whole string as one list element rather than split out by spaces?</p>
| 9
|
2009-03-25T16:50:57Z
| 682,471
|
<p>The <code>maxsplit</code> optional argument to the <code>split</code> method might help you:</p>
<pre><code>sep.split.(row, maxsplit=42)
</code></pre>
| 1
|
2009-03-25T16:54:15Z
|
[
"python",
"regex",
"linux"
] |
Splitting out the output of ps using Python
| 682,446
|
<p>On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.</p>
<pre><code>USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 09:58 0:05 /usr/sbin/httpd
</code></pre>
<p>I want to be able to read this in using Python and split out each row and then each column so they can be used as values.</p>
<p>For the most part, this is not a problem:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
</code></pre>
<p>I can now loop through processes to get each row and split it out by spaces, for example</p>
<pre><code>sep = re.compile('[\s]+')
for row in processes:
print sep.split(row)
</code></pre>
<p>However, the problem is that the last column, the command, sometimes has spaces in. In the example above this can be seen in command </p>
<pre><code>pickup -l -t fifo -u
</code></pre>
<p>which would be split out as</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup', '-l', '-t', 'fifo', '-u']
</code></pre>
<p>but I really want it as:</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup -l -t fifo -u']
</code></pre>
<p>So my question is, how can I split out the columns but when it comes to the command column, keep the whole string as one list element rather than split out by spaces?</p>
| 9
|
2009-03-25T16:50:57Z
| 682,487
|
<p>Why don't you use <a href="https://pypi.python.org/pypi/PSI/" rel="nofollow">PSI</a> instead? PSI provides process information on Linux and other Unix variants.</p>
<pre><code>import psi.process
for p in psi.process.ProcessTable().values(): â¦
</code></pre>
| 4
|
2009-03-25T16:57:08Z
|
[
"python",
"regex",
"linux"
] |
Splitting out the output of ps using Python
| 682,446
|
<p>On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.</p>
<pre><code>USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 09:58 0:05 /usr/sbin/httpd
</code></pre>
<p>I want to be able to read this in using Python and split out each row and then each column so they can be used as values.</p>
<p>For the most part, this is not a problem:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
</code></pre>
<p>I can now loop through processes to get each row and split it out by spaces, for example</p>
<pre><code>sep = re.compile('[\s]+')
for row in processes:
print sep.split(row)
</code></pre>
<p>However, the problem is that the last column, the command, sometimes has spaces in. In the example above this can be seen in command </p>
<pre><code>pickup -l -t fifo -u
</code></pre>
<p>which would be split out as</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup', '-l', '-t', 'fifo', '-u']
</code></pre>
<p>but I really want it as:</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup -l -t fifo -u']
</code></pre>
<p>So my question is, how can I split out the columns but when it comes to the command column, keep the whole string as one list element rather than split out by spaces?</p>
| 9
|
2009-03-25T16:50:57Z
| 3,367,742
|
<p>Check out the <a href="http://pypi.python.org/pypi/psutil/" rel="nofollow">python.psutils</a> package.</p>
<p><code>psutil.process_iter</code> returns a generator which you can use to iterate over all processes.
<code>p.cmdline</code> is a list of each Process object's cmdline arguments, separated just the way you want.</p>
<p>You can create a dictionary of pids vs <code>(pid,cmdline,path)</code> with just one line and then use it anyway you want.</p>
<pre><code>pid_dict = dict([(p.pid, dict([('pid',p.pid), ('cmdline',p.cmdline), ('path',p.path)]))
for p in psutil.process_iter()]))
</code></pre>
| 11
|
2010-07-29T23:27:40Z
|
[
"python",
"regex",
"linux"
] |
Splitting out the output of ps using Python
| 682,446
|
<p>On Linux, the command ps aux outputs a list of processes with multiple columns for each stat. e.g.</p>
<pre><code>USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
...
postfix 22611 0.0 0.2 54136 2544 ? S 15:26 0:00 pickup -l -t fifo -u
apache 22920 0.0 1.5 198340 16588 ? S 09:58 0:05 /usr/sbin/httpd
</code></pre>
<p>I want to be able to read this in using Python and split out each row and then each column so they can be used as values.</p>
<p>For the most part, this is not a problem:</p>
<pre><code>ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
</code></pre>
<p>I can now loop through processes to get each row and split it out by spaces, for example</p>
<pre><code>sep = re.compile('[\s]+')
for row in processes:
print sep.split(row)
</code></pre>
<p>However, the problem is that the last column, the command, sometimes has spaces in. In the example above this can be seen in command </p>
<pre><code>pickup -l -t fifo -u
</code></pre>
<p>which would be split out as</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup', '-l', '-t', 'fifo', '-u']
</code></pre>
<p>but I really want it as:</p>
<pre><code>['postfix', '22611', '0.0', '0.2', '54136', '2544', '?', 'S', '15:26', '0:00', 'pickup -l -t fifo -u']
</code></pre>
<p>So my question is, how can I split out the columns but when it comes to the command column, keep the whole string as one list element rather than split out by spaces?</p>
| 9
|
2009-03-25T16:50:57Z
| 10,490,104
|
<p>Here's a nice routine and usage to get you going:</p>
<pre><code>def getProcessData():
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
# this specifies the number of splits, so the splitted lines
# will have (nfields+1) elements
nfields = len(processes[0].split()) - 1
retval = []
for row in processes[1:]:
retval.append(row.split(None, nfields))
return retval
wantpid = int(contents[0])
pstats = getProcessData()
for ps in pstats:
if (not len(ps) >= 1): continue
if (int(ps[1]) == wantpid):
print "process data:"
print "USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND"
print "%-10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %10.10s %s" % (ps[0], ps[1], ps[2], ps[3], ps[4], ps[5], ps[6], ps[7], ps[8], ps[9])
</code></pre>
| 1
|
2012-05-07T22:38:41Z
|
[
"python",
"regex",
"linux"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 682,513
|
<p>Actually <code>None</code> is much better for "magic" values:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = None):
if num_holes is None:
...
</code></pre>
<p>Now if you want complete freedom of adding more parameters:</p>
<pre><code>class Cheese():
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
self.num_holes = kwargs.get('num_holes',random_holes())
</code></pre>
<p>To better explain the concept of <code>*args</code> and <code>**kwargs</code> (you can actually change these names):</p>
<pre><code>def f(*args, **kwargs):
print 'args: ', args, ' kwargs: ', kwargs
>>> f('a')
args: ('a',) kwargs: {}
>>> f(ar='a')
args: () kwargs: {'ar': 'a'}
>>> f(1,2,param=3)
args: (1, 2) kwargs: {'param': 3}
</code></pre>
<p><a href="http://docs.python.org/reference/expressions.html#calls">http://docs.python.org/reference/expressions.html#calls</a></p>
| 542
|
2009-03-25T17:03:38Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 682,514
|
<p>Use <code>num_holes=None</code> as a default, instead. Then check for whether <code>num_holes is None</code>, and if so, randomize. That's what I generally see, anyway.</p>
<p>More radically different construction methods may warrant a classmethod that returns an instance of <code>cls</code>.</p>
| 6
|
2009-03-25T17:03:56Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 682,545
|
<p>Using <code>num_holes=None</code> as the default is fine if you are going to have just <code>__init__</code>.</p>
<p>If you want multiple, independent "constructors", you can provide these as class methods. These are usually called factory methods. In this case you could have the default for <code>num_holes</code> be <code>0</code>.</p>
<pre><code>class Cheese(object):
def __init__(self, num_holes=0):
"defaults to a solid cheese"
self.number_of_holes = num_holes
@classmethod
def random(cls):
return cls(randint(0, 100))
@classmethod
def slightly_holey(cls):
return cls(randint((0,33))
@classmethod
def very_holey(cls):
return cls(randint(66, 100))
</code></pre>
<p>Now create object like this:</p>
<pre><code>gouda = Cheese()
emmentaler = Cheese.random()
leerdammer = Cheese.slightly_holey()
</code></pre>
| 356
|
2009-03-25T17:11:24Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 682,546
|
<p>Why do you think your solution is "clunky"? Personally I would prefer one constructor with default values over multiple overloaded constructors in situations like yours (Python does not support method overloading anyway):</p>
<pre><code>def __init__(self, num_holes=None):
if num_holes is None:
# Construct a gouda
else:
# custom cheese
# common initialization
</code></pre>
<p>For really complex cases with lots of different constructors, it might be cleaner to use different factory functions instead:</p>
<pre><code>@classmethod
def create_gouda(cls):
c = Cheese()
# ...
return c
@classmethod
def create_cheddar(cls):
# ...
</code></pre>
<p>In your cheese example you might want to use a Gouda subclass of Cheese though...</p>
| 14
|
2009-03-25T17:11:35Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 682,563
|
<p>All of these answers are excellent if you want to use optional parameters, but another Pythonic possibility is to use a classmethod to generate a factory-style pseudo-constructor:</p>
<pre><code>def __init__(self, num_holes):
# do stuff with the number
@classmethod
def fromRandom(cls):
return cls( # some-random-number )
</code></pre>
| 13
|
2009-03-25T17:16:04Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 683,155
|
<p>The best answer is the one above about default arguments, but I had fun writing this, and it certainly does fit the bill for "multiple constructors". Use at your own risk.</p>
<p>What about the <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fnew%5F%5F"><strong>new</strong></a> method.</p>
<p>"Typical implementations create a new instance of the class by invoking the superclassâs <strong>new</strong>() method using super(currentclass, cls).<strong>new</strong>(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it."</p>
<p>So you can have the <strong>new</strong> method modify your class definition by attaching the appropriate constructor method.</p>
<pre><code>class Cheese(object):
def __new__(cls, *args, **kwargs):
obj = super(Cheese, cls).__new__(cls)
num_holes = kwargs.get('num_holes', random_holes())
if num_holes == 0:
cls.__init__ = cls.foomethod
else:
cls.__init__ = cls.barmethod
return obj
def foomethod(self, *args, **kwargs):
print "foomethod called as __init__ for Cheese"
def barmethod(self, *args, **kwargs):
print "barmethod called as __init__ for Cheese"
if __name__ == "__main__":
parm = Cheese(num_holes=5)
</code></pre>
| 8
|
2009-03-25T19:48:35Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 7,891,419
|
<p>Those are good ideas for your implementation, but if you are presenting a cheese making interface to a user. They don't care how many holes the cheese has or what internals go into making cheese. The user of your code just wants "gouda" or "parmesean" right?</p>
<p>So why not do this:</p>
<pre><code># cheese_user.py
from cheeses import make_gouda, make_parmesean
gouda = make_gouda()
paremesean = make_parmesean()
</code></pre>
<p>And then you can use any of the methods above to actually implement the functions:</p>
<pre><code># cheeses.py
class Cheese(object):
def __init__(self, *args, **kwargs):
#args -- tuple of anonymous arguments
#kwargs -- dictionary of named arguments
self.num_holes = kwargs.get('num_holes',random_holes())
def make_gouda():
return Cheese()
def make_paremesean():
return Cheese(num_holes=15)
</code></pre>
<p>This is a good encapsulation technique, and I think it is more Pythonic. To me this way of doing things fits more in line more with duck typing. You are simply asking for a gouda object and you don't really care what class it is.</p>
| 11
|
2011-10-25T15:06:03Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 29,919,666
|
<p>I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.</p>
<pre><code>class Gouda(Cheese):
def __init__(self):
super(Gouda).__init__(num_holes=10)
class Parmesan(Cheese):
def __init__(self):
super(Parmesan).__init__(num_holes=15)
</code></pre>
| 2
|
2015-04-28T12:33:56Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 33,545,167
|
<h3><a href="https://groups.google.com/forum/#!searchin/comp.lang.python/Re$3A$20Multiple$20constructors%22$20by$20Alex$20Martelli/comp.lang.python/E86OghKdggc/rtokcAhE1JkJ" rel="nofollow">Text from Alex Martelli</a></h3>
<p>(as mentioned by <a href="http://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python#comment1488950_682545">the comment from @ariddell</a>)</p>
<blockquote>
<p>OK, I've researched and read the posts (and the FAQ) on how to simulate
multiple constructors. Alex Martelli provided the most robust answer by
testing the number of *args and executing the appropriate section of code.
However in another post he says</p>
<blockquote>
<p>This 'overloads' the constructors based on how many arguments are
given -- how elegant (and how Pythonic...!) this is, being of course
<em>debatable</em>. Overloading on <em>types</em> would be less elegant <em>and</em> less Pythonic, though you could easily extend this idea to do it -- I would
discourage it even more strongly.</p>
</blockquote>
</blockquote>
<p>I think <em>this</em> part of my response is what makes it "robust":-).</p>
<p>In other words, the best answer to this sort of queries is most
often: yes, you can do it (and here's how), but there are better
approaches (and here they are). I didn't get <em>fully</em> into the
"here's how" and "here they are" parts, admittedly.</p>
<blockquote>
<p>However, what I need to do is <em>exactly</em> what is being discouraged, that is
creating 3 constructors both with 2 arguments where the second argument of
each is a different type. The real kicker is that in one of the
constructors, I need to check the <strong>class</strong> of the object to make sure the
method is receiving the proper object. I have no problem coding this if
this
is the way it has to be but if there are more acceptable (and Pythonic)
ways
to do this, I would appreciate some pointers.</p>
</blockquote>
<p>Why do you think you <em>NEED</em> to distinguish your processing based on
an argument's type, or class? More likely, what you want to know
about an argument (to determine different processing in different
cases) is <em>how it BEHAVES</em> -- which you can't do by testing types,
or classes; rather, you may use hasattr or try/except to find out.</p>
<p>By focusing on behavior, rather than on type-identity, you make
life easier for the client-code programmer: he or she can then
make polymorphic use of your components with any instance that
implements the needed behavior, which IS all your code needs.</p>
<p>The idea of 'overloading' -- having a callable with a single given
name that maps to multiple internal callables depending on various
conditions -- is also related to polymorphism; the only good reason
to supply a single callable that maps to multiple ones is to let
client-code use that single callable polymorphically if need be.</p>
<p>It's generally a good idea to ALSO expose the multiple callables
directly -- don't make client-code programmers go through strange
contortions to make sure the 'right' overload is invoked in the
end; when their need are non-polymorphic, let them explicitly
state as much in the simplest possible way. This does not sit in
well with 'constructors' -- which is why <em>factory functions</em> tend
to be preferable whenever any application need of some richness
and complexity is involved (factory callables that are not
functions are also OK, but meet a rarer, yet-more-involved need).</p>
<p>In Python (just like in VB, and other languages with the concept
of explicitly-named and default-valued arguments) you have another
stylistic alternative to 'multiple callables': one callable can
be explicitly used for several related purposes by supplying
different named-arguments. This can easily be overdone (and VB
supplies a LOT of examples of this style being overused!-) but,
used with taste and moderation, it can be very helpful too.</p>
<p>Let's try to see one typical example. We want to expose a class
Munger, whose instances need to be initialized with 'a lot of
data to be munged'; the 'lot of data' could be a file, a string,
or an instance of our own class DataBuffer which provides the
data-access features Munger instances need -- in fact, when we
are given a file or string, we construct a DataBuffer ourselves
and hold that anyway.</p>
<p>The 'overload' style might be:</p>
<pre><code>class Munger:
def __init__(self, data):
name = type(data).__name__
if name=='instance':
name = data.__class__.__name__
method = getattr(self, '_init_'+name)
method(data)
def _init_string(self, data):
self.data = DataBuffer(data)
def _init_file(self, data):
self.data = DataBuffer(data)
def _init_DataBuffer(self, data):
self.data = data
</code></pre>
<p>Now, this IS intended as a 'bad example', and maybe I've overdone
the badness, but I hope at least it IS clear why doing it this
way would be heavily sub-optimal. This does not exploit in any
way the polymorphism of <em>DataBuffer</em>'s own constructor, <em>AND</em>
it seriously inhibits polymorphism capabilities of client-code
(except via such tricks as naming a <em>class</em> as, say, 'string'...!).</p>
<p>It's clearly simpler to frame this as 'a Munger needs to be
passed a DataBuffer, or anything a DataBuffer may be built from':</p>
<pre><code>class Munger:
def __init__(self, data):
if not isinstance(data, DataBuffer):
data = DataBuffer(data)
self.data = data
</code></pre>
<p>at least, we have some simplicity here. Polymorphism is still
not optimal, though; if client-code wants to <em>mimic</em> a data
buffer, it needs to inherit from our DataBuffer class, even
if it's not using any of its implementation, just to satisfy
our isinstance check. At the very least, one would 'split out'
from DataBuffer the interface and implementation parts:</p>
<pre><code>class IDataBuffer:
def rewind(self):
raise TypeError, "must override .rewind method"
def nextBytes(self, N):
raise TypeError, "must override .nextBytes method"
def pushBack(self, bytes):
raise TypeError, "must override .pushBack method"
</code></pre>
<p>etc, with class DataBuffer inheriting from this (and providing
the needed overrides, of course) and the isinstance check
done against IDataBuffer. Not very Pythonic, but workable
if there are a LOT of DataBuffer methods we need -- checking
for each of them separately may become more trouble than
it's worth.</p>
<p>DataBuffer's own 'overloading' ("am I being initialized from
a file or from a string?") needs to be handled. Once again,
it would be <em>seriously</em> wrong to code:</p>
<pre><code>class DataBuffer(IDataBuffer):
def __init__(self, data):
name = type(data).__name__
if name=='instance':
name = data.__class__.__name__
method = getattr(self, '_init_'+name)
method(data)
def _init_string(self, data):
self.data = data
self.index = 0
def _init_file(self, data):
self.data = data.read()
self.index = 0
# etc etc
</code></pre>
<p>because it horribily inhibits client-code's polymorphism.
Here, all we need from a 'file object' is a .read method
we can call without arguments to supply our data -- so
why not code that directly...:</p>
<pre><code>class DataBuffer(IDataBuffer):
def __init__(self, data):
try: self.data = data.read()
except AttributeError: self.data=data
self.index = 0
# etc etc
</code></pre>
<p>this is MUCH simpler, of course. One may add some
tests at initialization to ensure the resulting data
are usable for our purposes, but it's generally no
big problem if the error (if any) comes at first
usage rather than at initialization.</p>
<p>An alternative architecture is also worth considering. DOES
client code REALLY NEED the polymorphism implicit in passing
a Munger constructor, either a file(-like) object, or a
string(-like) one, with very different implied semantics
regarding how one gets data from said object? Python libraries
give us counterexamples of that -- file-like objects and
string-like ones are generally passed through <em>separate</em>
methods; there's no real polymorphism opportunity there!</p>
<p>So...:</p>
<pre><code>class DataBuffer(IDataBuffer):
def __init__(self, data):
self.data = data
self.index = 0
# etc etc
class Munger:
def __init__(self, data):
self.data = data
# etc etc
def FileMunger(afile):
return Munger(DataBuffer(afile.read()))
def StringMunger(astring):
return Munger(DataBuffer(astring))
</code></pre>
<p>There, isn't THIS better? Two non-overloaded factory
functions, maximal simplicity in the constructors proper.</p>
<p>Client-code knows what it IS using to construct the
Munger and doesn't need the polymorphism -- it will
be clearer and more explicit and readable if it calls
FileMunger or StringMunger appropriately, and only
uses Munger's ctor directly for those cases where it
needs to reuse some existing IDataBuffer instance.</p>
<p>If very occasionally a polymorphic use may benefit
the client-code author, we can add a further factory
function for that purpose only:</p>
<pre><code>def AnyMunger(mystery):
if isinstance(mystery, IDataBuffer):
return Munger(mystery)
else:
try: return FileMunger(mystery)
except AttributeError: return StringMunger(mystery)
</code></pre>
<p>However, one doesn't go around just adding such stuff
<em>unless its appropriateness is clearly shown by some
specific use-case/scenario</em> -- "you ain't gonna need it"
is a GREAT design principle:-) [XP rules...!-)].</p>
<p>Now, this IS of course a toy-level example, but I hope
that just because of this it may show up the issues more
clearly -- and perhaps convince you to rethink your
design in simpler and more usable ways.</p>
<p>Alex</p>
| 2
|
2015-11-05T12:57:06Z
|
[
"coding-style",
"python"
] |
What is a clean, pythonic way to have multiple constructors in Python?
| 682,504
|
<p>I can't find a definitive answer for this. AFAIK, you can't have multiple <code>__init__</code> functions in a Python class. So what is a good way to solve this problem? </p>
<p>Suppose I have an class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese-objects...</p>
<ul>
<li>one that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code></li>
<li>and one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code></li>
</ul>
<p>I can think of only one way to do this, but that seems kinda clunky:</p>
<pre><code>class Cheese():
def __init__(self, num_holes = 0):
if (num_holes == 0):
# randomize number_of_holes
else:
number_of_holes = num_holes
</code></pre>
<p>What do you say? Is there a better way?</p>
| 385
|
2009-03-25T17:00:21Z
| 38,885,481
|
<p>One should definitely prefer the solutions already posted, but since no one mentioned this solution yet, I think it is worth mentioning for completeness.</p>
<p>The <code>@classmethod</code> approach can be modified to provide an alternative constructor which does not invoke the default constructor (<code>__init__</code>). Instead, an instance is created using <code>__new__</code>. </p>
<p>This could be used if the type of initialization cannot be selected based on the type of the constructor argument, and the constructors do not share code. </p>
<p>Example:</p>
<pre><code>class MyClass(set):
def __init__(self, filename):
self._value = load_from_file(filename)
@classmethod
def from_somewhere(cls, somename):
obj = cls.__new__(cls) # Does not call __init__
obj._value = load_from_somewhere(somename)
return obj
</code></pre>
| 0
|
2016-08-11T00:20:55Z
|
[
"coding-style",
"python"
] |
Python Virtual Machine architecture diagrams/references
| 682,675
|
<p>Someone could point out sites/books where I can find introductory documentation about the architecture of the Python VM? </p>
<p>I'm interested in the C version, but if there are easy-to-follow references about other implementations it could be helpful too.</p>
<p>I'm trying to find any kind of resources of higher level than plain source code (however, UML diagrams or something like that would be nice) And also, information about the design decisions involved, including tradeoffs between the different factors (performance, stability, simplicity).</p>
| 10
|
2009-03-25T17:42:49Z
| 682,897
|
<p>You should be able to find the information you need at <a href="http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup" rel="nofollow">http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup</a></p>
<p>If that's too low level for you, try</p>
<ul>
<li><a href="http://www.python.org/dev/peps/pep-0339/" rel="nofollow">http://www.python.org/dev/peps/pep-0339/</a></li>
<li><a href="http://codespeak.net/pypy/dist/pypy/doc/interpreter.html" rel="nofollow">http://codespeak.net/pypy/dist/pypy/doc/interpreter.html</a></li>
<li><a href="http://thermalnoise.wordpress.com/2007/12/30/exploring-python-bytecode/" rel="nofollow">http://thermalnoise.wordpress.com/2007/12/30/exploring-python-bytecode/</a></li>
<li><a href="https://docs.python.org/library/dis.html#python-bytecode-instructions" rel="nofollow">https://docs.python.org/library/dis.html#python-bytecode-instructions</a></li>
<li><a href="http://wiki.python.org/moin/ByteplayDoc" rel="nofollow">http://wiki.python.org/moin/ByteplayDoc</a></li>
<li><a href="http://peak.telecommunity.com/DevCenter/BytecodeAssembler" rel="nofollow">http://peak.telecommunity.com/DevCenter/BytecodeAssembler</a></li>
<li><a href="http://nedbatchelder.com/blog/200804/wicked_hack_python_bytecode_tracing.html" rel="nofollow">http://nedbatchelder.com/blog/200804/wicked_hack_python_bytecode_tracing.html</a></li>
</ul>
| 9
|
2009-03-25T18:36:39Z
|
[
"python",
"architecture",
"language-design",
"vm-implementation"
] |
Python Desktop Integration - Drag and drop
| 682,692
|
<p>I have a pygame window that I want to know when a file has been dragged and dropped onto it. I only need to be able to fetch the name of the file. How can this be accomplished?</p>
| 3
|
2009-03-25T17:47:20Z
| 683,454
|
<p>Here's a <a href="http://mail.python.org/pipermail/python-win32/2008-April/007406.html" rel="nofollow">forum thread</a> that might be what you're looking for. </p>
<p>And <a href="http://mail.python.org/pipermail/python-win32/2008-September/008209.html" rel="nofollow">another</a> forum.</p>
<p>And a link to the <a href="http://msdn.microsoft.com/en-us/library/ms678486%28VS.85%29.aspx" rel="nofollow">msdn page</a>. You'll probably want the <a href="http://docs.activestate.com/activepython/2.4/pywin32/pythoncom.html" rel="nofollow">pythoncom</a> library.</p>
| 4
|
2009-03-25T21:06:32Z
|
[
"python",
"drag-and-drop",
"pygame",
"desktop-integration"
] |
Python Desktop Integration - Drag and drop
| 682,692
|
<p>I have a pygame window that I want to know when a file has been dragged and dropped onto it. I only need to be able to fetch the name of the file. How can this be accomplished?</p>
| 3
|
2009-03-25T17:47:20Z
| 3,887,565
|
<p>one option for a similar effect is is to use pygame's scrap module so you can copy-paste into the window, your program would just need to look for ctr-V events.</p>
<p>On this XFCE desktop I'm using
If I hit ctrl-C with a file selected, the file name shows up when I type </p>
<pre><code>pygame.scrap.init()
types= pygame.scrap.get_types()
print dict(
[type,pygame.scrap.get(type)]
for type intypes
)
</code></pre>
| 0
|
2010-10-08T03:46:34Z
|
[
"python",
"drag-and-drop",
"pygame",
"desktop-integration"
] |
What to do with "The input line is too long" error message?
| 682,799
|
<p>I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. </p>
<p>When I try to call the command, I'm getting an error: <code>The input line is too long</code>.</p>
<p>I'm guessing there's a <code>255 character limit</code> (its built using a C system call, but I couldn't find the limitations on that either).</p>
<p>I tried changing the directory with <code>os.chdir()</code> to reduce the folder trail lengths, but when I try using <code>os.system()</code> with <code>"..\folder\filename"</code> it apparently can't handle relative path names. Is there any way to get around this limit or get it to recognize relative paths?</p>
| 10
|
2009-03-25T18:08:42Z
| 682,807
|
<p>Assuming you're using windows, from the backslashes, you could write a .bat file from python and then <code>os.system()</code> on that. It's a hack.</p>
| 1
|
2009-03-25T18:11:08Z
|
[
"python",
"command-line",
"windows-console"
] |
What to do with "The input line is too long" error message?
| 682,799
|
<p>I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names. </p>
<p>When I try to call the command, I'm getting an error: <code>The input line is too long</code>.</p>
<p>I'm guessing there's a <code>255 character limit</code> (its built using a C system call, but I couldn't find the limitations on that either).</p>
<p>I tried changing the directory with <code>os.chdir()</code> to reduce the folder trail lengths, but when I try using <code>os.system()</code> with <code>"..\folder\filename"</code> it apparently can't handle relative path names. Is there any way to get around this limit or get it to recognize relative paths?</p>
| 10
|
2009-03-25T18:08:42Z
| 682,815
|
<p>Make sure when you're using '\' in your strings that they're being properly escaped.</p>
<p>Python uses the '\' as the escape character, so the string <code>"..\folder\filename"</code> evaluates to <code>"..folderfilename"</code> since an escaped f is still an f.</p>
<p>You probably want to use</p>
<pre><code>r"..\folder\filename"
</code></pre>
<p>or </p>
<pre><code>"..\\folder\\filename"
</code></pre>
| 1
|
2009-03-25T18:13:55Z
|
[
"python",
"command-line",
"windows-console"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.