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
sequence
Django Template Variables and Javascript
298,772
<p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p> <p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
92
2008-11-18T13:52:31Z
18,094,087
<p>When the variable is returned by Django it turns all quotes into <code>&amp;quot;</code>. Using <code>{{someDjangoVariable|safe}}</code> causes a Javascript error. </p> <p>To fix this use Javascript <code>.replace</code>:</p> <pre><code>&lt;script type="text/javascript"&gt; var json = "{{someDjangoVariable}}".replace(/&amp;quot;/g,"\"") &lt;/script&gt; </code></pre>
5
2013-08-07T03:22:00Z
[ "javascript", "python", "django", "google-app-engine", "django-templates" ]
Django Template Variables and Javascript
298,772
<p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p> <p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
92
2008-11-18T13:52:31Z
25,538,871
<p><strong>CAUTION</strong> Check ticket <a href="https://code.djangoproject.com/ticket/17419">#17419</a> for discussion on adding similar tag into Django core and possible XSS vulnerabilities introduced by using this template tag with user generated data. <a href="https://code.djangoproject.com/ticket/17419#comment:27">Comment</a> from amacneil discusses most of the concerns raised in the ticket.</p> <hr> <p>I think the most flexible and handy way of doing this is to define a template filter for variables you want to use in JS code. This allows you to ensure, that your data is properly escaped and you can use it with complex data structures, such as <code>dict</code> and <code>list</code>. That's why I write this answer despite there is an accepted answer with a lot of upvotes.</p> <p>Here is an example of template filter:</p> <pre><code>// myapp/templatetags/js.py from django.utils.safestring import mark_safe from django.template import Library import json register = Library() @register.filter(is_safe=True) def js(obj): return mark_safe(json.dumps(obj)) </code></pre> <p>This template filters converts variable to JSON string. You can use it like so:</p> <pre><code>// myapp/templates/example.html {% load js %} &lt;script type="text/javascript"&gt; var someVar = {{ some_var | js }}; &lt;/script&gt; </code></pre>
21
2014-08-28T00:14:04Z
[ "javascript", "python", "django", "google-app-engine", "django-templates" ]
Django Template Variables and Javascript
298,772
<p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p> <p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
92
2008-11-18T13:52:31Z
29,032,335
<p>Here is what I'm doing very easily: I modified my base.html file for my template and put that at the bottom:</p> <pre><code>{% if DJdata %} &lt;script type="text/javascript"&gt; (function () {window.DJdata = {{DJdata|safe}};})(); &lt;/script&gt; {% endif %} </code></pre> <p>then when I want to use a variable in the javascript files, I create a DJdata dictionary and I add it to the context by a json : <code>context['DJdata'] = json.dumps(DJdata)</code></p> <p>Hope it helps!</p>
3
2015-03-13T12:31:04Z
[ "javascript", "python", "django", "google-app-engine", "django-templates" ]
Django Template Variables and Javascript
298,772
<p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p> <p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
92
2008-11-18T13:52:31Z
32,998,283
<p>I was facing simillar issue and answer suggested by S.Lott worked for me.</p> <pre><code>&lt;script type="text/javascript"&gt; var a = "{{someDjangoVariable}}" &lt;/script&gt; </code></pre> <p>However I would like to point out <strong>major implementation limitation</strong> here. If you are planning to put your javascript code in different file and include that file in your template. This won't work.</p> <p>This works only when you main template and javascript code is in same file. Probably django team can address this limitation.</p>
3
2015-10-07T17:03:39Z
[ "javascript", "python", "django", "google-app-engine", "django-templates" ]
Form (or Formset?) to handle multiple table rows in Django
298,779
<p>I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which corresponds to one row in a MySQL table, but how do I produce a form that iterates over all the movie titles in the database and produces a form that lets you rate lots of them at once? </p> <p>At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean.</p> <p>Currently, my views.py has this code:</p> <pre><code>def survey(request): ScoreFormSet = formset_factory(ScoreForm) if request.method == 'POST': formset = ScoreFormSet(request.POST, request.FILES) if formset.is_valid(): return HttpResponseRedirect('/') else: formset = ScoreFormSet() return render_to_response('cf/survey.html', { 'formset':formset, }) </code></pre> <p>And my survey.html has this:</p> <pre><code>&lt;form action="/survey/" method="POST"&gt; &lt;table&gt; {{ formset }} &lt;/table&gt; &lt;input type = "submit" value = "Submit"&gt; &lt;/form&gt; </code></pre> <p>Oh, and the definition of ScoreForm and Score from models.py are:</p> <pre><code>class Score(models.Model): movie = models.ForeignKey(Movie) score = models.IntegerField() user = models.ForeignKey(User) class ScoreForm(ModelForm): class Meta: model = Score </code></pre> <p>So, in case the above is not clear, what I'm aiming to produce is a form which has one row per movie, and each row shows a title, and has a box to allow the user to enter their score.</p> <p>If anyone can point me at the right sort of approach to this, I'd be most grateful.</p>
3
2008-11-18T13:55:17Z
298,835
<p>"At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean."</p> <p>You need to get a queryset. And you need to provide that queryset to your form as initial data. See <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset" rel="nofollow">using initial data with a formset</a> for the code.</p> <pre><code>initial = [ list of { dictionaries }, one per form ] </code></pre> <p>Interestingly, this is a direct feature of the model API through the <code>values</code> method of a queryset.</p>
3
2008-11-18T14:12:17Z
[ "python", "django" ]
Form (or Formset?) to handle multiple table rows in Django
298,779
<p>I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which corresponds to one row in a MySQL table, but how do I produce a form that iterates over all the movie titles in the database and produces a form that lets you rate lots of them at once? </p> <p>At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean.</p> <p>Currently, my views.py has this code:</p> <pre><code>def survey(request): ScoreFormSet = formset_factory(ScoreForm) if request.method == 'POST': formset = ScoreFormSet(request.POST, request.FILES) if formset.is_valid(): return HttpResponseRedirect('/') else: formset = ScoreFormSet() return render_to_response('cf/survey.html', { 'formset':formset, }) </code></pre> <p>And my survey.html has this:</p> <pre><code>&lt;form action="/survey/" method="POST"&gt; &lt;table&gt; {{ formset }} &lt;/table&gt; &lt;input type = "submit" value = "Submit"&gt; &lt;/form&gt; </code></pre> <p>Oh, and the definition of ScoreForm and Score from models.py are:</p> <pre><code>class Score(models.Model): movie = models.ForeignKey(Movie) score = models.IntegerField() user = models.ForeignKey(User) class ScoreForm(ModelForm): class Meta: model = Score </code></pre> <p>So, in case the above is not clear, what I'm aiming to produce is a form which has one row per movie, and each row shows a title, and has a box to allow the user to enter their score.</p> <p>If anyone can point me at the right sort of approach to this, I'd be most grateful.</p>
3
2008-11-18T13:55:17Z
494,872
<p>I have found my answer, using modelformset_factory instead formset_factory solves the problem, Thanks...</p>
1
2009-01-30T08:22:07Z
[ "python", "django" ]
Python xml.dom.minidom.parse() function ignores DTDs
298,782
<p>I have the following Python code: </p> <pre><code>import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] </code></pre> <p>which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; &lt;!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"&gt; </code></pre> <p>so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?</p>
3
2008-11-18T13:56:04Z
298,827
<p>I believe you need to switch from expat to xmlproc.<br /> See: <a href="http://code.activestate.com/recipes/220472/" rel="nofollow">http://code.activestate.com/recipes/220472/</a></p>
0
2008-11-18T14:09:52Z
[ "python", "xml" ]
Python xml.dom.minidom.parse() function ignores DTDs
298,782
<p>I have the following Python code: </p> <pre><code>import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] </code></pre> <p>which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; &lt;!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"&gt; </code></pre> <p>so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?</p>
3
2008-11-18T13:56:04Z
298,833
<p>See <a href="http://stackoverflow.com/questions/15798/how-do-i-validate-xml-against-a-dtd-file-in-python">this question</a> - the accepted answer is to use <a href="http://codespeak.net/lxml/validation.html" rel="nofollow">lxml validation</a>.</p>
4
2008-11-18T14:11:14Z
[ "python", "xml" ]
Python xml.dom.minidom.parse() function ignores DTDs
298,782
<p>I have the following Python code: </p> <pre><code>import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] </code></pre> <p>which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; &lt;!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"&gt; </code></pre> <p>so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?</p>
3
2008-11-18T13:56:04Z
298,854
<p>I recommend lxml over xmlproc because the PyXML package (containing xmlproc) is not being developed any more; the latest Python version that PyXML can be used with is 2.4.</p>
1
2008-11-18T14:20:30Z
[ "python", "xml" ]
Python xml.dom.minidom.parse() function ignores DTDs
298,782
<p>I have the following Python code: </p> <pre><code>import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] </code></pre> <p>which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; &lt;!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"&gt; </code></pre> <p>so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?</p>
3
2008-11-18T13:56:04Z
298,978
<p>Just by way of explanation: Python xml.dom.minidom and xml.sax use the expat parser by default, which is a non-validating parser. It may read the DTD in order to do entity replacement, but it won't validate against the DTD.</p> <p>gimel and Tim recommend lxml, which is a nicely pythonic binding for the libxml2 and libxslt libraries. It supports validation against a DTD. I've been using lxml, and I like it a lot.</p>
3
2008-11-18T15:04:18Z
[ "python", "xml" ]
Python xml.dom.minidom.parse() function ignores DTDs
298,782
<p>I have the following Python code: </p> <pre><code>import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName) except xml.parsers.expat.ExpatError, e: return e.args[0] </code></pre> <p>which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it completely ignores the DTD specified at the top of the XML file: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; &lt;!DOCTYPE ServerConfig SYSTEM "ServerConfig.dtd"&gt; </code></pre> <p>so it doesn't notice when mandatory elements are missing, for example. How can I switch on DTD checking?</p>
3
2008-11-18T13:56:04Z
299,278
<p>Just for the record, this is what my code looks like now: </p> <pre><code>from lxml import etree try: parser = etree.XMLParser(dtd_validation=True) domTree = etree.parse(myXMLFileName, parser=parser) except etree.XMLSyntaxError, e: return e.args[0] </code></pre>
2
2008-11-18T16:33:11Z
[ "python", "xml" ]
Python Distutils
298,828
<p>I was unable to install <a href="http://cython.org/" rel="nofollow">cython</a> due to <a href="http://epydoc.sourceforge.net/stdlib/distutils.version.StrictVersion-class.html" rel="nofollow">strict version numbering class</a> of <a href="http://www.python.org/doc/2.5.2/dist/dist.html" rel="nofollow">Distutils</a>. For example binutils-2.18.50-20080109-2.tar.gz cannot be used along with <a href="http://mingw.org/" rel="nofollow">MinGW</a> for installing cython. The <a href="http://epydoc.sourceforge.net/stdlib/distutils.version.StrictVersion-class.html" rel="nofollow">source code documentation</a> says that "The rationale for this version numbering system will be explained in the distutils documentation." I am unable to find the rationale. </p> <p>My question: What is the rationale for this version numbering system?</p>
0
2008-11-18T14:10:22Z
299,591
<p>You could try <a href="http://www.develer.com/oss/GccWinBinaries" rel="nofollow">this</a> unofficial MinGW distribution, it has a simple install process that sets up distutils to use it for compiling extensions.</p>
0
2008-11-18T18:01:24Z
[ "python", "mingw", "distutils", "cython" ]
Python Distutils
298,828
<p>I was unable to install <a href="http://cython.org/" rel="nofollow">cython</a> due to <a href="http://epydoc.sourceforge.net/stdlib/distutils.version.StrictVersion-class.html" rel="nofollow">strict version numbering class</a> of <a href="http://www.python.org/doc/2.5.2/dist/dist.html" rel="nofollow">Distutils</a>. For example binutils-2.18.50-20080109-2.tar.gz cannot be used along with <a href="http://mingw.org/" rel="nofollow">MinGW</a> for installing cython. The <a href="http://epydoc.sourceforge.net/stdlib/distutils.version.StrictVersion-class.html" rel="nofollow">source code documentation</a> says that "The rationale for this version numbering system will be explained in the distutils documentation." I am unable to find the rationale. </p> <p>My question: What is the rationale for this version numbering system?</p>
0
2008-11-18T14:10:22Z
510,898
<p>That's just another stupidness of distutils. I personally remove this annoying check in my distutils installation on every windows machine I have to use.</p> <p>Installing another mingw version would work as long as it passes the version check - but really, the whole idea of checking version of the tools does not make much sense.</p>
1
2009-02-04T11:04:31Z
[ "python", "mingw", "distutils", "cython" ]
Python Distutils
298,828
<p>I was unable to install <a href="http://cython.org/" rel="nofollow">cython</a> due to <a href="http://epydoc.sourceforge.net/stdlib/distutils.version.StrictVersion-class.html" rel="nofollow">strict version numbering class</a> of <a href="http://www.python.org/doc/2.5.2/dist/dist.html" rel="nofollow">Distutils</a>. For example binutils-2.18.50-20080109-2.tar.gz cannot be used along with <a href="http://mingw.org/" rel="nofollow">MinGW</a> for installing cython. The <a href="http://epydoc.sourceforge.net/stdlib/distutils.version.StrictVersion-class.html" rel="nofollow">source code documentation</a> says that "The rationale for this version numbering system will be explained in the distutils documentation." I am unable to find the rationale. </p> <p>My question: What is the rationale for this version numbering system?</p>
0
2008-11-18T14:10:22Z
7,715,596
<p>I guess that the idea was to recommend that projects use a version number compatible with the StrictVersion class for easy sorting (i.e. comparison of versions, to know that 1.0 is newer than 1.0b). The problem is that it never really took off, and the original author of distutils moved on to other projects. When setuptools was started as a set of new features and monkey-patches to distutils, instead of using Version classes it defined an algorithm to convert any version number to a sortable representation. A few years ago, Tarek Ziadé took over maintenance and development of distutils and worked on a PEP with the distutils community to define a new version number specification. This PEP, PEP 386, has been accepted and implemented in distutils2. It was defined with the goals of supporting features used by the community (alpha/beta/candidate versions, post-release markers for example) and still allow sorting. It’s more constraining than the setuptools’ also, but much more useful than StrictVersion and LooseVersion.</p>
0
2011-10-10T16:06:42Z
[ "python", "mingw", "distutils", "cython" ]
How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?
299,249
<p>I am familiar with using the <em>os.system</em> to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: <code>c:\test&gt;java -jar run_this.jar required_parameter.ext</code> ? I'm a python newbie so details are greatly appreciated. Thanks in advance. </p>
3
2008-11-18T16:22:39Z
299,262
<p>In general: Use os.chdir to change the directory of the parent process, then os.system to run the jar file. If you need to keep Python's working directory stable, you need to chdir back to original working directory - you need to record that with os.getcwd().</p> <p>On Unix: Create a child process with os.fork explicitly. In the parent, wait for the child with os.waitpid. In the child, use os.chdir, then os.exec to run java.</p>
1
2008-11-18T16:27:24Z
[ "python" ]
How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?
299,249
<p>I am familiar with using the <em>os.system</em> to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script that does the following: <code>c:\test&gt;java -jar run_this.jar required_parameter.ext</code> ? I'm a python newbie so details are greatly appreciated. Thanks in advance. </p>
3
2008-11-18T16:22:39Z
299,377
<p>Here is a small script to get you started. There are ways to make it "better", but not knowing the full scope of what you are trying to accomplish this should be sufficient.</p> <pre><code>import os if __name__ == "__main__": startingDir = os.getcwd() # save our current directory testDir = "\\test" # note that \ is windows specific, and we have to escape it os.chdir(testDir) # change to our test directory os.system("java -jar run_this.jar required_paramter.ext") os.chdir(startingDir) # change back to where we started </code></pre>
5
2008-11-18T16:59:37Z
[ "python" ]
How do I change directory back to my original working directory with Python?
299,446
<p>I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. </p> <pre><code>def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) </code></pre> <p>note: I think my code formatting is off - not sure why. My apologies in advance</p>
5
2008-11-18T17:19:47Z
299,462
<p>You simply need to add the line:</p> <pre><code>os.chdir(owd) </code></pre> <p>Just a note this was also answered in your other <A href="http://stackoverflow.com/questions/299249/how-can-i-get-my-python-version-25-script-to-run-a-jar-file-inside-a-folder-ins" rel="nofollow">question</A>.</p>
10
2008-11-18T17:24:48Z
[ "python" ]
How do I change directory back to my original working directory with Python?
299,446
<p>I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. </p> <pre><code>def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) </code></pre> <p>note: I think my code formatting is off - not sure why. My apologies in advance</p>
5
2008-11-18T17:19:47Z
299,464
<p>os.chdir(owd) should do the trick (like you've done when changing to testDir)</p>
2
2008-11-18T17:25:20Z
[ "python" ]
How do I change directory back to my original working directory with Python?
299,446
<p>I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. </p> <pre><code>def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) </code></pre> <p>note: I think my code formatting is off - not sure why. My apologies in advance</p>
5
2008-11-18T17:19:47Z
300,204
<p>The advice to use <code>os.chdir(owd)</code> is good. It would be wise to put the code which needs the changed directory in a <code>try:finally</code> block (or in python 2.6 and later, a <code>with:</code> block.) That reduces the risk that you will accidentally put a <code>return</code> in the code before the change back to the original directory.</p> <pre><code>def run(): owd = os.getcwd() try: #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) finally: #change dir back to original working directory (owd) os.chdir(owd) </code></pre>
4
2008-11-18T21:34:16Z
[ "python" ]
How do I change directory back to my original working directory with Python?
299,446
<p>I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. </p> <pre><code>def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) </code></pre> <p>note: I think my code formatting is off - not sure why. My apologies in advance</p>
5
2008-11-18T17:19:47Z
5,963,196
<p>Python is case sensitive so when typing the path make sure it's the same as the directory you want to set.</p> <pre><code>import os os.getcwd() os.chdir('C:\\') </code></pre>
1
2011-05-11T11:05:26Z
[ "python" ]
How do I change directory back to my original working directory with Python?
299,446
<p>I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution. </p> <pre><code>def run(): owd = os.getcwd() #first change dir to build_dir path os.chdir(testDir) #run jar from test directory os.system(cmd) #change dir back to original working directory (owd) </code></pre> <p>note: I think my code formatting is off - not sure why. My apologies in advance</p>
5
2008-11-18T17:19:47Z
37,996,581
<p>A context manager is a very appropriate tool for this job:</p> <pre><code>from contextlib import contextmanager @contextmanager def cwd(path): oldpwd=os.getcwd() os.chdir(path) try: yield finally: os.chdir(oldpwd) </code></pre> <p>...used as:</p> <pre><code>os.chdir('/tmp') # for testing purposes, be in a known directory print 'before context manager: %s' % os.getcwd() with cwd('/'): # code inside this block, and only inside this block, is in the new directory print 'inside context manager: %s' % os.getcwd() print 'after context manager: %s' % os.getcwd() </code></pre> <p>...which will yield something like:</p> <pre><code>before context manager: /tmp inside context manager: / after context manager: /tmp </code></pre> <p>This is actually <strong>superior</strong> to the <code>cd -</code> shell builtin, inasmuch as it also takes care of changing directories back when a block is exited due to an exception being thrown.</p> <hr> <p>For your specific use case, this would instead be:</p> <pre><code>with cwd(testDir): os.system(cmd) </code></pre> <hr> <p>Another option to consider is using <code>subprocess.call()</code> instead of <code>os.system()</code>, which will let you specify a working directory for the command to run:</p> <pre><code># note: better to modify this to not need shell=True if possible subprocess.call(cmd, cwd=testDir, shell=True) </code></pre> <p>...which would prevent you from needing to change the interpreter's directory at all.</p>
1
2016-06-23T16:00:24Z
[ "python" ]
Validating with an XML schema in Python
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
67
2008-11-18T17:59:56Z
299,611
<p>lxml provides etree.DTD</p> <p>from the tests on <a href="http://lxml.de/api/lxml.tests.test_dtd-pysrc.html" rel="nofollow">http://lxml.de/api/lxml.tests.test_dtd-pysrc.html</a></p> <pre><code>... root = etree.XML(_bytes("&lt;b/&gt;")) dtd = etree.DTD(BytesIO("&lt;!ELEMENT b EMPTY&gt;")) self.assert_(dtd.validate(root)) </code></pre>
7
2008-11-18T18:09:40Z
[ "python", "xml", "validation", "xsd" ]
Validating with an XML schema in Python
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
67
2008-11-18T17:59:56Z
299,635
<p>I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check <a href="http://lxml.de/validation.html">Validation with lxml</a>. The page also lists how to use lxml to validate with other schema types.</p>
42
2008-11-18T18:16:53Z
[ "python", "xml", "validation", "xsd" ]
Validating with an XML schema in Python
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
67
2008-11-18T17:59:56Z
300,877
<p>If you're working with dtd you might enjoy this <a href="http://code.activestate.com/recipes/220472/" rel="nofollow">recipe</a></p>
3
2008-11-19T02:53:41Z
[ "python", "xml", "validation", "xsd" ]
Validating with an XML schema in Python
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
67
2008-11-18T17:59:56Z
1,946,225
<p>The PyXB package at <a href="http://pyxb.sourceforge.net/">http://pyxb.sourceforge.net/</a> generates validating bindings for Python from XML schema documents. It handles almost every schema construct and supports multiple namespaces.</p>
12
2009-12-22T12:54:33Z
[ "python", "xml", "validation", "xsd" ]
Validating with an XML schema in Python
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
67
2008-11-18T17:59:56Z
5,566,672
<p>As for "pure python" solutions: the package index lists:</p> <ul> <li><a href="http://pypi.python.org/pypi/pyxsd">pyxsd</a>, the description says it uses xml.etree.cElementTree, which is not "pure python" (but included in stdlib), but source code indicates that it falls back to xml.etree.ElementTree, so this would count as pure python. Haven't used it, but according to the docs, it does do schema validation.</li> <li><a href="http://pypi.python.org/pypi/minixsv">minixsv</a>: 'a lightweight XML schema validator written in "pure" Python'. However, the description says "currently a subset of the XML schema standard is supported", so this may not be enough.</li> <li><a href="http://pypi.python.org/pypi/XSV">XSV</a>, which I think is used for the W3C's online xsd validator (it still seems to use the old pyxml package, which I think is no longer maintained)</li> </ul>
20
2011-04-06T12:53:52Z
[ "python", "xml", "validation", "xsd" ]
Validating with an XML schema in Python
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
67
2008-11-18T17:59:56Z
32,228,567
<p>There are two ways(actually there are more) that you could do this.<br> 1. using <a href="http://lxml.de/" rel="nofollow">lxml</a><br> <code>pip install lxml</code> </p> <pre><code>from lxml import etree, objectify from lxml.etree import XMLSyntaxError def xml_validator(some_xml_string, xsd_file='/path/to/my_schema_file.xsd'): try: schema = etree.XMLSchema(file=xsd_file) parser = objectify.makeparser(schema=schema) objectify.fromstring(some_xml_string, parser) print "YEAH!, my xml file has validated" except XMLSyntaxError: #handle exception here print "Oh NO!, my xml file does not validate" pass xml_file = open('my_xml_file.xml', 'r') xml_string = xml_file.read() xml_file.close() xml_validator(xml_string, '/path/to/my_schema_file.xsd') </code></pre> <ol start="2"> <li>Use <a href="http://xmlsoft.org/xmllint.html" rel="nofollow">xmllint</a> from the commandline. xmllint comes installed in many linux distributions.</li> </ol> <p><code>&gt;&gt; xmllint --format --pretty 1 --load-trace --debug --schema /path/to/my_schema_file.xsd /path/to/my_xml_file.xml</code></p>
3
2015-08-26T13:51:27Z
[ "python", "xml", "validation", "xsd" ]
Validating with an XML schema in Python
299,588
<p>I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python?</p> <p>I'd prefer something using the standard library, but I can install a third-party package if necessary.</p>
67
2008-11-18T17:59:56Z
37,972,081
<h2>An example of a simple validator in Python3 using the popular library <a href="http://lxml.de/" rel="nofollow">lxml</a></h2> <p><strong>Installation lxml</strong></p> <pre><code>pip install lxml </code></pre> <p>If you get an error like <em>"Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?"</em>, try to do this first:</p> <pre><code># Debian/Ubuntu apt-get install python-dev python3-dev libxml2-dev libxslt-dev # Fedora 23+ dnf install python-devel python3-devel libxml2-devel libxslt-devel </code></pre> <hr> <p><strong>The simplest validator</strong></p> <p>Let's create simplest <strong>validator.py</strong></p> <pre><code>from lxml import etree def validate(xml_path: str, xsd_path: str) -&gt; bool: xmlschema_doc = etree.parse(xsd_path) xmlschema = etree.XMLSchema(xmlschema_doc) xml_doc = etree.parse(xml_path) result = xmlschema.validate(xml_doc) return result </code></pre> <p>then write and run <strong>main.py</strong></p> <pre><code>from validator import validate if validate("path/to/file.xml", "path/to/scheme.xsd"): print('Valid! :)') else: print('Not valid! :(') </code></pre> <hr> <p><strong>A little bit of OOP</strong></p> <p>In order to validate more than one file, there is no need to create an <em>XMLSchema</em> object every time, therefore:</p> <p><strong>validator.py</strong></p> <pre><code>from lxml import etree class Validator: def __init__(self, xsd_path: str): xmlschema_doc = etree.parse(xsd_path) self.xmlschema = etree.XMLSchema(xmlschema_doc) def validate(self, xml_path: str) -&gt; bool: xml_doc = etree.parse(xml_path) result = self.xmlschema.validate(xml_doc) return result </code></pre> <p>Now we can validate all files in the directory as follows:</p> <p><strong>main.py</strong></p> <pre><code>import os from validator import Validator validator = Validator("path/to/scheme.xsd") # The directory with XML files XML_DIR = "path/to/directory" for file_name in os.listdir(XML_DIR): print('{}: '.format(file_name), end='') file_path = '{}/{}'.format(XML_DIR, file_name) if validator.validate(file_path): print('Valid! :)') else: print('Not valid! :(') </code></pre> <hr> <p>For more options read here: <a href="http://lxml.de/validation.html#xmlschema" rel="nofollow">Validation with lxml</a></p>
1
2016-06-22T15:14:40Z
[ "python", "xml", "validation", "xsd" ]
Calling Java (or python or perl) from a PHP script
299,913
<p>I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up and running in a few days). So, I'm now thinking of going with PHP instead, as it's the method for creating dynamic web content I'm most familiar with, and I know I can get something working quickly.</p> <p>My application, while simple, is probably going to be doing some reasonably complex AI stuff, and it may be that libraries don't exist for what I need in PHP. So I'm wondering how easy / possible it is for a PHP script to "call" a Java program or Python script or a program or script in another language. It's not entirely clear to me what exactly I mean by "call" in this context, but I guess I probably mean that ideally I'd like to define a function in, let's say Java, and then be able to call it from PHP. If that's not possible, then I guess my best bet (assuming I do go with PHP) will be to pass control directly to the external program explicitly through a POST or GET to a CGI program or similar.</p> <p>Feel free to convince me I should stick with Django, although I'm really at the point where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex...</p> <p>Alternatively, anyone who can offer any advice on linking PHP and other languages, that'll be grateful received.</p>
3
2008-11-18T19:51:54Z
299,941
<p>For an easy access of Java classes from PHP scripts you can use a php-java bridge.</p> <p>There is a open source solution: <a href="http://php-java-bridge.sourceforge.net/pjb/" rel="nofollow">http://php-java-bridge.sourceforge.net/pjb/</a> <br>or a solution from Zend (<a href="http://www.zend.com/en/products/platform/product-comparison/java-bridge" rel="nofollow">http://www.zend.com/en/products/platform/product-comparison/java-bridge</a>).</p> <p>I'm more familiar with the later, and it's very easy and intuitive to use.</p>
2
2008-11-18T20:01:46Z
[ "java", "php", "python", "dynamic-linking" ]
Calling Java (or python or perl) from a PHP script
299,913
<p>I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up and running in a few days). So, I'm now thinking of going with PHP instead, as it's the method for creating dynamic web content I'm most familiar with, and I know I can get something working quickly.</p> <p>My application, while simple, is probably going to be doing some reasonably complex AI stuff, and it may be that libraries don't exist for what I need in PHP. So I'm wondering how easy / possible it is for a PHP script to "call" a Java program or Python script or a program or script in another language. It's not entirely clear to me what exactly I mean by "call" in this context, but I guess I probably mean that ideally I'd like to define a function in, let's say Java, and then be able to call it from PHP. If that's not possible, then I guess my best bet (assuming I do go with PHP) will be to pass control directly to the external program explicitly through a POST or GET to a CGI program or similar.</p> <p>Feel free to convince me I should stick with Django, although I'm really at the point where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex...</p> <p>Alternatively, anyone who can offer any advice on linking PHP and other languages, that'll be grateful received.</p>
3
2008-11-18T19:51:54Z
300,035
<p>"where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex" </p> <p>Common problem.</p> <p>Root cause: Too much programming.</p> <p>Solution. Do less programming. Seriously.</p> <p>Define the Django model. Use the default admin pages to see if it's right. Fix the model. Regenerate the database. Look at the default admin pages. Repeat until the default admin pages work correctly and simply.</p> <p>Once it's right in the default admin pages, you have a model that works. It's testable. And the automatic stuff is hooked up correctly. Choices are defined correctly. Computations are in the model mmethods. Queries work. Now you can start working on other presentations of the data.</p> <p>Django generally starts (and ends) with the model. The forms, view and templates are derived from the model.</p>
4
2008-11-18T20:31:06Z
[ "java", "php", "python", "dynamic-linking" ]
Is it possible to bind an event against a menu instead of a menu item in wxPython?
300,032
<p>Nothing to add</p>
0
2008-11-18T20:29:33Z
300,045
<p>Do you want an event when your menu is opened? Use <code>EVT_MENU_OPEN(func)</code> (<code>wxMenuEvent</code>). But it's not in particular precise. As the documentation says, it is only sent once if you open a menu. For another event you have to close it and open another menu again. I.e in between, you can open other menus (by hovering other items in the menubar), and the event won't be sent again. </p> <p>What do you need this for? Probably there is another way to do it, instead of listening for this kind of event. </p> <p>If you want an event for all items of a menu, use <code>EVT_MENU_RANGE(id1, id2, func)</code> (it's using <code>wxCommandEvent</code>). All IDs starting from <code>id1</code> up to and including <code>id2</code> will be connected to the given event handler. Using a range instead of connecting each item separate will provide for better performance, as there are fewer items in the event-handler list.</p>
2
2008-11-18T20:34:58Z
[ "python", "wxpython" ]
Why is fuse not using the class supplied in file_class
300,047
<p>I have a python fuse project based on the Xmp example in the fuse documentation. I have included a small piece of the code to show how this works. For some reason get_file does get called and the class gets created, but instead of fuse calling .read() on the class from get_file (file_class) fuse keeps calling Dstorage.read() which defeats the purpose in moving the read function out of that class.</p> <pre><code>class Dstorage(Fuse, Distributor): def get_file(self, server, path, flags, *mode): pass # This does some work and passes back an instance of # a class very similar to XmpFile def main(self, *a, **kw): self.file_class = self.get_file return Fuse.main(self, *a, **kw) </code></pre> <p>I have my code hosted on launchpad, you can download it with this command.<br /> <strike>bzr co https://code.launchpad.net/~asa-ayers/+junk/dstorage</strike><br /> bzr branch lp:~asa-ayers/dstorage/trunk </p> <p><strong>solution:</strong><br /> I used a proxy class that subclasses the one I needed and in the constructor I get the instance of the class I need and overwrite all of the proxy's methods to simply call the instance methods.</p>
1
2008-11-18T20:35:12Z
301,437
<p>Looking at the code of the Fuse class (which is a maze of twisty little passages creating method proxies), I see this bit (which is a closure used to create a setter inside <code>Fuse.MethodProxy._add_class_type</code>, line 865):</p> <pre><code> def setter(self, xcls): setattr(self, type + '_class', xcls) for m in inits: self.mdic[m] = xcls for m in proxied: if hasattr(xcls, m): self.mdic[m] = self.proxyclass(m) </code></pre> <p>When you do <code>self.file_class = self.get_file</code>, this gets called with <code>self.get_file</code>, which is a bound method. The loop over proxied attributes is expecting to be able to get the attributes off the class you set, to put them into its <code>mdic</code> proxy dictionary after wrapping them, but they aren't there, because it's a bound method, rather than a class. Since it can't find them, it reverts to calling them on <code>Dstorage</code>.</p> <p>So, long story short, you can't use a callable that returns an instance (kind of a pseudo-class) instead of a class here, because Fuse is introspecting the object that you set to find the methods it should call. </p> <p>You need to assign a class to <code>file_class</code> - if you need to refer back to the parent instance, you can use the nested class trick they show in the docs.</p>
1
2008-11-19T10:10:28Z
[ "python", "fuse" ]
How to unquote a urlencoded unicode string in python?
300,445
<p>I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode. Apparently urllib.unquote does not support unicode.</p>
38
2008-11-18T22:49:27Z
300,531
<pre><code>def unquote(text): def unicode_unquoter(match): return unichr(int(match.group(1),16)) return re.sub(r'%u([0-9a-fA-F]{4})',unicode_unquoter,text) </code></pre>
8
2008-11-18T23:22:24Z
[ "python", "unicode", "urllib" ]
How to unquote a urlencoded unicode string in python?
300,445
<p>I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode. Apparently urllib.unquote does not support unicode.</p>
38
2008-11-18T22:49:27Z
300,533
<p>%uXXXX is a <a href="http://en.wikipedia.org/wiki/Percent-encoding#Non-standard_implementations">non-standard encoding scheme</a> that has been rejected by the w3c, despite the fact that an implementation continues to live on in JavaScript land.</p> <p>The more common technique seems to be to UTF-8 encode the string and then % escape the resulting bytes using %XX. This scheme is supported by urllib.unquote:</p> <pre><code>&gt;&gt;&gt; urllib2.unquote("%0a") '\n' </code></pre> <p>Unfortunately, if you really <strong>need</strong> to support %uXXXX, you will probably have to roll your own decoder. Otherwise, it is likely to be far more preferable to simply UTF-8 encode your unicode and then % escape the resulting bytes.</p> <p>A more complete example:</p> <pre><code>&gt;&gt;&gt; u"Tanım" u'Tan\u0131m' &gt;&gt;&gt; url = urllib.quote(u"Tanım".encode('utf8')) &gt;&gt;&gt; urllib.unquote(url).decode('utf8') u'Tan\u0131m' </code></pre>
60
2008-11-18T23:22:44Z
[ "python", "unicode", "urllib" ]
How to unquote a urlencoded unicode string in python?
300,445
<p>I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode. Apparently urllib.unquote does not support unicode.</p>
38
2008-11-18T22:49:27Z
300,556
<p>This will do it if you absolutely have to have this (I really do agree with the cries of "non-standard"):</p> <pre><code>from urllib import unquote def unquote_u(source): result = unquote(source) if '%u' in result: result = result.replace('%u','\\u').decode('unicode_escape') return result print unquote_u('Tan%u0131m') &gt; Tanım </code></pre>
6
2008-11-18T23:32:49Z
[ "python", "unicode", "urllib" ]
How to unquote a urlencoded unicode string in python?
300,445
<p>I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode. Apparently urllib.unquote does not support unicode.</p>
38
2008-11-18T22:49:27Z
370,365
<p>there is a bug in the above version where it freaks out sometimes when there are both ascii encoded and unicode encoded characters in the string. I think its specifically when there are characters from the upper 128 range like '\xab' in addition to unicode.</p> <p>eg. "%5B%AB%u03E1%BB%5D" causes this error.</p> <p>I found if you just did the unicode ones first, the problem went away:</p> <pre><code>def unquote_u(source): result = source if '%u' in result: result = result.replace('%u','\\u').decode('unicode_escape') result = unquote(result) return result </code></pre>
3
2008-12-16T03:13:58Z
[ "python", "unicode", "urllib" ]
Python - Backslash Quoting in String Literals
301,068
<p>I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\"' &gt;&gt;&gt; foo 'baz ""' </code></pre> <p>So instead of <code>baz "\"</code> like I want I'm getting <code>baz ""</code>. If I then try to escape the backslash, it doesn't help either:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\\"' &gt;&gt;&gt; foo 'baz "\\"' </code></pre> <p>Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?</p>
34
2008-11-19T05:22:47Z
301,075
<p>You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\\"' &gt;&gt;&gt; foo 'baz "\\"' &gt;&gt;&gt; print foo baz "\" </code></pre> <p>Incidentally, there's another string form which might be a bit clearer:</p> <pre><code>&gt;&gt;&gt; print r'baz "\"' baz "\" </code></pre>
52
2008-11-19T05:26:43Z
[ "python", "string" ]
Python - Backslash Quoting in String Literals
301,068
<p>I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\"' &gt;&gt;&gt; foo 'baz ""' </code></pre> <p>So instead of <code>baz "\"</code> like I want I'm getting <code>baz ""</code>. If I then try to escape the backslash, it doesn't help either:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\\"' &gt;&gt;&gt; foo 'baz "\\"' </code></pre> <p>Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?</p>
34
2008-11-19T05:22:47Z
301,076
<p>Use a raw string:</p> <pre><code>&gt;&gt;&gt; foo = r'baz "\"' &gt;&gt;&gt; foo 'baz "\\"' </code></pre> <p>Note that although it looks wrong, it's actually right. There is only one backslash in the string <code>foo</code>.</p> <p>This happens because when you just type <code>foo</code> at the prompt, python displays the result of <code>__repr__()</code> on the string. This leads to the following (notice only one backslash and no quotes around the <code>print</code>ed string):</p> <pre><code>&gt;&gt;&gt; foo = r'baz "\"' &gt;&gt;&gt; foo 'baz "\\"' &gt;&gt;&gt; print foo baz "\" </code></pre> <p>And let's keep going because there's more backslash tricks. If you want to have a backslash at the end of the string and use the method above you'll come across a problem:</p> <pre><code>&gt;&gt;&gt; foo = r'baz \' File "&lt;stdin&gt;", line 1 foo = r'baz \' ^ SyntaxError: EOL while scanning single-quoted string </code></pre> <p>Raw strings don't work properly when you do that. You have to use a regular string and escape your backslashes:</p> <pre><code>&gt;&gt;&gt; foo = 'baz \\' &gt;&gt;&gt; print foo baz \ </code></pre> <p>However, if you're working with Windows file names, you're in for some pain. What you want to do is use forward slashes and the <code>os.path.normpath()</code> function:</p> <pre><code>myfile = os.path.normpath('c:/folder/subfolder/file.txt') open(myfile) </code></pre> <p>This will save a lot of escaping and hair-tearing. <a href="http://pythonconquerstheuniverse.blogspot.com/2008/06/python-gotcha-raw-strings-and.html">This page</a> was handy when going through this a while ago.</p>
17
2008-11-19T05:29:45Z
[ "python", "string" ]
Python - Backslash Quoting in String Literals
301,068
<p>I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\"' &gt;&gt;&gt; foo 'baz ""' </code></pre> <p>So instead of <code>baz "\"</code> like I want I'm getting <code>baz ""</code>. If I then try to escape the backslash, it doesn't help either:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\\"' &gt;&gt;&gt; foo 'baz "\\"' </code></pre> <p>Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?</p>
34
2008-11-19T05:22:47Z
301,293
<p>What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.</p> <pre><code>infile = open('c:/folder/subfolder/file.txt') </code></pre> <p>The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using <code>os.system</code> or the <code>subprocess</code> module).</p>
2
2008-11-19T08:17:59Z
[ "python", "string" ]
Python - Backslash Quoting in String Literals
301,068
<p>I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\"' &gt;&gt;&gt; foo 'baz ""' </code></pre> <p>So instead of <code>baz "\"</code> like I want I'm getting <code>baz ""</code>. If I then try to escape the backslash, it doesn't help either:</p> <pre><code>&gt;&gt;&gt; foo = 'baz "\\"' &gt;&gt;&gt; foo 'baz "\\"' </code></pre> <p>Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?</p>
34
2008-11-19T05:22:47Z
19,167,835
<p>Another way to end a string with a backslash is to end the string with a backslash followed by a space, and then call the <code>.strip()</code> function on the string. </p> <p>I was trying to concatenate two string variables and have them separated by a backslash, so i used the following:</p> <pre><code>newString = string1 + "\ ".strip() + string2 </code></pre>
-1
2013-10-03T19:40:54Z
[ "python", "string" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
301,139
<p>You can use <a href="http://www.python.org/doc/2.5.2/ref/exec.html"><code>exec</code></a>:</p> <pre><code>exec "import myapp.commands.%s" % command </code></pre>
6
2008-11-19T06:12:54Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
301,146
<p>With Python older than 2.7/3.1, that's pretty much how you do it. For newer versions, see <code>importlib.import_module</code> <a href="https://docs.python.org/2/library/importlib.html#importlib.import_module" rel="nofollow">for 2.7+</a> and <a href="https://docs.python.org/3.1/library/importlib.html#importlib.import_module" rel="nofollow">for 3.1+</a>.</p> <p>You can use <code>exec</code> if you want to as well.</p> <p>Note you can import a list of modules by doing this:</p> <pre><code>&gt;&gt;&gt; moduleNames = ['sys', 'os', 're', 'unittest'] &gt;&gt;&gt; moduleNames ['sys', 'os', 're', 'unittest'] &gt;&gt;&gt; modules = map(__import__, moduleNames) </code></pre> <p>Ripped straight from <a href="http://www.diveintopython.net/functional_programming/dynamic_import.html" rel="nofollow">Dive Into Python</a>.</p>
176
2008-11-19T06:17:18Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
301,165
<p>Use the <a href="http://docs.python.org/library/imp.html#imp.load_module">imp module</a>, or the more direct <a href="http://docs.python.org/library/functions.html#__import__"><code>__import__()</code></a> function.</p>
19
2008-11-19T06:28:28Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
301,298
<p>As mentioned the <a href="http://docs.python.org/library/imp.html" rel="nofollow">imp</a> module provides you loading functions:</p> <pre><code>imp.load_source(name, path) imp.load_compiled(name, path) </code></pre> <p>I've used these before to perform something similar. </p> <p>In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:</p> <pre><code>import imp import os def load_from_file(filepath): class_inst = None expected_class = 'MyClass' mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1]) if file_ext.lower() == '.py': py_mod = imp.load_source(mod_name, filepath) elif file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) if hasattr(py_mod, expected_class): class_inst = getattr(py_mod, expected_class)() return class_inst </code></pre>
107
2008-11-19T08:21:25Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
302,359
<p>It sounds like what you really want is a plugin architecture. </p> <p>You should have a look at the <a href="http://peak.telecommunity.com/DevCenter/setuptools#extensible-applications-and-frameworks" rel="nofollow">entry points</a> functionality provided by the setuptools package. It offers a great way to discover plugins that are loaded for your application.</p>
0
2008-11-19T15:52:19Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
3,529,271
<p>The following worked for me:</p> <pre><code>import sys, glob sys.path.append('/home/marc/python/importtest/modus') fl = glob.glob('modus/*.py') modulist = [] adapters=[] for i in range(len(fl)): fl[i] = fl[i].split('/')[1] fl[i] = fl[i][0:(len(fl[i])-3)] modulist.append(getattr(__import__(fl[i]),fl[i])) adapters.append(modulist[i]()) </code></pre> <p>It loads modules from the folder 'modus'. The modules have a single class with the same name as the module name. E.g. the file modus/modu1.py contains:</p> <pre><code>class modu1(): def __init__(self): self.x=1 print self.x </code></pre> <p>The result is a list of dynamically loaded classes "adapters".</p>
-5
2010-08-20T08:24:14Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
8,028,743
<p>If you want it in your locals:</p> <pre><code>&gt;&gt;&gt; mod = 'sys' &gt;&gt;&gt; locals()['my_module'] = __import__(mod) &gt;&gt;&gt; my_module.version '2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]' </code></pre> <p>same would work with <code>globals()</code></p>
10
2011-11-06T17:08:08Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
14,000,967
<p>The recommended way for Python 2.7 and later is to use <a href="http://docs.python.org/2/library/importlib.html#importlib.import_module"><code>importlib</code></a> module:</p> <pre><code>my_module = importlib.import_module('os.path') </code></pre>
142
2012-12-22T07:33:46Z
[ "python", "python-import" ]
Dynamic module import in Python
301,134
<p>I'm writing a Python application that takes as a command as an argument, for example:</p> <pre><code>$ python myapp.py command1 </code></pre> <p>I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:</p> <pre><code>myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py </code></pre> <p>So I want the application to find the available command modules at runtime and execute the appropriate one.</p> <p>Currently this is implemented something like:</p> <pre><code>command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() </code></pre> <p>This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.</p> <p>Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.</p>
281
2008-11-19T06:09:57Z
17,394,692
<p>Similar as @monkut 's solution but reusable and error tolerant described here <a href="http://stamat.wordpress.com/dynamic-module-import-in-python/" rel="nofollow">http://stamat.wordpress.com/dynamic-module-import-in-python/</a>:</p> <pre><code>import os import imp def importFromURI(uri, absl): mod = None if not absl: uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri)) path, fname = os.path.split(uri) mname, ext = os.path.splitext(fname) if os.path.exists(os.path.join(path,mname)+'.pyc'): try: return imp.load_compiled(mname, uri) except: pass if os.path.exists(os.path.join(path,mname)+'.py'): try: return imp.load_source(mname, uri) except: pass return mod </code></pre>
1
2013-06-30T20:46:19Z
[ "python", "python-import" ]
loadComponentFromURL falls over and dies, howto do CPR?
301,239
<p>Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automation. Now it seems we have knocked down many bottles related to show stopper errors with one bottle remaining. OO hangs after a while. </p> <p>It happens where you see this line '&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' in the code </p> <p>What is the correct way for me to handle a stalled Open Office process. could you please provide useful links, and give me a good suggestion on the way out.<br /> Also one more question. </p> <p>Sum up:<br /> * How to handle a stalled Open Office instance?<br /> * How to make conversion with java headless, so I dont have a GUI popping up all the time wasting memory.<br /> * also any general suggestions on code quality, optimizations and general coding standards will be most appreciated. <hr /></p> <p>Traceback (innermost last):<br /> File "dcmail.py", line 184, in ?<br /> File "dcmail.py", line 174, in main<br /> File "C:\DCMail\digestemails.py", line 126, in process_inbox<br /> File "C:\DCMail\digestemails.py", line 258, in _convert<br /> File "C:\DCMail\digestemails.py", line 284, in _choose_conversion_type<br /> File "C:\DCMail\digestemails.py", line 287, in _open_office_convert<br /> File "C:\DCMail\digestemails.py", line 299, in _load_attachment_to_convert<br /> com.sun.star.lang.DisposedException: java.io.EOFException<br /> at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDi spatcher.run(java_remote_bridge.java:176) </p> <p>com.sun.star.lang.DisposedException: com.sun.star.lang.DisposedException: java.i o.EOFException </p> <p>Just to clear up this exception only throws when I kill the open office process. Otherwise the program just waits for open office to complete. Indefinitely<br /> <hr /></p> <p>The Code (with non functional code tags) </p> <p>[code] </p> <blockquote> <blockquote> <p>#ghost script handles these file types<br /> GS_WHITELIST=[".pdf"]<br /> #Open Office handles these file types<br /> OO_WHITELIST=[".xls", ".doc", ".rtf", ".tif", ".tiff"]<br /> #whitelist is used to check against any unsupported files.<br /> WHITELIST=GS_WHITELIST + OO_WHITELIST </p> </blockquote> </blockquote> <pre><code>def _get_service_manager(self): try: self._context=Bootstrap.bootstrap(); self._xMultiCompFactory=self._context.getServiceManager() self._xcomponentloader=UnoRuntime.queryInterface(XComponentLoader, self._xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", self._context)) except: raise OpenOfficeException("Exception Occurred with Open Office") def _choose_conversion_type(self,fn): ext=os.path.splitext(fn)[1] if ext in GS_WHITELIST: self._ghostscript_convert_to_tiff(fn) elif ext in OO_WHITELIST: self._open_office_convert(fn) def _open_office_convert(self,fn): self._load_attachment_to_convert(fn) self._save_as_pdf(fn) self._ghostscript_convert_to_tiff(fn) def _load_attachment_to_convert(self, file): file=self._create_UNO_File_URL(file) properties=[] p=PropertyValue() p.Name="Hidden" p.Value=True properties.append(p) properties=tuple(properties) self._doc=self._xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; here is line 299 def _create_UNO_File_URL(self, filepath): try: file=str("file:///" + filepath) file=file.replace("\\", "/") except MalformedURLException, e: raise e return file def _save_as_pdf(self, docSource): dirName=os.path.dirname(docSource) baseName=os.path.basename(docSource) baseName, ext=os.path.splitext(baseName) dirTmpPdfConverted=os.path.join(dirName + DIR + PDF_TEMP_CONVERT_DIR) if not os.path.exists(dirTmpPdfConverted): os.makedirs(dirTmpPdfConverted) pdfDest=os.path.join(dirTmpPdfConverted + DIR + baseName + ".pdf") url_save=self._create_UNO_File_URL(pdfDest) properties=self._create_properties(ext) try: try: self._xstorable=UnoRuntime.queryInterface(XStorable, self._doc); self._xstorable.storeToURL(url_save, properties) except AttributeError,e: self.logger.info("pdf file already created (" + str(e) + ")") raise e finally: try: self._doc.dispose() except: raise def _create_properties(self,ext): properties=[] p=PropertyValue() p.Name="Overwrite" p.Value=True properties.append(p) p=PropertyValue() p.Name="FilterName" if ext==".doc": p.Value='writer_pdf_Export' elif ext==".rtf": p.Value='writer_pdf_Export' elif ext==".xls": p.Value='calc_pdf_Export' elif ext==".tif": p.Value='draw_pdf_Export' elif ext==".tiff": p.Value='draw_pdf_Export' properties.append(p) return tuple(properties) def _ghostscript_convert_to_tiff(self, docSource): dest, source=self._get_dest_and_source_conversion_file(docSource) try: command = ' '.join([ self._ghostscriptPath + 'gswin32c.exe', '-q', '-dNOPAUSE', '-dBATCH', '-r500', '-sDEVICE=tiffg4', '-sPAPERSIZE=a4', '-sOutputFile=%s %s' % (dest, source), ]) self._execute_ghostscript(command) self.convertedTifDocList.append(dest) except OSError, e: self.logger.info(e) raise e except TypeError, (e): raise e except AttributeError, (e): raise e except: raise </code></pre> <p>[/code]</p>
0
2008-11-19T07:29:41Z
301,413
<p>OpenOffice.org has a "-headless" parameter to run it without a GUI. I'm not sure this actually frees up all resources that would be spent on GUI. Here's how I run my server-side headless instance:</p> <pre><code>soffice -headless -accept="socket,port=1234;urp" -display :25 </code></pre> <p>I can't tell what's causing the stalling problems for your Python script, but you might want to to check out <a href="http://www.artofsolving.com/opensource/pyodconverter" rel="nofollow">PyODConverter</a>, and see what this script does differently to maybe catch the error causing your trouble.</p>
1
2008-11-19T09:48:45Z
[ "java", "python", "jython", "openoffice.org" ]
loadComponentFromURL falls over and dies, howto do CPR?
301,239
<p>Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automation. Now it seems we have knocked down many bottles related to show stopper errors with one bottle remaining. OO hangs after a while. </p> <p>It happens where you see this line '&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' in the code </p> <p>What is the correct way for me to handle a stalled Open Office process. could you please provide useful links, and give me a good suggestion on the way out.<br /> Also one more question. </p> <p>Sum up:<br /> * How to handle a stalled Open Office instance?<br /> * How to make conversion with java headless, so I dont have a GUI popping up all the time wasting memory.<br /> * also any general suggestions on code quality, optimizations and general coding standards will be most appreciated. <hr /></p> <p>Traceback (innermost last):<br /> File "dcmail.py", line 184, in ?<br /> File "dcmail.py", line 174, in main<br /> File "C:\DCMail\digestemails.py", line 126, in process_inbox<br /> File "C:\DCMail\digestemails.py", line 258, in _convert<br /> File "C:\DCMail\digestemails.py", line 284, in _choose_conversion_type<br /> File "C:\DCMail\digestemails.py", line 287, in _open_office_convert<br /> File "C:\DCMail\digestemails.py", line 299, in _load_attachment_to_convert<br /> com.sun.star.lang.DisposedException: java.io.EOFException<br /> at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge$MessageDi spatcher.run(java_remote_bridge.java:176) </p> <p>com.sun.star.lang.DisposedException: com.sun.star.lang.DisposedException: java.i o.EOFException </p> <p>Just to clear up this exception only throws when I kill the open office process. Otherwise the program just waits for open office to complete. Indefinitely<br /> <hr /></p> <p>The Code (with non functional code tags) </p> <p>[code] </p> <blockquote> <blockquote> <p>#ghost script handles these file types<br /> GS_WHITELIST=[".pdf"]<br /> #Open Office handles these file types<br /> OO_WHITELIST=[".xls", ".doc", ".rtf", ".tif", ".tiff"]<br /> #whitelist is used to check against any unsupported files.<br /> WHITELIST=GS_WHITELIST + OO_WHITELIST </p> </blockquote> </blockquote> <pre><code>def _get_service_manager(self): try: self._context=Bootstrap.bootstrap(); self._xMultiCompFactory=self._context.getServiceManager() self._xcomponentloader=UnoRuntime.queryInterface(XComponentLoader, self._xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", self._context)) except: raise OpenOfficeException("Exception Occurred with Open Office") def _choose_conversion_type(self,fn): ext=os.path.splitext(fn)[1] if ext in GS_WHITELIST: self._ghostscript_convert_to_tiff(fn) elif ext in OO_WHITELIST: self._open_office_convert(fn) def _open_office_convert(self,fn): self._load_attachment_to_convert(fn) self._save_as_pdf(fn) self._ghostscript_convert_to_tiff(fn) def _load_attachment_to_convert(self, file): file=self._create_UNO_File_URL(file) properties=[] p=PropertyValue() p.Name="Hidden" p.Value=True properties.append(p) properties=tuple(properties) self._doc=self._xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; here is line 299 def _create_UNO_File_URL(self, filepath): try: file=str("file:///" + filepath) file=file.replace("\\", "/") except MalformedURLException, e: raise e return file def _save_as_pdf(self, docSource): dirName=os.path.dirname(docSource) baseName=os.path.basename(docSource) baseName, ext=os.path.splitext(baseName) dirTmpPdfConverted=os.path.join(dirName + DIR + PDF_TEMP_CONVERT_DIR) if not os.path.exists(dirTmpPdfConverted): os.makedirs(dirTmpPdfConverted) pdfDest=os.path.join(dirTmpPdfConverted + DIR + baseName + ".pdf") url_save=self._create_UNO_File_URL(pdfDest) properties=self._create_properties(ext) try: try: self._xstorable=UnoRuntime.queryInterface(XStorable, self._doc); self._xstorable.storeToURL(url_save, properties) except AttributeError,e: self.logger.info("pdf file already created (" + str(e) + ")") raise e finally: try: self._doc.dispose() except: raise def _create_properties(self,ext): properties=[] p=PropertyValue() p.Name="Overwrite" p.Value=True properties.append(p) p=PropertyValue() p.Name="FilterName" if ext==".doc": p.Value='writer_pdf_Export' elif ext==".rtf": p.Value='writer_pdf_Export' elif ext==".xls": p.Value='calc_pdf_Export' elif ext==".tif": p.Value='draw_pdf_Export' elif ext==".tiff": p.Value='draw_pdf_Export' properties.append(p) return tuple(properties) def _ghostscript_convert_to_tiff(self, docSource): dest, source=self._get_dest_and_source_conversion_file(docSource) try: command = ' '.join([ self._ghostscriptPath + 'gswin32c.exe', '-q', '-dNOPAUSE', '-dBATCH', '-r500', '-sDEVICE=tiffg4', '-sPAPERSIZE=a4', '-sOutputFile=%s %s' % (dest, source), ]) self._execute_ghostscript(command) self.convertedTifDocList.append(dest) except OSError, e: self.logger.info(e) raise e except TypeError, (e): raise e except AttributeError, (e): raise e except: raise </code></pre> <p>[/code]</p>
0
2008-11-19T07:29:41Z
301,620
<p>The icky solution is to have a monitor for the OpenOffice process. If your monitor knows the PID and has privileges, it can get CPU time used every few seconds. If OO hangs in a stalled state (no more CPU), then the monitor can kill it. </p> <p>The easiest way to handle this is to have the "wrapper" that's firing off the open office task watch it while it runs and kill it when it hangs. The parent process has to do a wait anyway, so it may as well monitor.</p> <p>If OpenOffuce hangs in a loop, then it's tougher to spot. CPU usually goes through the roof, stays there, and the priority plummets to the lowest possible priority. Processing or hung? Judgement call. You have to let it hang like this for "a while" (pick a random duration, 432 seconds (3 dozen dozen) for instance; you'll always be second-guessing yourself.)</p>
1
2008-11-19T11:26:53Z
[ "java", "python", "jython", "openoffice.org" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
301,533
<p>In .NET, C# 3.0 and VB9 provide excellent support for working with XML using LINQ to XML:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb387061.aspx">LINQ to XML Overview</a></p>
6
2008-11-19T10:48:54Z
[ "java", ".net", "python", "xml", "ruby" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
301,538
<p>either C# or VB.Net using LiNQ to XML. LiNQ to XML is very very powerful and easy to implement</p>
2
2008-11-19T10:50:18Z
[ "java", ".net", "python", "xml", "ruby" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
301,630
<p>A dynamic language rules for this. Why? The mappings are easy to code and change. You don't have to recompile and rebuild.</p> <p>Indeed, with a little cleverness, you can have your "XML XPATH to a Tag -> DB table-field" mappings as disjoint blocks of Python code that your main application imports.</p> <p>The block of Python code <strong>is</strong> your configuration file. It's not an <code>.ini</code> file or a <code>.properties</code> file that describes a configuration. It <strong>is</strong> the configuration.</p> <p>We use Python, xml.etree and the SQLAlchemy (to separate the SQL out of your programs) for this because we're up and running with very little effort and a great deal of flexibility.</p> <p><hr /></p> <p><strong>source.py</strong></p> <pre><code>"""A particular XML parser. Formats change, so sometimes this changes, too.""" import xml.etree.ElementTree as xml class SSXML_Source( object ): ns0= "urn:schemas-microsoft-com:office:spreadsheet" ns1= "urn:schemas-microsoft-com:office:excel" def __init__( self, aFileName, *sheets ): """Initialize a XML source. XXX - Create better sheet filtering here, in the constructor. @param aFileName: the file name. """ super( SSXML_Source, self ).__init__( aFileName ) self.log= logging.getLogger( "source.PCIX_XLS" ) self.dom= etree.parse( aFileName ).getroot() def sheets( self ): for wb in self.dom.getiterator("{%s}Workbook" % ( self.ns0, ) ): for ws in wb.getiterator( "{%s}Worksheet" % ( self.ns0, ) ): yield ws def rows( self ): for s in self.sheets(): print s.attrib["{%s}Name" % ( self.ns0, ) ] for t in s.getiterator( "{%s}Table" % ( self.ns0, ) ): for r in t.getiterator( "{%s}Row" % ( self.ns0, ) ): # The XML may not be really useful. # In some cases, you may have to convert to something useful yield r </code></pre> <p><strong>model.py</strong></p> <pre><code>"""This is your target object. It's part of the problem domain; it rarely changes. """ class MyTargetObject( object ): def __init__( self ): self.someAttr= "" self.anotherAttr= "" self.this= 0 self.that= 3.14159 def aMethod( self ): """etc.""" pass </code></pre> <p><strong>builder_today.py</strong> One of many mapping configurations</p> <pre><code>"""One of many builders. This changes all the time to fit specific needs and situations. The goal is to keep this short and to-the-point so that it has the mapping and nothing but the mapping. """ import model class MyTargetBuilder( object ): def makeFromXML( self, element ): result= model.MyTargetObject() result.someAttr= element.findtext( "Some" ) result.anotherAttr= element.findtext( "Another" ) result.this= int( element.findtext( "This" ) ) result.that= float( element.findtext( "that" ) ) return result </code></pre> <p><strong>loader.py</strong></p> <pre><code>"""An application that maps from XML to the domain object using a configurable "builder". """ import model import source import builder_1 import builder_2 import builder_today # Configure this: pick a builder is appropriate for the data: b= builder_today.MyTargetBuilder() s= source.SSXML_Source( sys.argv[1] ) for r in s.rows(): data= b.makeFromXML( r ) # ... persist data with a DB save or file write </code></pre> <p><hr /></p> <p>To make changes, you can correct a builder or create a new builder. You adjust the loader source to identify which builder will be used. You can, without too much trouble, make the selection of builder a command-line parameter. Dynamic imports in dynamic languages seem like overkill to me, but they are handy.</p>
17
2008-11-19T11:31:34Z
[ "java", ".net", "python", "xml", "ruby" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
301,649
<h2>XSLT</h2> <p>I suggest using <a href="http://en.wikipedia.org/wiki/Xslt">XSLT templates</a> to transform the XML into INSERT statements (or whatever you need), as required.<br /> You should be able to invoke XSLT from any of the languages you mention. </p> <p>This will result in a lot less code than doing it the long way round. </p>
8
2008-11-19T11:40:58Z
[ "java", ".net", "python", "xml", "ruby" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
301,847
<p>I'll toss in a suggestion for <a href="http://code.whytheluckystiff.net/hpricot/" rel="nofollow">Hpricot</a>, a popular Ruby XML parser (although there are many similar options).</p> <p>Example:</p> <p>Given the following XML:</p> <pre><code>&lt;Export&gt; &lt;Product&gt; &lt;SKU&gt;403276&lt;/SKU&gt; &lt;ItemName&gt;Trivet&lt;/ItemName&gt; &lt;CollectionNo&gt;0&lt;/CollectionNo&gt; &lt;Pages&gt;0&lt;/Pages&gt; &lt;/Product&gt; &lt;/Export&gt; </code></pre> <p>You parse simply by:</p> <pre><code>FIELDS = %w[SKU ItemName CollectionNo Pages] doc = Hpricot.parse(File.read("my.xml")) (doc/:product).each do |xml_product| product = Product.new for field in FIELDS product[field] = (xml_product/field.intern).first.innerHTML end product.save end </code></pre> <p>It sounds like your application would be very fit for a <a href="http://www.rubyonrails.org" rel="nofollow">Rails</a> application, You could quickly prototype what you need, you've got direct interaction with your database of choice and you can output the data however you need to.</p> <p>Here's another great resource page for <a href="http://code.whytheluckystiff.net/hpricot/wiki/HpricotXML" rel="nofollow">parsing XML with Hpricot</a> that might help as well as the <a href="http://code.whytheluckystiff.net/doc/hpricot/" rel="nofollow">documentation</a>.</p>
4
2008-11-19T13:13:16Z
[ "java", ".net", "python", "xml", "ruby" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
301,859
<p>For quick turnaround I've found <a href="http://groovy.codehaus.org/Processing+XML" rel="nofollow">Groovy</a> very useful.</p>
4
2008-11-19T13:17:41Z
[ "java", ".net", "python", "xml", "ruby" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
326,700
<p>An interesting solution could be Ruby. Simply use XML->Object mappers and then use an object-relational-mapper (ORM) to put it inside a database. I had to do a short talk on XML Mapping with ruby, you could look at the slides and see what you like best: <a href="http://www.marc-seeger.de/2008/11/25/ruby-xml-mapping/" rel="nofollow">http://www.marc-seeger.de/2008/11/25/ruby-xml-mapping/</a></p> <p>As for the ORM: Active Record or Datamapper should be the way to go</p>
2
2008-11-28T21:15:01Z
[ "java", ".net", "python", "xml", "ruby" ]
Which language is easiest and fastest to work with XML content?
301,493
<p>We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)</p>
13
2008-11-19T10:35:18Z
326,726
<p>ECMAScript handles XML pretty nicely using E4X ("ECMAScript for XML"). This can be seen in Adobe's latest version of ActionScript, version 3. I believe JavaScript 2 (to be released with Firefox 4, I think) will support E4X as well.</p> <p>Not sure about the support of the standalone JavaScript interpreters (i.e. Rhino, et al) of this, which is what matters most to you I suppose... But if it looks good to you, you can always look up their support for it (and report back to us :-)).</p> <p>See <a href="http://en.wikipedia.org/wiki/E4X#Example" rel="nofollow">http://en.wikipedia.org/wiki/E4X#Example</a> for a simple example.</p>
2
2008-11-28T21:27:31Z
[ "java", ".net", "python", "xml", "ruby" ]
Convert a string with date and time to a date
301,528
<p>I've got this date time string:</p> <pre><code>post["date"] = "2007-07-18 10:03:19" </code></pre> <p>I'd like to extract just "2007-07-18" as a date. I've seen some reference to <code>strptime</code> but I'm not sure how to use it. How can I extract the date from this string?</p>
18
2008-11-19T10:45:01Z
301,537
<p>In your case, just use split:</p> <pre><code>&gt;&gt;&gt; d1="2007-07-18 10:03:19" &gt;&gt;&gt; d1.split()[0] '2007-07-18' &gt;&gt;&gt; </code></pre> <p>(The 1st part after splitting with whitespace)</p> <p>If you insist on using <code>strptime</code>, the format is <code>"%Y-%m-%d %H:%M:%S"</code> :</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strptime(d1,"%Y-%m-%d %H:%M:%S") time.struct_time(tm_year=2007, tm_mon=7, tm_mday=18, tm_hour=10, tm_min=3, tm_sec=19, tm_wday=2, tm_yday=199, tm_isdst=-1) &gt;&gt;&gt; time.strftime("%Y-%m-%d", _) '2007-07-18' &gt;&gt;&gt; </code></pre>
5
2008-11-19T10:50:03Z
[ "python", "datetime" ]
Convert a string with date and time to a date
301,528
<p>I've got this date time string:</p> <pre><code>post["date"] = "2007-07-18 10:03:19" </code></pre> <p>I'd like to extract just "2007-07-18" as a date. I've seen some reference to <code>strptime</code> but I'm not sure how to use it. How can I extract the date from this string?</p>
18
2008-11-19T10:45:01Z
301,542
<p>Probably not what you are looking for but you could just split the string:</p> <pre><code>post["date"].split()[0] </code></pre> <p>would give you <code>'2007-07-18'</code></p>
2
2008-11-19T10:51:19Z
[ "python", "datetime" ]
Convert a string with date and time to a date
301,528
<p>I've got this date time string:</p> <pre><code>post["date"] = "2007-07-18 10:03:19" </code></pre> <p>I'd like to extract just "2007-07-18" as a date. I've seen some reference to <code>strptime</code> but I'm not sure how to use it. How can I extract the date from this string?</p>
18
2008-11-19T10:45:01Z
301,580
<p>The other two answers are fine, but if you actually want the date for something else, you can use the <code>datetime</code> module:</p> <pre><code>from datetime import datetime d = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S') day_string = d.strftime('%Y-%m-%d') </code></pre> <p>It might be overkill for now, but it'll come in useful. You can see all of the format specifiers <a href="http://docs.python.org/library/time.html#time.strftime">here</a>.</p>
44
2008-11-19T11:05:41Z
[ "python", "datetime" ]
Convert a string with date and time to a date
301,528
<p>I've got this date time string:</p> <pre><code>post["date"] = "2007-07-18 10:03:19" </code></pre> <p>I'd like to extract just "2007-07-18" as a date. I've seen some reference to <code>strptime</code> but I'm not sure how to use it. How can I extract the date from this string?</p>
18
2008-11-19T10:45:01Z
301,591
<p>You can use the <code>mx.DateTime</code> module from <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/" rel="nofollow">eGenix</a></p> <pre><code>import mx date_object = mx.DateTime.Parser.DateTimeFromString('2007-07-18 10:03:19') print "%s-%s-%s" % (date_object.year, date_object.month, date_object.day) </code></pre> <p>will output: <code>2007-07-18</code></p>
1
2008-11-19T11:10:27Z
[ "python", "datetime" ]
Convert a string with date and time to a date
301,528
<p>I've got this date time string:</p> <pre><code>post["date"] = "2007-07-18 10:03:19" </code></pre> <p>I'd like to extract just "2007-07-18" as a date. I've seen some reference to <code>strptime</code> but I'm not sure how to use it. How can I extract the date from this string?</p>
18
2008-11-19T10:45:01Z
301,593
<p>You can use the <a href="http://pypi.python.org/pypi/parsedatetime/" rel="nofollow">parsedatetime</a> module.</p> <pre><code>&gt;&gt;&gt; from parsedatetime.parsedatetime import Calendar &gt;&gt;&gt; c = Calendar() &gt;&gt;&gt; c.parse("2007-07-18 10:03:19") ((2008, 11, 19, 10, 3, 19, 2, 324, 0), 2) </code></pre>
0
2008-11-19T11:11:54Z
[ "python", "datetime" ]
Convert a string with date and time to a date
301,528
<p>I've got this date time string:</p> <pre><code>post["date"] = "2007-07-18 10:03:19" </code></pre> <p>I'd like to extract just "2007-07-18" as a date. I've seen some reference to <code>strptime</code> but I'm not sure how to use it. How can I extract the date from this string?</p>
18
2008-11-19T10:45:01Z
16,184,809
<p>You can use <a href="https://pypi.python.org/pypi/python-dateutil" rel="nofollow">https://pypi.python.org/pypi/python-dateutil</a> which can support any datetime format e.g:</p> <pre><code>&gt;&gt;&gt; from dateutil.parser import parse &gt;&gt;&gt; d1="2007-07-18 10:03:19" &gt;&gt;&gt; date_obj = parse(d1) &gt;&gt;&gt; date_obj datetime.datetime(2007, 7, 18, 10, 3, 19) &gt;&gt;&gt; date_obj.strftime("%Y-%m-%d") '2007-07-18' &gt;&gt;&gt; d2 = "18-07-2007 10:03:19" &gt;&gt;&gt; d = parse(d2) &gt;&gt;&gt; d datetime.datetime(2007, 7, 18, 10, 3, 19) &gt;&gt;&gt; d.strftime("%Y-%m-%d") '2007-07-18' </code></pre>
2
2013-04-24T06:25:29Z
[ "python", "datetime" ]
Convert a string with date and time to a date
301,528
<p>I've got this date time string:</p> <pre><code>post["date"] = "2007-07-18 10:03:19" </code></pre> <p>I'd like to extract just "2007-07-18" as a date. I've seen some reference to <code>strptime</code> but I'm not sure how to use it. How can I extract the date from this string?</p>
18
2008-11-19T10:45:01Z
39,764,551
<pre><code>import dateutil.parser a = "2007-07-18 10:03:19" d = dateutil.parser.parse(b).date() </code></pre> <p>Your Output will be like this **</p> <blockquote> <p>datetime.date(2007, 07, 18)</p> </blockquote> <p>**</p>
0
2016-09-29T07:57:56Z
[ "python", "datetime" ]
How to update turbogears application production database
301,566
<p>I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. </p> <p>How do i do this? I am using sqlAlchemy.</p>
1
2008-11-19T11:00:34Z
301,706
<p>If you are just adding tables, and not modifying any of the tables which have the existing data in it, you can simply add the new sqlAlchemy table definitions to model.py, and run:</p> <pre><code>tg-admin sql create </code></pre> <p>This will not overwrite any of your existing tables.</p> <p>For schema migration, you might take a look at <a href="http://code.google.com/p/sqlalchemy-migrate/" rel="nofollow">http://code.google.com/p/sqlalchemy-migrate/</a> although I haven't used it yet myself.</p> <p>Always take a backup of the production database before migration activity.</p>
0
2008-11-19T12:10:19Z
[ "python", "database", "postgresql", "data-migration", "turbogears" ]
How to update turbogears application production database
301,566
<p>I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. </p> <p>How do i do this? I am using sqlAlchemy.</p>
1
2008-11-19T11:00:34Z
301,707
<p>The simplest approach is to simply write some sql update scripts and use those to update the database. Obviously that's a fairly low-level (as it were) approach.</p> <p>If you think you will be doing this a lot and want to stick in Python you might want to look at <a href="http://code.google.com/p/sqlalchemy-migrate/" rel="nofollow">sqlalchemy-migrate</a>. There was an article about it in the recent Python Magazine.</p>
1
2008-11-19T12:10:43Z
[ "python", "database", "postgresql", "data-migration", "turbogears" ]
How to update turbogears application production database
301,566
<p>I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. </p> <p>How do i do this? I am using sqlAlchemy.</p>
1
2008-11-19T11:00:34Z
301,708
<p>This always works and requires little thinking -- only patience.</p> <ol> <li><p>Make a backup.</p></li> <li><p>Actually make a backup. Everyone skips step 1 thinking that they have a backup, but they can never find it or work with it. Don't trust any backup that you can't recover from.</p></li> <li><p>Create a new database schema.</p></li> <li><p>Define your new structure from the ground up in the new schema. Ideally, you'll run a DDL script that builds the new schema. Don't have a script to build the schema? Create one and put it under version control.</p> <p>With SA, you can define your tables and it can build your schema for you. This is ideal, since you have your schema under version control in Python.</p></li> <li><p>Move data.</p> <p>a. For tables which did not change structure, move data from old schema to new schema using simple INSERT/SELECT statements.</p> <p>b. For tables which did change structure, develop INSERT/SELECT scripts to move the data from old to new. Often, this can be a single SQL statement per new table. In some cases, it has to be a Python loop with two open connections.</p> <p>c. For new tables, load the data.</p></li> <li><p>Stop using the old schema. Start using the new schema. Find every program that used the old schema and fix the configuration. </p> <p>Don't have a list of applications? Make one. Seriously -- it's important. </p> <p>Applications have hard-coded DB configurations? Fix that, too, while you're at it. Either create a common config file, or use some common environment variable or something to (a) assure consistency and (b) centralize the notion of "production".</p></li> </ol> <p>You can do this kind of procedure any time you do major surgery. It never touches the old database except to extract the data.</p>
1
2008-11-19T12:10:50Z
[ "python", "database", "postgresql", "data-migration", "turbogears" ]
How to update turbogears application production database
301,566
<p>I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database. </p> <p>How do i do this? I am using sqlAlchemy.</p>
1
2008-11-19T11:00:34Z
390,485
<p>I'd agree in general with <a href="http://stackoverflow.com/users/5868/john-montgomery">John</a>. One-pass SELECTing and INSERTing would not be practical for a large database, and setting up replication or multi-pass differential SELECT / INSERTs would probably be harder and more error-prone.</p> <p>Personally, I use SQLAlchemy as an ORM under <a href="http://turbogears.com/" rel="nofollow">TurboGears</a>. To do schema migrations I run:</p> <pre><code>tg-admin sql status </code></pre> <p>To see the difference between the live and development schemas, then manually write (and version control) DDL scripts to make the required changes.</p> <p>For those using SQLAlchemy standalone (i.e. not under TurboGears), the <code>sql status</code> functionality is pretty simple and can be found here in the TG source: <a href="http://svn.turbogears.org/branches/1.1/turbogears/command/sacommand.py" rel="nofollow">http://svn.turbogears.org/branches/1.1/turbogears/command/sacommand.py</a> (there's versions for older Python / SA releases in the 1.0 branch, too).</p>
1
2008-12-24T00:30:18Z
[ "python", "database", "postgresql", "data-migration", "turbogears" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
301,953
<p>Besides the fact that you may be missing a cookie, there might be some field(s) in the form that you are not POSTing to the webserver. The best way would be to capture the actual POST from a web browser. You can use <a href="https://addons.mozilla.org/en-US/firefox/addon/3829" rel="nofollow">LiveHTTPHeaders</a> or <a href="http://www.wireshark.org/" rel="nofollow">WireShark</a> to snoop the traffic and mimic the same behaviour in your script.</p>
0
2008-11-19T14:00:59Z
[ "python", "http", "urllib2" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
301,987
<p>Try <a href="http://twill.idyll.org/" rel="nofollow">twill</a> - a simple language that allows users to browse the Web from a command-line interface. With twill, you can navigate through Web sites that use forms, cookies, and most standard Web features. More to the point, <em>twill</em> is written in <code>Python</code> and has a <a href="http://twill.idyll.org/python-api.html" rel="nofollow">python API</a>, e.g:</p> <pre><code>from twill import get_browser b = get_browser() b.go("http://www.python.org/") b.showforms() </code></pre>
6
2008-11-19T14:15:32Z
[ "python", "http", "urllib2" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
301,998
<p>I'd give Mechanize (<a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">http://wwwsearch.sourceforge.net/mechanize/</a>) a shot. It may well handle your cookie/headers transparently.</p>
8
2008-11-19T14:19:19Z
[ "python", "http", "urllib2" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
302,035
<p><a href="http://funkload.nuxeo.org/" rel="nofollow">Funkload</a> is a great web app testing tool also. It wraps webunit to handle the browser emulation, then gives you both functional and load testing features on top.</p>
0
2008-11-19T14:32:49Z
[ "python", "http", "urllib2" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
302,099
<p>Focus on <code>urllib2</code> for this, it works quite well. Don't mess with <code>httplib</code>, it's not the top-level API.</p> <p>What you're noting is that <code>urllib2</code> doesn't follow the redirect.</p> <p>You need to fold in an instance of <code>HTTPRedirectHandler</code> that will catch and follow the redirects.</p> <p>Further, you may want to subclass the default <code>HTTPRedirectHandler</code> to capture information that you'll then check as part of your unit testing.</p> <pre><code>cookie_handler= urllib2.HTTPCookieProcessor( self.cookies ) redirect_handler= HTTPRedirectHandler() opener = urllib2.build_opener(redirect_handler,cookie_handler) </code></pre> <p>You can then use this <code>opener</code> object to POST and GET, handling redirects and cookies properly.</p> <p>You may want to add your own subclass of <code>HTTPHandler</code> to capture and log various error codes, also.</p>
31
2008-11-19T14:52:47Z
[ "python", "http", "urllib2" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
302,184
<p>I had to do this exact thing myself recently. I only needed classes from the standard library. Here's an excerpt from my code:</p> <pre><code>from urllib import urlencode from urllib2 import urlopen, Request # encode my POST parameters for the login page login_qs = urlencode( [("username",USERNAME), ("password",PASSWORD)] ) # extract my session id by loading a page from the site set_cookie = urlopen(URL_BASE).headers.getheader("Set-Cookie") sess_id = set_cookie[set_cookie.index("=")+1:set_cookie.index(";")] # construct headers dictionary using the session id headers = {"Cookie": "session_id="+sess_id} # perform login and make sure it worked if "Announcements:" not in urlopen(Request(URL_BASE+"login",headers=headers), login_qs).read(): print "Didn't log in properly" exit(1) # here's the function I used after this for loading pages def download(page=""): return urlopen(Request(URL_BASE+page, headers=headers)).read() # for example: print download(URL_BASE + "config") </code></pre>
11
2008-11-19T15:12:08Z
[ "python", "http", "urllib2" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
302,205
<p>@S.Lott, thank you. Your suggestion worked for me, with some modification. Here's how I did it.</p> <pre><code>data = urllib.urlencode(params) url = host+page request = urllib2.Request(url, data, headers) response = urllib2.urlopen(request) cookies = CookieJar() cookies.extract_cookies(response,request) cookie_handler= urllib2.HTTPCookieProcessor( cookies ) redirect_handler= HTTPRedirectHandler() opener = urllib2.build_opener(redirect_handler,cookie_handler) response = opener.open(request) </code></pre>
13
2008-11-19T15:17:31Z
[ "python", "http", "urllib2" ]
Python: urllib/urllib2/httplib confusion
301,924
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
52
2008-11-19T13:44:20Z
4,836,113
<p>Here's my take on this issue.</p> <pre><code>#!/usr/bin/env python import urllib import urllib2 class HttpBot: """an HttpBot represents one browser session, with cookies.""" def __init__(self): cookie_handler= urllib2.HTTPCookieProcessor() redirect_handler= urllib2.HTTPRedirectHandler() self._opener = urllib2.build_opener(redirect_handler, cookie_handler) def GET(self, url): return self._opener.open(url).read() def POST(self, url, parameters): return self._opener.open(url, urllib.urlencode(parameters)).read() if __name__ == "__main__": bot = HttpBot() ignored_html = bot.POST('https://example.com/authenticator', {'passwd':'foo'}) print bot.GET('https://example.com/interesting/content') ignored_html = bot.POST('https://example.com/deauthenticator',{}) </code></pre>
15
2011-01-29T09:33:42Z
[ "python", "http", "urllib2" ]
Global hotkey for Python application in Gnome
302,163
<p>I would like to assign a global hotkey to my Python application, running in Gnome. How do I do that? All I can find are two year old posts saying, well, pretty much nothing :-)</p>
6
2008-11-19T15:08:12Z
302,168
<p>Check out the Deskbar source code - they do this; afaik, they call out a C library that interacts with X11 to do the job</p>
2
2008-11-19T15:09:54Z
[ "python", "gnome" ]
Global hotkey for Python application in Gnome
302,163
<p>I would like to assign a global hotkey to my Python application, running in Gnome. How do I do that? All I can find are two year old posts saying, well, pretty much nothing :-)</p>
6
2008-11-19T15:08:12Z
1,359,417
<p>There is python-keybinder which is that same code, but packaged standalone. Also available in debian and ubuntu repositories now.</p> <p><a href="https://github.com/engla/keybinder" rel="nofollow">https://github.com/engla/keybinder</a></p>
8
2009-08-31T21:03:58Z
[ "python", "gnome" ]
Calculate exact result of complex throw of two D30
302,379
<p>Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, <em>now</em>. Too late.</p> <p>Okay. Take a deep breath. Here are the rules. Take <em>two</em> thirty sided dice (yes, <a href="http://paizo.com/store/byCompany/k/koplow/dice/d30" rel="nofollow">they do exist</a>) and roll them simultaneously.</p> <ul> <li>Add the two numbers</li> <li>If both dice show &lt;= 5 or >= 26, throw again and <em>add</em> the result to what you have</li> <li>If one is &lt;= 5 and the other >= 26, throw again and <em>subtract</em> the result from what you have</li> <li>Repeat until either is > 5 and &lt; 26!</li> </ul> <p>If you write some code (see below), roll those dice a few million times and you count how often you receive each number as the final result, you get a curve that is pretty flat left of 1, around 45° degrees between 1 and 60 and flat above 60. The chance to roll 30.5 or better is greater than 50%, to roll better than 18 is 80% and to roll better than 0 is 97%.</p> <p>Now the question: Is it possible to write a program to <em>calculate</em> the <em>exact</em> value f(x), i.e. the probability to roll a certain value?</p> <p>Background: For our role playing game "Jungle of Stars" we looked for a way to keep random events in check. The rules above guarantee a much more stable outcome for something you try :)</p> <p>For the geeks around, the code in Python:</p> <pre><code>import random import sys def OW60 (): """Do an open throw with a "60" sided dice""" val = 0 sign = 1 while 1: r1 = random.randint (1, 30) r2 = random.randint (1, 30) #print r1,r2 val = val + sign * (r1 + r2) islow = 0 ishigh = 0 if r1 &lt;= 5: islow += 1 elif r1 &gt;= 26: ishigh += 1 if r2 &lt;= 5: islow += 1 elif r2 &gt;= 26: ishigh += 1 if islow == 2 or ishigh == 2: sign = 1 elif islow == 1 and ishigh == 1: sign = -1 else: break #print sign #print val return val result = [0] * 2000 N = 100000 for i in range(N): r = OW60() x = r+1000 if x &lt; 0: print "Too low:",r if i % 1000 == 0: sys.stderr.write('%d\n' % i) result[x] += 1 i = 0 while result[i] == 0: i += 1 j = len(result) - 1 while result[j] == 0: j -= 1 pSum = 0 # Lower Probability: The probability to throw this or less # Higher Probability: The probability to throw this or higher print "Result;Absolut Count;Probability;Lower Probability;Rel. Lower Probability;Higher Probability;Rel. Higher Probability;" while i &lt;= j: pSum += result[i] print '%d;%d;%.10f;%d;%.10f;%d;%.10f' % (i-1000, result[i], (float(result[i])/N), pSum, (float(pSum)/N), N-pSum, (float(N-pSum)/N)) i += 1 </code></pre>
3
2008-11-19T15:57:35Z
302,455
<p>Well, let's see. The <em>second</em> throw (which will sometimes be added or subtracted to the first roll) has a nice easily predictable bell curve around 31. The first roll, of course, is the problem.</p> <p>For the first roll, we have 900 possible combinations. </p> <ul> <li>50 combinations result in adding the second roll.</li> <li>25 combinations result in subtracting the second roll.</li> <li>Leaving 825 combinations which match the bell curve of the second roll.</li> </ul> <p>The subtracting set (pre-subtraction) will form a bell curve in the range (27..35). The lower half of the adding set will form a bell curve in the range (2..10), while the upper half will form a bell curve in the range (52...60)</p> <p>My probablity is a bit rusty, so I can't figure the exact values for you, but it should be clear that these lead to predictable values.</p>
0
2008-11-19T16:20:37Z
[ "python", "math", "statistics", "puzzle" ]
Calculate exact result of complex throw of two D30
302,379
<p>Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, <em>now</em>. Too late.</p> <p>Okay. Take a deep breath. Here are the rules. Take <em>two</em> thirty sided dice (yes, <a href="http://paizo.com/store/byCompany/k/koplow/dice/d30" rel="nofollow">they do exist</a>) and roll them simultaneously.</p> <ul> <li>Add the two numbers</li> <li>If both dice show &lt;= 5 or >= 26, throw again and <em>add</em> the result to what you have</li> <li>If one is &lt;= 5 and the other >= 26, throw again and <em>subtract</em> the result from what you have</li> <li>Repeat until either is > 5 and &lt; 26!</li> </ul> <p>If you write some code (see below), roll those dice a few million times and you count how often you receive each number as the final result, you get a curve that is pretty flat left of 1, around 45° degrees between 1 and 60 and flat above 60. The chance to roll 30.5 or better is greater than 50%, to roll better than 18 is 80% and to roll better than 0 is 97%.</p> <p>Now the question: Is it possible to write a program to <em>calculate</em> the <em>exact</em> value f(x), i.e. the probability to roll a certain value?</p> <p>Background: For our role playing game "Jungle of Stars" we looked for a way to keep random events in check. The rules above guarantee a much more stable outcome for something you try :)</p> <p>For the geeks around, the code in Python:</p> <pre><code>import random import sys def OW60 (): """Do an open throw with a "60" sided dice""" val = 0 sign = 1 while 1: r1 = random.randint (1, 30) r2 = random.randint (1, 30) #print r1,r2 val = val + sign * (r1 + r2) islow = 0 ishigh = 0 if r1 &lt;= 5: islow += 1 elif r1 &gt;= 26: ishigh += 1 if r2 &lt;= 5: islow += 1 elif r2 &gt;= 26: ishigh += 1 if islow == 2 or ishigh == 2: sign = 1 elif islow == 1 and ishigh == 1: sign = -1 else: break #print sign #print val return val result = [0] * 2000 N = 100000 for i in range(N): r = OW60() x = r+1000 if x &lt; 0: print "Too low:",r if i % 1000 == 0: sys.stderr.write('%d\n' % i) result[x] += 1 i = 0 while result[i] == 0: i += 1 j = len(result) - 1 while result[j] == 0: j -= 1 pSum = 0 # Lower Probability: The probability to throw this or less # Higher Probability: The probability to throw this or higher print "Result;Absolut Count;Probability;Lower Probability;Rel. Lower Probability;Higher Probability;Rel. Higher Probability;" while i &lt;= j: pSum += result[i] print '%d;%d;%.10f;%d;%.10f;%d;%.10f' % (i-1000, result[i], (float(result[i])/N), pSum, (float(pSum)/N), N-pSum, (float(N-pSum)/N)) i += 1 </code></pre>
3
2008-11-19T15:57:35Z
303,453
<p>Compound unbounded probability is... non-trivial. I was going to tackle the problem the same way as James Curran, but then I saw from your source code that there could be a third set of rolls, and a fourth, and so on. The problem is solvable, but far beyond most die rolling simulators.</p> <p>Is there any particular reason that you need a random range from -Inf to +Inf with such a complex curve around 1-60? Why is the bell curve of 2D30 not acceptable? If you explain your requirements, it is likely someone could provide a simpler and more bounded algorithm.</p>
1
2008-11-19T21:35:51Z
[ "python", "math", "statistics", "puzzle" ]
Calculate exact result of complex throw of two D30
302,379
<p>Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, <em>now</em>. Too late.</p> <p>Okay. Take a deep breath. Here are the rules. Take <em>two</em> thirty sided dice (yes, <a href="http://paizo.com/store/byCompany/k/koplow/dice/d30" rel="nofollow">they do exist</a>) and roll them simultaneously.</p> <ul> <li>Add the two numbers</li> <li>If both dice show &lt;= 5 or >= 26, throw again and <em>add</em> the result to what you have</li> <li>If one is &lt;= 5 and the other >= 26, throw again and <em>subtract</em> the result from what you have</li> <li>Repeat until either is > 5 and &lt; 26!</li> </ul> <p>If you write some code (see below), roll those dice a few million times and you count how often you receive each number as the final result, you get a curve that is pretty flat left of 1, around 45° degrees between 1 and 60 and flat above 60. The chance to roll 30.5 or better is greater than 50%, to roll better than 18 is 80% and to roll better than 0 is 97%.</p> <p>Now the question: Is it possible to write a program to <em>calculate</em> the <em>exact</em> value f(x), i.e. the probability to roll a certain value?</p> <p>Background: For our role playing game "Jungle of Stars" we looked for a way to keep random events in check. The rules above guarantee a much more stable outcome for something you try :)</p> <p>For the geeks around, the code in Python:</p> <pre><code>import random import sys def OW60 (): """Do an open throw with a "60" sided dice""" val = 0 sign = 1 while 1: r1 = random.randint (1, 30) r2 = random.randint (1, 30) #print r1,r2 val = val + sign * (r1 + r2) islow = 0 ishigh = 0 if r1 &lt;= 5: islow += 1 elif r1 &gt;= 26: ishigh += 1 if r2 &lt;= 5: islow += 1 elif r2 &gt;= 26: ishigh += 1 if islow == 2 or ishigh == 2: sign = 1 elif islow == 1 and ishigh == 1: sign = -1 else: break #print sign #print val return val result = [0] * 2000 N = 100000 for i in range(N): r = OW60() x = r+1000 if x &lt; 0: print "Too low:",r if i % 1000 == 0: sys.stderr.write('%d\n' % i) result[x] += 1 i = 0 while result[i] == 0: i += 1 j = len(result) - 1 while result[j] == 0: j -= 1 pSum = 0 # Lower Probability: The probability to throw this or less # Higher Probability: The probability to throw this or higher print "Result;Absolut Count;Probability;Lower Probability;Rel. Lower Probability;Higher Probability;Rel. Higher Probability;" while i &lt;= j: pSum += result[i] print '%d;%d;%.10f;%d;%.10f;%d;%.10f' % (i-1000, result[i], (float(result[i])/N), pSum, (float(pSum)/N), N-pSum, (float(N-pSum)/N)) i += 1 </code></pre>
3
2008-11-19T15:57:35Z
305,649
<p>I had to first rewrite your code before I could understand it:</p> <pre><code>def OW60(sign=1): r1 = random.randint (1, 30) r2 = random.randint (1, 30) val = sign * (r1 + r2) islow = (r1&lt;=5) + (r2&lt;=5) ishigh = (r1&gt;=26) + (r2&gt;=26) if islow == 2 or ishigh == 2: return val + OW60(1) elif islow == 1 and ishigh == 1: return val + OW60(-1) else: return val </code></pre> <p>Maybe you might find this less readable; I don't know. (Do check if it is equivalent to what you had in mind.) Also, regarding the way you use "result" in your code -- do you know of Python's <a href="http://www.diveintopython.org/getting_to_know_python/dictionaries.html" rel="nofollow">dict</a>s?</p> <p>Anyway, matters of programming style aside: Suppose F(x) is the <a href="http://en.wikipedia.org/wiki/Cumulative_distribution_function" rel="nofollow">CDF</a> of OW60(1), i.e. </p> <pre><code>F(x) = the probability that OW60(1) returns a value ≤ x. </code></pre> <p>Similarly let </p> <pre><code>G(x) = the probability that OW60(-1) returns a value ≤ x. </code></pre> <p>Then you can calculate F(x) from the definition, by summing over all (30&times;30) possible values of the result of the first throw. For instance, if the first throw is (2,3) then you'll roll again, so this term contributes (1/30)(1/30)(5+F(x-5)) to the expression for F(x). So you'll get some obscenely long expression like</p> <pre><code>F(x) = (1/900)(2+F(x-2) + 3+F(x-3) + ... + 59+F(x-59) + 60+F(x-60)) </code></pre> <p>which is a sum over 900 terms, one for each pair (a,b) in [30]&times;[30]. The pairs (a,b) with both ≤ 5 or both ≥26 have a term a+b+F(x-a-b), the pairs with one ≤5 and one ≥26 have a term a+b+G(x-a-b), and the rest have a term like (a+b), because you don't throw again.</p> <p>Similarly you have </p> <pre><code>G(x) = (1/900)(-2+F(x-2) + (-3)+F(x-3) + ... + (-59)+F(x-59) + (-60)+F(x-60)) </code></pre> <p>Of course, you can collect coefficients; the only F terms that occur are from F(x-60) to F(x-52) and from F(x-10) to F(x-2) (for a,b≥26 or both≤5), and the only G terms that occur are from G(x-35) to G(x-27) (for one of a,b≥26 and the other ≤5), so there are fewer terms than 30 terms. In any case, defining the vector V(x) as </p> <pre><code>V(x) = [F(x-60) G(x-60) ... F(x-2) G(x-2) F(x-1) G(x-1) F(x) G(x)] </code></pre> <p>(say), you have (from those expressions for F and G) a relation of the form </p> <pre><code>V(x) = A*V(x-1) + B </code></pre> <p>for an appropriate matrix A and an appropriate vector B (which you can calculate), so starting from initial values of the form V(x) = [0 0] for x sufficiently small, you can find F(x) and G(x) for x in the range you want to arbitrarily close precision. (And your f(x), the probability of throwing x, is just F(x)-F(x-1), so that comes out as well.)</p> <p>There might be a better way. All said and done, though, why are you doing this? Whatever kind of distribution you want, there are nice and simple probability distributions, with the appropriate parameters, that have good properties (e.g. small variance, one-sided errors, whatever). There is no reason to make up your own ad-hoc procedure to generate random numbers.</p>
6
2008-11-20T15:29:30Z
[ "python", "math", "statistics", "puzzle" ]
Calculate exact result of complex throw of two D30
302,379
<p>Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, <em>now</em>. Too late.</p> <p>Okay. Take a deep breath. Here are the rules. Take <em>two</em> thirty sided dice (yes, <a href="http://paizo.com/store/byCompany/k/koplow/dice/d30" rel="nofollow">they do exist</a>) and roll them simultaneously.</p> <ul> <li>Add the two numbers</li> <li>If both dice show &lt;= 5 or >= 26, throw again and <em>add</em> the result to what you have</li> <li>If one is &lt;= 5 and the other >= 26, throw again and <em>subtract</em> the result from what you have</li> <li>Repeat until either is > 5 and &lt; 26!</li> </ul> <p>If you write some code (see below), roll those dice a few million times and you count how often you receive each number as the final result, you get a curve that is pretty flat left of 1, around 45° degrees between 1 and 60 and flat above 60. The chance to roll 30.5 or better is greater than 50%, to roll better than 18 is 80% and to roll better than 0 is 97%.</p> <p>Now the question: Is it possible to write a program to <em>calculate</em> the <em>exact</em> value f(x), i.e. the probability to roll a certain value?</p> <p>Background: For our role playing game "Jungle of Stars" we looked for a way to keep random events in check. The rules above guarantee a much more stable outcome for something you try :)</p> <p>For the geeks around, the code in Python:</p> <pre><code>import random import sys def OW60 (): """Do an open throw with a "60" sided dice""" val = 0 sign = 1 while 1: r1 = random.randint (1, 30) r2 = random.randint (1, 30) #print r1,r2 val = val + sign * (r1 + r2) islow = 0 ishigh = 0 if r1 &lt;= 5: islow += 1 elif r1 &gt;= 26: ishigh += 1 if r2 &lt;= 5: islow += 1 elif r2 &gt;= 26: ishigh += 1 if islow == 2 or ishigh == 2: sign = 1 elif islow == 1 and ishigh == 1: sign = -1 else: break #print sign #print val return val result = [0] * 2000 N = 100000 for i in range(N): r = OW60() x = r+1000 if x &lt; 0: print "Too low:",r if i % 1000 == 0: sys.stderr.write('%d\n' % i) result[x] += 1 i = 0 while result[i] == 0: i += 1 j = len(result) - 1 while result[j] == 0: j -= 1 pSum = 0 # Lower Probability: The probability to throw this or less # Higher Probability: The probability to throw this or higher print "Result;Absolut Count;Probability;Lower Probability;Rel. Lower Probability;Higher Probability;Rel. Higher Probability;" while i &lt;= j: pSum += result[i] print '%d;%d;%.10f;%d;%.10f;%d;%.10f' % (i-1000, result[i], (float(result[i])/N), pSum, (float(pSum)/N), N-pSum, (float(N-pSum)/N)) i += 1 </code></pre>
3
2008-11-19T15:57:35Z
3,435,254
<p>I've done some basic statistics on a sample of 20 million throws. Here are the results:</p> <pre><code>Median: 17 (+18, -?) # This result is meaningless Arithmetic Mean: 31.0 (±0.1) Standard Deviation: 21 (+1, -2) Root Mean Square: 35.4 (±0.7) Mode: 36 (seemingly accurate) </code></pre> <p>The errors were determined experimentally. The arithmetic mean and the mode are really accurate, and changing the parameters even quite aggressively doesn't seem to influence them much. I suppose the behaviour of the median has already been explained.</p> <p>Note: don't take these number for a proper mathematical description of the function. Use them to quickly get a picture of what the distribution looks like. For anything else, they aren't accurate enough (even though they might be precise.</p> <p>Perhaps this is helpful to someone.</p> <p>Edit 2:</p> <p><img src="http://chart.apis.google.com/chart?cht=lc&amp;chs=400x200&amp;chd=e:UshVbmkydgXwlLifjQljW.cvgkackylLRPd5ZriGhVbmgkdgfCi3eRfCgk4VSyYhhufbbmYhcvhVg9ZrljkZa0ZrljhVY6gMfzkZkyXYacfClLfbackBifd5kZi3fCiGcvgMi3acnel8g9gMmtZrdgbmbNd5l8fCcvbNkBmUdIbNgMZrb-kymUbmdIhuxDiGbNeRYJwqgkjobmeqiGaDY6cvpxjobNlLhVgMonkZcXg92aVFl8iGljeRjoljhVdIiGn2bNfzd5-1kZhVWOhVnenFgMbmaceRfzgMifeqbNfbfCjon2dIjo2yi3gMdIjQZSjQa0y9hukBi3jog9ZrfbeRmUkycvgMdIZrnFbNjQhVjo04bmbNZracYhfbi3aceqhuYhZSlLcXd5n21pljkBa0kZmtifaceqifUUiG6oeRgMkycXeqQ3fCmtaDlLjogMgMjQkygkkyfbcveqiGZSkZeRfbbNaceReRd5l8gkpYfCiGlLkyfzgMfCmUififdgifb-mUac2ymtifd5kBfzjQnFcvfbfCYhjQac2yacifeqjocvb-bmjQifdghVd5g9ifkZeqd5hVdgjQnFn2fCZScXcXifd5-dhVnFbmbNacgMgk8KbmmUWncvlLd5bNcXRojonF.mkZbNmUdgfCnFkBljoPhVjQoPdId5fzifachufCgkhVpAcXgkmUd5nFiGdgi3gMV2kyl8n2jofCfzoPdIeqPVa0kZhVoncvhVaDlLbmXwaDiGYhkyZrVFljSZhuaDi3acnecvb-gknFbmjQeRkBonjQeqfbb-mUjob-jQdgmtzueqmUifoPFwcX2aeRjoiGfCXYa0b-iGpAaDiGNCoPi3kZl8ZrQ3jQiGW.ZrbmY6dIiGeRjQkyY6bmfzoPpxgMd5l8fzhufzlLg9lLa0i3YhkBiGXweqjQcXjogMa0WOg9oPl8eRhujQfbZSjocvifhVRPmtd5hVgMn2jQhuifd5gkYJnen2kZcXY6fCdgcvmtjobNfChufCnekZdIgkg9ackydggMeq7AYhiGfbjoeqeRachuT7cvVFbmeqeRkyUshusEd5joiGRPgMlLeqdgfChujoifg9g9YJiGdgkBmtdIhuYhO8RoiffzfCiGfbjQi3Yhkylja0gMjobmfCdIdghVljdIjQwqhVoPl8jQljg9kZdIdgfCd5yMnFeRZraDYhgkmtWOjQn2l8fznecva0mthuAAkyg9ZrZSYJonkyNafCeqfCx0fzkymtkycXgkl8b-jQcXhVW.eRdgkZcvfbnegkjoeqkZiGkykBhVfbkBcXfCSymUg9neeRnehVeqd5g9hukBififn2kZl8n2d5l8huYhfzifd5bNXYW.oni3b-jQifacn2eqjQifmUdIfCNalLeqvhkZpAjQkBXweRi3T7kBZr5GifjoneYJifWnackZbmeqeqiGaDeRyli30fbmeqcvn2ifackyfCifkya0kBfCeqcXY6oPhujogMiGlLg9YhneYhg9iGiGiGgkgkoPjQn2eqlLa0VdoPbNXYfChufCjobNeRhui3g9a0gkbmifSAifaceqhueRifZSb-mUmtfCZrb-lLYJbmjQfCdgjooncXhufC-1fbb-eRdgfbdgoPdgeRdIl8lLgMdgfbljkyljbmlLhuifeRfzg904L4fzfzgMbNkyYJZrcvkygMiGeRkBn2hVd5cXd5gMfbZrbNfzn2eRgMlLZrlLn2g9ljg9hVifnFd5nFonhunecXdgneSARPifl8iGfbYhkZkBfzneacnFyMYhjoa0fCjoaDgkd5iGkBeqmtnehub-eRnekZ2BaDkBlLd5eRgMkBljcvZrlj1Qy9ZSkZhubmhuifd5bNkykBcvpAa0onifnFdgfCjonFifbNMpjoaDhVkZfbQGmUfzjobmljfzeqgMiGmtjofCi3joRoeqdIpAb-a0d5dgi3cXfzeRljb-cXjofbmUmt&amp;chxt=y,x&amp;chxr=0,-54,112|1,0,991" alt="graph" /></p> <p>Based on just 991 values. I could've crammed more values into it, but they would've distorted the result. This sample happens to be fairly typical.</p> <p>Edit 1:</p> <p>here are the above values for just one sixty-sided die, for comparison:</p> <pre><code>Median: 30.5 Arithmetic Mean: 30.5 Standard Deviation: 7.68114574787 Root Mean Square: 35.0737318611 </code></pre> <p>Note that these values are calculated, not experimental.</p>
2
2010-08-08T17:12:44Z
[ "python", "math", "statistics", "puzzle" ]
Use only some parts of Django?
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
29
2008-11-19T17:14:42Z
302,686
<p>There are of course other projects out there that specifically implement single parts of django. <a href="http://turbogears.org/" rel="nofollow">TurboGears</a> for example is a collection of several projects that can work by themselves and together form a complete web development framework.</p> <p>For the db abstraction <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> comes to mind.</p> <p>Regarding the caching part: I'm not aware of any standalone project that implements a generic caching facility.</p> <p>On the other hand, it should be fairly easy to implement your own caching, for example by using <a href="http://docs.python.org/library/pickle.html#module-cPickle" rel="nofollow">pickles</a>. Have a look at <a href="http://code.activestate.com/recipes/325205/" rel="nofollow">this recipe for a decorator</a> for ideas and google for "memoize".</p> <p>Also keep in mind that your database has its own caching mechanism, so maybe you don't even need to concern yourself with the details.</p>
2
2008-11-19T17:23:08Z
[ "python", "django" ]
Use only some parts of Django?
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
29
2008-11-19T17:14:42Z
302,691
<p>I tend to prefer a mix-and-match approach to using Python for web programming. :-)</p> <p>I don't have a lot of experience with Django, but I'd recommend giving <a href="http://www.sqlalchemy.org/" rel="nofollow">sqlalchemy</a> a look for the database stuff. It works well with others and gives you several potential layers of abstraction (so you can go with something basic or tweak the hell out of it if you want). Plus, you'll already be somewhat familiar with it if you've ever used hibernate/nhibernate.</p> <p>My favorite part is that it has a lot of options for databases to connect to (most notably SQL Server, which django doesn't have built in last time I checked).</p> <p>With that said, I'm told that with Django, it's pretty easy to decouple functionality (but never done so myself).</p>
2
2008-11-19T17:24:07Z
[ "python", "django" ]
Use only some parts of Django?
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
29
2008-11-19T17:14:42Z
302,847
<p>I myself use Django for its object/db mapping without using its urlconfigs. Simply create a file called <code>djangosettings.py</code> and insert the necessary configuration, for example:</p> <pre><code>DATABASE_ENGINE = 'oracle' DATABASE_HOST = 'localhost' DATABASE_NAME = 'ORCL' DATABASE_USER = 'scott' DATABASE_PASSWORD = 'tiger' </code></pre> <p>Then in your regular Python code, do</p> <pre><code>import os os.environ["DJANGO_SETTINGS_MODULE"] = "djangosettings" </code></pre> <p>before you import any Django modules. This will let you use Django's object/db mappings without actually having a Django project, so you can use it for standalone scripts or other web applications or whatever you want.</p> <p>As for caching, if you don't want to use Django then you should probably decide what you are using and go from there. I recommend using CherryPy, which doesn't use Django-style regular expression URL mapping, but instead automatically maps URLs to functions based on the function names. There's an example right at the top of the CherryPy home page: <a href="http://cherrypy.org/">http://cherrypy.org/</a></p> <p>CherryPy has its own caching system, so you can accomplish exactly the same thing as what Django does but without needing to use Django's urlconfig system.</p>
36
2008-11-19T18:17:41Z
[ "python", "django" ]
Use only some parts of Django?
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
29
2008-11-19T17:14:42Z
304,352
<p>Django, being a web framework, is extremely efficient at creating websites. However, it's also equally well-suited to tackling problems off the web. This is the <em>loose coupling</em> that the project prides itself on. Nothing stops you from installing a complete version of Django, and just using what you need. As a rule, very few components of Django make broad assumptions about their usage.</p> <p>Specifically:</p> <ul> <li>Django models don't know anything about HTML or HTTP.</li> <li>Templates don't know anything about HTML or HTTP.</li> <li>The cache system can be used to <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">store <em>anything that can be pickled</em></a>.</li> </ul> <p>One of the main things you'll face when trying to use Django without a web server is setting up the environment properly. The ORM and cache system still need to be configured in settings.py. There are docs on <a href="http://docs.djangoproject.com/en/dev/topics/settings/#using-settings-without-setting-django-settings-module">using django without a settings module</a> that you may find useful.</p>
11
2008-11-20T04:46:55Z
[ "python", "django" ]
Use only some parts of Django?
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
29
2008-11-19T17:14:42Z
10,789,890
<p>I've created a template Django project that allows you to do just that. </p> <p><a href="https://github.com/dancaron/Django-ORM">https://github.com/dancaron/Django-ORM</a></p> <p>Just follow the instructions and you can write standalone python files that utilize Django's database functionality, without having to use urlconf, views, etc. </p>
5
2012-05-28T20:04:18Z
[ "python", "django" ]
Use only some parts of Django?
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
29
2008-11-19T17:14:42Z
14,431,427
<p>I've shared an example of solution, which prevents Python Path manipulation inside code:</p> <p><a href="https://github.com/askalyuk/django-orm-standalone" rel="nofollow">https://github.com/askalyuk/django-orm-standalone</a></p> <p>It contains a standalone data access package, a separated simple Django site and a unit test.</p>
0
2013-01-21T01:42:27Z
[ "python", "django" ]
Use only some parts of Django?
302,651
<p>I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out.</p> <p>Specifically, I <i>want to use</i>:</p> <ul> <li>The models and database abstraction</li> <li>The <a href="http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api">caching API</a>, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate.</li> </ul> <p>I would <i>not use</i>:</p> <ul> <li>Templating</li> <li>urlconfigs</li> </ul> <p>Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual.</p> <p>Can this work?</p> <p>My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.</p>
29
2008-11-19T17:14:42Z
32,477,964
<p>I found <a href="http://stackoverflow.com/a/948593/1145750">KeyboardInterrupt's answer</a> but it was answered in 2009 and I failed to run it in Django 1.8.For recent <code>Django 1.8</code>, You can have a look at this, in which some parts come from KeyboardInterrupt's answer.</p> <p>The folder structure is:</p> <pre><code>. ├── myApp │   ├── __init__.py │   └── models.py └── my_manage.py </code></pre> <p>myApp is a module, contains an empty <code>__init__.py</code> and <code>models.py</code>.</p> <p>There is an example model class in <code>models.py</code>: from django.db import models</p> <pre><code>class MyModel(models.Model): field = models.CharField(max_length=255) </code></pre> <p>my_manage.py contains django database, installed_app settings and acts as django offical manage.py, so you can:</p> <pre><code>python my_manage.py sql myApp python my_manage.py migrate ...... </code></pre> <p>The codes in <code>my_manage.py</code> are: from django.conf import settings</p> <pre><code>db_conf = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'your_database_name', 'USER': 'your_user_name', 'PASSWORD': 'your_password', 'HOST': 'your_mysql_server_host', 'PORT': 'your_mysql_server_port', } } settings.configure( DATABASES = db_conf, INSTALLED_APPS = ( "myApp", ) ) # Calling django.setup() is required for “standalone” Django u usage # https://docs.djangoproject.com/en/1.8/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage import django django.setup() if __name__ == '__main__': import sys from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) </code></pre>
1
2015-09-09T11:09:36Z
[ "python", "django" ]
Running a Django site under mod_wsgi
302,679
<p>I am trying to run my Django sites with mod_wsgi instead of mod_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out.</p> <p>Apache conf:</p> <pre><code>&lt;VirtualHost 74.54.144.34&gt; DocumentRoot /wwwclients/thymeandagain ServerName thymeandagain4corners.com ServerAlias www.thymeandagain4corners.com LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /var/log/httpd/thymeandagain_access_log combined ErrorLog /var/log/httpd/thymeandagain_error_log LogLevel error WSGIScriptAlias / /wwwclients/thymeandagain/wsgi_handler.py WSGIDaemonProcess thymeandagain user=admin group=admin processes=1 threads=16 WSGIProcessGroup thymeandagain &lt;/VirtualHost&gt; </code></pre> <p>wsgi_handler.py:</p> <pre><code>import sys import os sys.path.append("/wwwclients") os.environ['DJANGO_SETTINGS_MODULE'] = 'thymeandagain.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre> <p>The daemon mod_wsgi is supposed to spawn off is not there, so requests just time out and I get a bunch of "Unable to connect to WSGI daemon process" errors in the logs. Is there something about the WSGIDaemonProcess directive that is preventing creation of the daemon? Thanks in advance for any help...</p> <p>EDIT: I get this in the error log:</p> <pre><code>[[email protected]] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [[email protected]] mcm_get_line():1592 [[email protected]] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [[email protected]] mcm_get_line():1592 [Thu Nov 20 21:18:17 2008] [notice] caught SIGTERM, shutting down [Thu Nov 20 21:18:18 2008] [notice] Digest: generating secret for digest authentication ... [Thu Nov 20 21:18:18 2008] [notice] Digest: done [Thu Nov 20 21:18:18 2008] [notice] mod_python: Creating 4 session mutexes based on 8 max processes and 64 max threads. [Thu Nov 20 21:18:18 2008] [notice] Apache/2.2.3 (Red Hat) mod_python/3.2.8 Python/2.4.3 mod_wsgi/2.1-BRANCH configured -- resuming normal operations </code></pre>
9
2008-11-19T17:21:02Z
302,858
<p><a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango" rel="nofollow">Here</a> is very detailed description on how to integrate django with mod_wsgi.</p>
1
2008-11-19T18:21:34Z
[ "python", "django", "apache", "mod-wsgi" ]
Running a Django site under mod_wsgi
302,679
<p>I am trying to run my Django sites with mod_wsgi instead of mod_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out.</p> <p>Apache conf:</p> <pre><code>&lt;VirtualHost 74.54.144.34&gt; DocumentRoot /wwwclients/thymeandagain ServerName thymeandagain4corners.com ServerAlias www.thymeandagain4corners.com LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /var/log/httpd/thymeandagain_access_log combined ErrorLog /var/log/httpd/thymeandagain_error_log LogLevel error WSGIScriptAlias / /wwwclients/thymeandagain/wsgi_handler.py WSGIDaemonProcess thymeandagain user=admin group=admin processes=1 threads=16 WSGIProcessGroup thymeandagain &lt;/VirtualHost&gt; </code></pre> <p>wsgi_handler.py:</p> <pre><code>import sys import os sys.path.append("/wwwclients") os.environ['DJANGO_SETTINGS_MODULE'] = 'thymeandagain.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre> <p>The daemon mod_wsgi is supposed to spawn off is not there, so requests just time out and I get a bunch of "Unable to connect to WSGI daemon process" errors in the logs. Is there something about the WSGIDaemonProcess directive that is preventing creation of the daemon? Thanks in advance for any help...</p> <p>EDIT: I get this in the error log:</p> <pre><code>[[email protected]] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [[email protected]] mcm_get_line():1592 [[email protected]] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [[email protected]] mcm_get_line():1592 [Thu Nov 20 21:18:17 2008] [notice] caught SIGTERM, shutting down [Thu Nov 20 21:18:18 2008] [notice] Digest: generating secret for digest authentication ... [Thu Nov 20 21:18:18 2008] [notice] Digest: done [Thu Nov 20 21:18:18 2008] [notice] mod_python: Creating 4 session mutexes based on 8 max processes and 64 max threads. [Thu Nov 20 21:18:18 2008] [notice] Apache/2.2.3 (Red Hat) mod_python/3.2.8 Python/2.4.3 mod_wsgi/2.1-BRANCH configured -- resuming normal operations </code></pre>
9
2008-11-19T17:21:02Z
339,471
<p>The problem is that mod_python doesn't go well together with mod_wsgi. I got into similar issue few weeks ago and everything started working for me shortly after I commented out mod_python inclusion.</p> <p>Try to search <a href="http://modwsgi.org" rel="nofollow">modwsgi.org</a> wiki for "mod_python", I believe there was someone talking about this somewhere in comments</p>
4
2008-12-04T02:42:14Z
[ "python", "django", "apache", "mod-wsgi" ]
Running a Django site under mod_wsgi
302,679
<p>I am trying to run my Django sites with mod_wsgi instead of mod_python (RHEL 5). I tried this with all my sites, but get the same problem. I configured it the standard way everyone recommends, but requests to the site simply time out.</p> <p>Apache conf:</p> <pre><code>&lt;VirtualHost 74.54.144.34&gt; DocumentRoot /wwwclients/thymeandagain ServerName thymeandagain4corners.com ServerAlias www.thymeandagain4corners.com LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog /var/log/httpd/thymeandagain_access_log combined ErrorLog /var/log/httpd/thymeandagain_error_log LogLevel error WSGIScriptAlias / /wwwclients/thymeandagain/wsgi_handler.py WSGIDaemonProcess thymeandagain user=admin group=admin processes=1 threads=16 WSGIProcessGroup thymeandagain &lt;/VirtualHost&gt; </code></pre> <p>wsgi_handler.py:</p> <pre><code>import sys import os sys.path.append("/wwwclients") os.environ['DJANGO_SETTINGS_MODULE'] = 'thymeandagain.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre> <p>The daemon mod_wsgi is supposed to spawn off is not there, so requests just time out and I get a bunch of "Unable to connect to WSGI daemon process" errors in the logs. Is there something about the WSGIDaemonProcess directive that is preventing creation of the daemon? Thanks in advance for any help...</p> <p>EDIT: I get this in the error log:</p> <pre><code>[[email protected]] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [[email protected]] mcm_get_line():1592 [[email protected]] mcm_server_readable():2582: timeout: Operation now in progress: select(2) call timed out for read(2)able fds [[email protected]] mcm_get_line():1592 [Thu Nov 20 21:18:17 2008] [notice] caught SIGTERM, shutting down [Thu Nov 20 21:18:18 2008] [notice] Digest: generating secret for digest authentication ... [Thu Nov 20 21:18:18 2008] [notice] Digest: done [Thu Nov 20 21:18:18 2008] [notice] mod_python: Creating 4 session mutexes based on 8 max processes and 64 max threads. [Thu Nov 20 21:18:18 2008] [notice] Apache/2.2.3 (Red Hat) mod_python/3.2.8 Python/2.4.3 mod_wsgi/2.1-BRANCH configured -- resuming normal operations </code></pre>
9
2008-11-19T17:21:02Z
1,038,087
<p>The real problem is permissions on Apache log directory. It is necessary to tell Apache/mod_wsgi to use an alternate location for the UNIX sockets used to communicate with the daemon processes. See:</p> <p><a href="http://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location%5FOf%5FUNIX%5FSockets">http://code.google.com/p/modwsgi/wiki/ConfigurationIssues#Location_Of_UNIX_Sockets</a></p>
10
2009-06-24T12:35:32Z
[ "python", "django", "apache", "mod-wsgi" ]
scons : src and include dirs
302,835
<p>can someone give a scons config file which allows the following structure</p> <pre><code>toplevel/ /src - .cc files /include .h files </code></pre> <p>at top level I want the o and final exe.</p>
5
2008-11-19T18:13:08Z
302,964
<p>This question: <a href="http://stackoverflow.com/questions/279860/how-do-i-get-projects-to-place-their-build-output-into-the-same-directory-with">http://stackoverflow.com/questions/279860/...</a> gives a pretty flexible scons skeleton which should serve your needs with a few tweaks to the path variables.</p>
4
2008-11-19T19:01:05Z
[ "python", "scons" ]
scons : src and include dirs
302,835
<p>can someone give a scons config file which allows the following structure</p> <pre><code>toplevel/ /src - .cc files /include .h files </code></pre> <p>at top level I want the o and final exe.</p>
5
2008-11-19T18:13:08Z
302,984
<p>Here is one example of Sconscript file</p> <pre><code>env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:inc', CPPDEFINES=[], LIBS=['glib-2.0']) env.Program('runme', Glob('src/*.c')) </code></pre> <p>(The environment line is not really necessary for the example, but I have it to include the non standard glib header path and left it there so you can get the idea how to add extra includes and defines)</p> <p>The source files are in src directory and header files in inc directory. You run scons from the base directory and the output file is also generated in the same directory.</p>
8
2008-11-19T19:05:01Z
[ "python", "scons" ]
scons : src and include dirs
302,835
<p>can someone give a scons config file which allows the following structure</p> <pre><code>toplevel/ /src - .cc files /include .h files </code></pre> <p>at top level I want the o and final exe.</p>
5
2008-11-19T18:13:08Z
303,597
<pre><code>env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:include', CPPDEFINES=[], LIBS=['glib-2.0']) if ARGUMENTS.get('debug', 0): env.Append(CCFLAGS = ' -g') env.Program('template', Glob('src/*.cc')) </code></pre> <p>Worked a treat. Thanks.</p>
4
2008-11-19T22:20:04Z
[ "python", "scons" ]
How do I install a Python extension module using distutils?
302,867
<p>I'm working on a Python package named "lehmer" that includes a bunch of extension modules written in C. Currently, I have a single extension module, "rng". I am using Python's Distutils to build and install the module. I can compile and install the module, but when I try to import the module using <code>import lehmer.rng</code> or <code>from lehmer import rng</code>, the Python interpreter throws an <code>ImportError</code> exception. I can import "lehmer" fine.</p> <p>Here are the contents of my <code>setup.py</code> file:</p> <pre><code>from distutils.core import setup, Extension exts = [Extension("rng", ["lehmer/rng.c"])] setup(name="lehmer", version="0.1", description="A Lehmer random number generator", author="Steve Park, Dave Geyer, and Michael Dippery", maintainer="Michael Dippery", maintainer_email="[email protected]", packages=["lehmer"], ext_package="lehmer", ext_modules=exts) </code></pre> <p>When I list the contents of Python's <code>site-packages</code> directory, I see the following:</p> <pre><code>th107c-4 lehmer $ ls /scratch/usr/lib64/python2.5/site-packages/lehmer __init__.py __init__.pyc rng.so* </code></pre> <p>My <code>PYTHONPATH</code> environment variable is set correctly, so that's not the problem (and as noted before, I can <code>import lehmer</code> just fine, so I <em>know</em> that <code>PYTHONPATH</code> is not the issue). Python uses the following search paths (as reported by <code>sys.path</code>):</p> <pre><code>['', '/scratch/usr/lib64/python2.5/site-packages', '/usr/lib/python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-dynload', '/usr/lib64/python2.5/site-packages', '/usr/lib64/python2.5/site-packages/Numeric', '/usr/lib64/python2.5/site-packages/PIL', '/usr/lib64/python2.5/site-packages/SaX', '/usr/lib64/python2.5/site-packages/gtk-2.0', '/usr/lib64/python2.5/site-packages/wx-2.8-gtk2-unicode', '/usr/local/lib64/python2.5/site-packages'] </code></pre> <h2>Update</h2> <p>It works when used on an OpenSUSE 10 box, but the C extensions still fail to load when tested on Mac OS X. Here are the results from the Python interpreter:</p> <pre><code>&gt;&gt;&gt; sys.path ['', '/usr/local/lib/python2.5/site-packages', '/opt/local/lib/python25.zip', '/opt/local/lib/python2.5', '/opt/local/lib/python2.5/plat-darwin', '/opt/local/lib/python2.5/plat-mac', '/opt/local/lib/python2.5/plat-mac/lib-scriptpackages', '/opt/local/lib/python2.5/lib-tk', '/opt/local/lib/python2.5/lib-dynload', '/opt/local/lib/python2.5/site-packages'] &gt;&gt;&gt; from lehmer import rng Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name rng &gt;&gt;&gt; import lehmer.rngs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named rngs &gt;&gt;&gt; import lehmer.rng Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named rng &gt;&gt;&gt; from lehmer import rngs Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name rngs </code></pre>
1
2008-11-19T18:23:33Z
436,038
<p>For the record (and because I am tired of seeing this marked as unanswered), here were the problems:</p> <ol> <li>Since the current directory is automatically added to the Python packages path, the interpreter was first looking in the current directory for packages; since some C modules were not compiled in the current directory, the interpreter couldn't find them. <strong>Solution:</strong> Don't launch the interpreter from the same directory in which your working copy of the code is stored.</li> <li>Distutils did not install the module with the correct permissions on OS X. <strong>Solution:</strong> Fix the permissions.</li> </ol>
3
2009-01-12T16:41:37Z
[ "python", "module", "distutils" ]
Best Django 'CMS' component for integration into existing site
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
13
2008-11-19T19:04:55Z
303,481
<p>See <a href="http://djangoplugables.com/" rel="nofollow">django-plugables</a> website, there are few CMS components for Django listed (and some look really good).</p>
2
2008-11-19T21:44:28Z
[ "python", "django", "content-management-system" ]
Best Django 'CMS' component for integration into existing site
302,983
<p>So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. </p> <p>Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface? </p>
13
2008-11-19T19:04:55Z
310,852
<p>I've had success with integrating <a href="http://django-cms.org" rel="nofollow">django-cms</a>. Just include it at the end of your urlconf and it won't interfere. (You'll just lose the the nice 404 page when <code>DEBUG=True</code>)</p> <p>Using various combinations of context processors and custom template tags I've been able to do everything I've needed, but if you <em>really</em> need to insert the content into your own view, that should be easy enough. (Perhaps call <code>cms.views.render_page()</code> with a template that lacks all the wrapper html?)</p>
1
2008-11-22T04:20:47Z
[ "python", "django", "content-management-system" ]