title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Possible: Program executing Qt3 and Qt4 code?
910,230
<p>Maybe its a very dumb question but I hope you can give me some answers.</p> <p>I have a commercial application which uses Qt3 for its GUI and an embedded Python interpreter (command line) for scripting. I want to write a custom plugin for this application which uses Qt4. The plugin is mainly a subclassed QMainWindow-class that is linked into a dll (so I am on Windows) together with a boost python wrapper. The python wrapper should be the interface between my plugin and my commercial application.</p> <p>So my question: is this possible?? So is running Qt3 code independent from running Qt4 code in the same application.</p> <p>First experiments resulted in application shutdown, I will try to investigate this further...</p> <p>Thank you!</p> <p>Edit: My application crashed because I didn´t created a QT4 qapplication instance. So when I create the instance everything works well without the additional Qt namespace (which is suggested in the answers, so no need to recompile)! ;)</p>
3
2009-05-26T11:35:27Z
910,452
<p>See <a href="http://labs.trolltech.com/forums/topic/414" rel="nofollow">this thread</a> on a Trolltech forum. (Well actually that's about Qt3 plugins in a Qt4 app but I suspect the answer is much the same). </p> <p>Update: link now a dud, but the <a href="http://web.archive.org/web/20090112213159/http://labs.trolltech.com/forums/topic/414" rel="nofollow">wayback machine</a> has it.</p>
3
2009-05-26T12:36:00Z
[ "c++", "python", "windows", "qt", "boost" ]
Possible: Program executing Qt3 and Qt4 code?
910,230
<p>Maybe its a very dumb question but I hope you can give me some answers.</p> <p>I have a commercial application which uses Qt3 for its GUI and an embedded Python interpreter (command line) for scripting. I want to write a custom plugin for this application which uses Qt4. The plugin is mainly a subclassed QMainWindow-class that is linked into a dll (so I am on Windows) together with a boost python wrapper. The python wrapper should be the interface between my plugin and my commercial application.</p> <p>So my question: is this possible?? So is running Qt3 code independent from running Qt4 code in the same application.</p> <p>First experiments resulted in application shutdown, I will try to investigate this further...</p> <p>Thank you!</p> <p>Edit: My application crashed because I didn´t created a QT4 qapplication instance. So when I create the instance everything works well without the additional Qt namespace (which is suggested in the answers, so no need to recompile)! ;)</p>
3
2009-05-26T11:35:27Z
910,558
<p>This might be possible by namespacing Qt. From <code>configure --help</code>;</p> <pre><code>-qtnamespace &lt;name&gt; Wraps all Qt library code in 'namespace &lt;name&gt; {...}'. </code></pre> <p>Theoretically this should prevent the symbol clashes which is likely making your current approach fail.</p>
3
2009-05-26T13:02:07Z
[ "c++", "python", "windows", "qt", "boost" ]
Django objects change model field
910,287
<p>This doesn't work:</p> <pre><code>&gt;&gt;&gt; pa = Person.objects.all() &gt;&gt;&gt; pa[2].nickname u'arst' &gt;&gt;&gt; pa[2].nickname = 'something else' &gt;&gt;&gt; pa[2].save() &gt;&gt;&gt; pa[2].nickname u'arst' </code></pre> <p>But it works if you take </p> <pre><code> p = Person.objects.get(pk=2) </code></pre> <p>and change the nick.</p> <p>Why so.</p>
2
2009-05-26T11:44:43Z
910,330
<p>If you assigned your <code>pa[2]</code> to a variable, like you do with <code>Person.objects.get(pk=2)</code> you'd have it right:</p> <pre><code>pa = Person.objects.all() print pa[2].nickname 'Jonny' pa[2].nickname = 'Billy' print pa[2].nickname 'Jonny' # when you assign it to some variable, your operations # change this particular object, not something that is queried out each time p1 = pa[2] print p1.nickname 'Jonny' p1.nickname = 'Billy' print p1.nickname 'Billy' </code></pre> <p>This has nothing to do with the method you pull the objects from database.</p> <p>And, btw, django numbers PrimaryKeys starting from 1, not 0, so</p> <pre><code>Person.objects.all()[2] == Person.objects.get(pk=2) False Person.objects.all()[2] == Person.objects.get(pk=3) True </code></pre>
3
2009-05-26T11:58:37Z
[ "python", "django", "django-models" ]
Django objects change model field
910,287
<p>This doesn't work:</p> <pre><code>&gt;&gt;&gt; pa = Person.objects.all() &gt;&gt;&gt; pa[2].nickname u'arst' &gt;&gt;&gt; pa[2].nickname = 'something else' &gt;&gt;&gt; pa[2].save() &gt;&gt;&gt; pa[2].nickname u'arst' </code></pre> <p>But it works if you take </p> <pre><code> p = Person.objects.get(pk=2) </code></pre> <p>and change the nick.</p> <p>Why so.</p>
2
2009-05-26T11:44:43Z
911,863
<pre><code>&gt;&gt;&gt; type(Person.objects.all()) &lt;class 'django.db.models.query.QuerySet'&gt; &gt;&gt;&gt; pa = Person.objects.all() # Not evaluated yet - lazy &gt;&gt;&gt; type(pa) &lt;class 'django.db.models.query.QuerySet'&gt; </code></pre> <p>DB queried to give you a Person object</p> <pre><code>&gt;&gt;&gt; pa[2] </code></pre> <p>DB queried again to give you yet another Person object. </p> <pre><code>&gt;&gt;&gt; pa[2].first_name = "Blah" </code></pre> <p>Let's call this instance PersonObject1 that resides in memory. So it's equivalent to something like this:</p> <pre><code>&gt;&gt;&gt; PersonObject1.first_name = "Blah" </code></pre> <p>Now let's do this:</p> <pre><code>&gt;&gt;&gt; pa[2].save() </code></pre> <p>The pa[2] again queries a db an returns Another instance of person object, say PersonObject2 for example. Which will be unchanged! So it's equvivalent to calling something like:</p> <pre><code>PersonObject2.save() </code></pre> <p>But this has nothing to do with PersonObject1.</p>
10
2009-05-26T17:41:35Z
[ "python", "django", "django-models" ]
Django objects change model field
910,287
<p>This doesn't work:</p> <pre><code>&gt;&gt;&gt; pa = Person.objects.all() &gt;&gt;&gt; pa[2].nickname u'arst' &gt;&gt;&gt; pa[2].nickname = 'something else' &gt;&gt;&gt; pa[2].save() &gt;&gt;&gt; pa[2].nickname u'arst' </code></pre> <p>But it works if you take </p> <pre><code> p = Person.objects.get(pk=2) </code></pre> <p>and change the nick.</p> <p>Why so.</p>
2
2009-05-26T11:44:43Z
911,971
<p><code>Person.objects.all()</code> returns a <code>QuerySet</code>, which is lazy (doesn't perform a DB query until data is requested from it). Slicing a <code>QuerySet</code> (pa[2]) performs a database query to get a single row from the database (using LIMIT and OFFSET in SQL). Slicing the same <code>QuerySet</code> again doesn't do the DB query again (results are cached) but it does return a <em>new</em> instance of the model. Each time you access pa[2] you are getting a new Person instance (albeit with all the same data in it).</p>
2
2009-05-26T18:13:04Z
[ "python", "django", "django-models" ]
A reliable way to determine if ntfs permissions were inherited
910,696
<p>I have a somewhat obscure question here.</p> <p>What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited.</p> <p>How I tried to solve this: using winapi bindings for python (win32security module, to be precise). Here is the stripped down version, that does just that, - it simply takes a path to a file as an argument and prints out ACEs one by one, indicating which flags are set.</p> <pre><code>#!/usr/bin/env python from win32security import * import sys def decode_flags(flags): _flags = { SE_DACL_PROTECTED:"SE_DACL_PROTECTED", SE_DACL_AUTO_INHERITED:"SE_DACL_AUTO_INHERITED", OBJECT_INHERIT_ACE:"OBJECT_INHERIT_ACE", CONTAINER_INHERIT_ACE:"CONTAINER_INHERIT_ACE", INHERIT_ONLY_ACE:"INHERIT_ONLY_ACE", NO_INHERITANCE:"NO_INHERITANCE", NO_PROPAGATE_INHERIT_ACE:"NO_PROPAGATE_INHERIT_ACE", INHERITED_ACE:"INHERITED_ACE" } for key in _flags.keys(): if (flags &amp; key): print '\t','\t',_flags[key],"is set!" def main(argv): target = argv[0] print target security_descriptor = GetFileSecurity(target,DACL_SECURITY_INFORMATION) dacl = security_descriptor.GetSecurityDescriptorDacl() for ace_index in range(dacl.GetAceCount()): (ace_type,ace_flags),access_mask,sid = dacl.GetAce(ace_index) name,domain,account_type = LookupAccountSid(None,sid) print '\t',domain+'\\'+name,hex(ace_flags) decode_flags(ace_flags) if __name__ == '__main__': main(sys.argv[1:]) </code></pre> <p>Simple enough - get a security descriptor, get a DACL from it then iterate through the ACEs in the DACL. The really important bit here is INHERITED_ACE access flag. It should be set when the ACE is inherited and not set explicitly. </p> <p>When you create a folder/file, its ACL gets populated with ACEs according to the ACEs of the parent object (folder), that are set to propagate to children. However, unless you do any change to the access list, the INHERITED_ACE flag will NOT be set! But the inherited permissions are there and they DO work. </p> <p>If you do any slight change (say, add an entry to the access list, apply changes and delete it), the flag magically appears (the behaviour does not change in any way, though, it worked before and it works afterwards)! What I want is to find the source of this behaviour of the INHERITED_ACE flag and, maybe find another <em>reliable</em> way to determine if the ACE was inherited or not.</p> <p>How to reproduce:</p> <ol> <li>Create an object (file or folder)</li> <li>Check permissions in windows explorer, see that they have been propagated from the parent object (using, say, security tab of file properties dialog of windows explorer).</li> <li>Check the flags using, for example, the script I was using (INHERITED_ACE will NOT be set on any ACEs).</li> <li>Change permissions of an object (apply changes), change them back even.</li> <li>Check the flags (INHERITED_ACE <em>will</em> be there)</li> <li>..shake your head in disbelief (I know I did)</li> </ol> <p>Sorry for a somewhat lengthy post, hope this makes at least a little sense.</p>
5
2009-05-26T13:31:29Z
1,036,160
<p>You can use the .Net framework </p> <pre><code>System.Security.AccessControl </code></pre> <p>This covers ACL and DACL and SACL.</p>
1
2009-06-24T02:32:39Z
[ "python", "winapi", "acl", "ntfs", "file-permissions" ]
A reliable way to determine if ntfs permissions were inherited
910,696
<p>I have a somewhat obscure question here.</p> <p>What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited.</p> <p>How I tried to solve this: using winapi bindings for python (win32security module, to be precise). Here is the stripped down version, that does just that, - it simply takes a path to a file as an argument and prints out ACEs one by one, indicating which flags are set.</p> <pre><code>#!/usr/bin/env python from win32security import * import sys def decode_flags(flags): _flags = { SE_DACL_PROTECTED:"SE_DACL_PROTECTED", SE_DACL_AUTO_INHERITED:"SE_DACL_AUTO_INHERITED", OBJECT_INHERIT_ACE:"OBJECT_INHERIT_ACE", CONTAINER_INHERIT_ACE:"CONTAINER_INHERIT_ACE", INHERIT_ONLY_ACE:"INHERIT_ONLY_ACE", NO_INHERITANCE:"NO_INHERITANCE", NO_PROPAGATE_INHERIT_ACE:"NO_PROPAGATE_INHERIT_ACE", INHERITED_ACE:"INHERITED_ACE" } for key in _flags.keys(): if (flags &amp; key): print '\t','\t',_flags[key],"is set!" def main(argv): target = argv[0] print target security_descriptor = GetFileSecurity(target,DACL_SECURITY_INFORMATION) dacl = security_descriptor.GetSecurityDescriptorDacl() for ace_index in range(dacl.GetAceCount()): (ace_type,ace_flags),access_mask,sid = dacl.GetAce(ace_index) name,domain,account_type = LookupAccountSid(None,sid) print '\t',domain+'\\'+name,hex(ace_flags) decode_flags(ace_flags) if __name__ == '__main__': main(sys.argv[1:]) </code></pre> <p>Simple enough - get a security descriptor, get a DACL from it then iterate through the ACEs in the DACL. The really important bit here is INHERITED_ACE access flag. It should be set when the ACE is inherited and not set explicitly. </p> <p>When you create a folder/file, its ACL gets populated with ACEs according to the ACEs of the parent object (folder), that are set to propagate to children. However, unless you do any change to the access list, the INHERITED_ACE flag will NOT be set! But the inherited permissions are there and they DO work. </p> <p>If you do any slight change (say, add an entry to the access list, apply changes and delete it), the flag magically appears (the behaviour does not change in any way, though, it worked before and it works afterwards)! What I want is to find the source of this behaviour of the INHERITED_ACE flag and, maybe find another <em>reliable</em> way to determine if the ACE was inherited or not.</p> <p>How to reproduce:</p> <ol> <li>Create an object (file or folder)</li> <li>Check permissions in windows explorer, see that they have been propagated from the parent object (using, say, security tab of file properties dialog of windows explorer).</li> <li>Check the flags using, for example, the script I was using (INHERITED_ACE will NOT be set on any ACEs).</li> <li>Change permissions of an object (apply changes), change them back even.</li> <li>Check the flags (INHERITED_ACE <em>will</em> be there)</li> <li>..shake your head in disbelief (I know I did)</li> </ol> <p>Sorry for a somewhat lengthy post, hope this makes at least a little sense.</p>
5
2009-05-26T13:31:29Z
1,040,954
<p>On my Win XP Home Edition this code doesn't seem to work at all :-)</p> <p>I get this stack trace:</p> <blockquote> <p>Traceback (most recent call last):<br /> File "C:\1.py", line 37, in main(sys.argv[1:])<br /> File "C:\1.py", line 29, in main for ace_index in range(dacl.GetAceCount()):</p> <p>AttributeError: 'NoneType' object has no attribute 'GetAceCount'</p> </blockquote> <p>Can you just try to "nudge" the DACL to be filled? I mean, if you know it's going to work after you make a slight change in it... do a slight change programmatically, add a stub ACE and remove it. Can you?</p> <p><strong>UPDATE.</strong> I made an experiment with a C# program on my work machine (with Win XP Prof) and I must tell you that the .net way of getting this security information actually works. So, when I create a new file, my C# program detects that the ACEs were inherited, while your python code doesn't.</p> <p>Here is the sample output of my runs:</p> <blockquote> <p>C:>csharp_tricks.exe 2.txt</p> <p>FullControl --> IsInherited: True</p> <p>FullControl --> IsInherited: True</p> <p>ReadAndExecute, Synchronize --> IsInherited: True</p> <p><hr /></p> <p>C:>1.py 2.txt</p> <p>2.txt</p> <p>BUILTIN\Administrators 0x0</p> <p>NT AUTHORITY\SYSTEM 0x0</p> <p>BUILTIN\Users 0x0</p> </blockquote> <p>My C# class:</p> <pre><code>public class InheritedAce { public static string GetDACLReport(string path) { StringBuilder result = new StringBuilder(); FileSecurity fs = new FileSecurity(path, AccessControlSections.Access); foreach (var rule in fs.GetAccessRules(true, true, typeof(SecurityIdentifier)).OfType&lt;FileSystemAccessRule&gt;()) { result.AppendFormat("{0} --&gt; IsInherited: {1}", rule.FileSystemRights, rule.IsInherited); result.AppendLine(); } return result.ToString(); } } </code></pre> <p>So, it seems to be a bug in the python pywin32 security library. Maybe they aren't doing all the necessary system calls...</p>
0
2009-06-24T20:58:07Z
[ "python", "winapi", "acl", "ntfs", "file-permissions" ]
A reliable way to determine if ntfs permissions were inherited
910,696
<p>I have a somewhat obscure question here.</p> <p>What I need: To determine if the permissions (or, strictly speaking, a specific ACE of a DACL) of a file/folder was inherited.</p> <p>How I tried to solve this: using winapi bindings for python (win32security module, to be precise). Here is the stripped down version, that does just that, - it simply takes a path to a file as an argument and prints out ACEs one by one, indicating which flags are set.</p> <pre><code>#!/usr/bin/env python from win32security import * import sys def decode_flags(flags): _flags = { SE_DACL_PROTECTED:"SE_DACL_PROTECTED", SE_DACL_AUTO_INHERITED:"SE_DACL_AUTO_INHERITED", OBJECT_INHERIT_ACE:"OBJECT_INHERIT_ACE", CONTAINER_INHERIT_ACE:"CONTAINER_INHERIT_ACE", INHERIT_ONLY_ACE:"INHERIT_ONLY_ACE", NO_INHERITANCE:"NO_INHERITANCE", NO_PROPAGATE_INHERIT_ACE:"NO_PROPAGATE_INHERIT_ACE", INHERITED_ACE:"INHERITED_ACE" } for key in _flags.keys(): if (flags &amp; key): print '\t','\t',_flags[key],"is set!" def main(argv): target = argv[0] print target security_descriptor = GetFileSecurity(target,DACL_SECURITY_INFORMATION) dacl = security_descriptor.GetSecurityDescriptorDacl() for ace_index in range(dacl.GetAceCount()): (ace_type,ace_flags),access_mask,sid = dacl.GetAce(ace_index) name,domain,account_type = LookupAccountSid(None,sid) print '\t',domain+'\\'+name,hex(ace_flags) decode_flags(ace_flags) if __name__ == '__main__': main(sys.argv[1:]) </code></pre> <p>Simple enough - get a security descriptor, get a DACL from it then iterate through the ACEs in the DACL. The really important bit here is INHERITED_ACE access flag. It should be set when the ACE is inherited and not set explicitly. </p> <p>When you create a folder/file, its ACL gets populated with ACEs according to the ACEs of the parent object (folder), that are set to propagate to children. However, unless you do any change to the access list, the INHERITED_ACE flag will NOT be set! But the inherited permissions are there and they DO work. </p> <p>If you do any slight change (say, add an entry to the access list, apply changes and delete it), the flag magically appears (the behaviour does not change in any way, though, it worked before and it works afterwards)! What I want is to find the source of this behaviour of the INHERITED_ACE flag and, maybe find another <em>reliable</em> way to determine if the ACE was inherited or not.</p> <p>How to reproduce:</p> <ol> <li>Create an object (file or folder)</li> <li>Check permissions in windows explorer, see that they have been propagated from the parent object (using, say, security tab of file properties dialog of windows explorer).</li> <li>Check the flags using, for example, the script I was using (INHERITED_ACE will NOT be set on any ACEs).</li> <li>Change permissions of an object (apply changes), change them back even.</li> <li>Check the flags (INHERITED_ACE <em>will</em> be there)</li> <li>..shake your head in disbelief (I know I did)</li> </ol> <p>Sorry for a somewhat lengthy post, hope this makes at least a little sense.</p>
5
2009-05-26T13:31:29Z
2,213,129
<p>I think the original poster is seeing behavior detailed in</p> <p><a href="http://groups.google.co.uk/group/microsoft.public.platformsdk.security/browse_thread/thread/5204736623c71a84/" rel="nofollow">This newsgroup posting</a></p> <p>Note that the control flags set on the container can change simply by un-ticking and re-ticking the inheritance box in the GUI.</p> <p>Further note that simply adding an ACE to the DACL using Microsoft's tools will also change the control flags.</p> <p>Further note that the GUI, cacls and icacls can NOT be relied on when it comes to inheritance due to many subtle bugs as discussed in the newsgroup posting.</p> <p>It seems that the "old" way of controlling inheritance was to use the control flags on the container in combination with inheritance related ACE flags.</p> <p>The "new" way does not use the control flags on the container and instead uses duplicate ACEs; one to control the access on the object and a second one to control what is inherited by child objects.</p> <p>BUT, it seems the existing Microsoft tools (e.g. Vista) can not work in the "new" way yet, so when you make a simple change using the tools, it resorts to the old way of using control flags on the container.</p> <p>If you create a new partition on Vista, then create a new folder, then look at the flags and ACEs, it will look something like this</p> <pre><code>ControlFlags : 0x8004 Owner : BUILTIN\Administrators Group : WS1\None S-1-5-32-544 : BUILTIN\Administrators : 0x0 : 0x0 : 0x1F01FF S-1-5-32-544 : BUILTIN\Administrators : 0x0 : 0xB : 0x10000000 S-1-5-18 : NT AUTHORITY\SYSTEM : 0x0 : 0x0 : 0x1F01FF S-1-5-18 : NT AUTHORITY\SYSTEM : 0x0 : 0xB : 0x10000000 S-1-5-11 : NT AUTHORITY\Authenticated Users : 0x0 : 0x0 : 0x1301BF S-1-5-11 : NT AUTHORITY\Authenticated Users : 0x0 : 0xB : 0xE0010000 S-1-5-32-545 : BUILTIN\Users : 0x0 : 0x0 : 0x1200A9 S-1-5-32-545 : BUILTIN\Users : 0x0 : 0xB : 0xA0000000 </code></pre> <p>Note the ControlFlags and the duplicated ACEs.</p>
0
2010-02-06T12:50:53Z
[ "python", "winapi", "acl", "ntfs", "file-permissions" ]
Send an xmpp message using a python library
910,737
<p>How can I send an XMPP message using one of the following Python libraries: wokkel, xmpppy, or jabber.py ?</p> <p>I think I am aware of the pseudo-code, but so far have not been able to get one running correctly. This is what I have tried so far:</p> <ul> <li>Call some API and pass the servername and port number to connect to that server. </li> <li>Call some API and pass the username, password to construct a JID object. </li> <li>Authenticate with that JID. </li> <li>Construct a Message object and call some API and pass that message obj in the argument.</li> <li>Call some send API.</li> </ul> <p>It seems easy enough in concept, but the devil is somewhere in the details. Please show a sample snippet if that's possible.</p>
11
2009-05-26T13:39:08Z
912,629
<p>This is the simplest possible xmpp client. It will send a 'hello :)' message. I'm using <a href="https://pypi.python.org/pypi/xmpppy" rel="nofollow"><code>xmpppy</code></a> in the example. And connecting to gtalk server. I think the example is self-explanatory:</p> <pre><code>import xmpp username = 'username' passwd = 'password' to='name@example.com' msg='hello :)' client = xmpp.Client('gmail.com') client.connect(server=('talk.google.com',5223)) client.auth(username, passwd, 'botty') client.sendInitPresence() message = xmpp.Message(to, msg) message.setAttr('type', 'chat') client.send(message) </code></pre>
38
2009-05-26T20:36:32Z
[ "python", "xmpp" ]
Send an xmpp message using a python library
910,737
<p>How can I send an XMPP message using one of the following Python libraries: wokkel, xmpppy, or jabber.py ?</p> <p>I think I am aware of the pseudo-code, but so far have not been able to get one running correctly. This is what I have tried so far:</p> <ul> <li>Call some API and pass the servername and port number to connect to that server. </li> <li>Call some API and pass the username, password to construct a JID object. </li> <li>Authenticate with that JID. </li> <li>Construct a Message object and call some API and pass that message obj in the argument.</li> <li>Call some send API.</li> </ul> <p>It seems easy enough in concept, but the devil is somewhere in the details. Please show a sample snippet if that's possible.</p>
11
2009-05-26T13:39:08Z
1,083,324
<p><a href="http://xmpppy.sourceforge.net/" rel="nofollow">xmpppy</a> has a number of examples listed on its main page (under "examples"), the most basic of which <a href="http://xmpppy.sourceforge.net/examples/README.py" rel="nofollow">sends a single test message</a>. They make the examples progressively more interesting -- they introduce the callback-oriented API via a <a href="http://xmpppy.sourceforge.net/examples/xtalk.py" rel="nofollow">chat bot program</a>.</p>
2
2009-07-05T01:46:45Z
[ "python", "xmpp" ]
How to show characters non ascii in python?
910,809
<p>I'm using the Python Shell in this way:</p> <pre><code>&gt;&gt;&gt; s = 'Ã' &gt;&gt;&gt; s '\xc3' </code></pre> <p>How can I print s variable to show the character Ã??? This is the first and easiest question. Really, I'm getting the content from a web page that has non ascii characters like the previous and others with tilde like á, é, í, ñ, etc. Also, I'm trying to execute a regex with these characters in the pattern expression against the content of the web page. </p> <p>How can solve this problem??</p> <p>This is an example of one regex: </p> <pre><code>u'&lt;td[^&gt;]*&gt;\s*Definición\s*&lt;/td&gt;&lt;td class="value"[^&gt;]*&gt;\s*(?P&lt;data&gt;[\w ,-:\.\(\)]+)\s*&lt;/td&gt;' </code></pre> <p>If I use Expresson application works fine.</p> <p>EDIT[05/26/2009 16:38]: Sorry, about my explanation. I'll try to explain better.</p> <p>I have to get some text from a page. I have the url of that page and I have the regex to get that text. The first thing I thought was the regex was wrong. I checked it with Expresso and works fine, I got the text I wanted. So, the second thing I thought was to print the content of the page and that was when I saw that the content was not what I see in the source code of the web page. The differences are the non ascii characters like á, é, í, etc. Now, I don't know what I have to do and if the problem is in the encoding of the page content or in the pattern text of the regex. One of the regex I've defined is the previous one.</p> <p>The question wolud be: is there any problem using regex which pattern text has non ascii characters???</p>
0
2009-05-26T13:53:18Z
910,880
<p><strong>How can I print s variable to show the character Ã???</strong><br> use <code>print</code>:</p> <pre><code>&gt;&gt;&gt; s = 'Ã' &gt;&gt;&gt; s '\xc3' &gt;&gt;&gt; print s à </code></pre>
2
2009-05-26T14:06:47Z
[ "python", "urllib2" ]
How to show characters non ascii in python?
910,809
<p>I'm using the Python Shell in this way:</p> <pre><code>&gt;&gt;&gt; s = 'Ã' &gt;&gt;&gt; s '\xc3' </code></pre> <p>How can I print s variable to show the character Ã??? This is the first and easiest question. Really, I'm getting the content from a web page that has non ascii characters like the previous and others with tilde like á, é, í, ñ, etc. Also, I'm trying to execute a regex with these characters in the pattern expression against the content of the web page. </p> <p>How can solve this problem??</p> <p>This is an example of one regex: </p> <pre><code>u'&lt;td[^&gt;]*&gt;\s*Definición\s*&lt;/td&gt;&lt;td class="value"[^&gt;]*&gt;\s*(?P&lt;data&gt;[\w ,-:\.\(\)]+)\s*&lt;/td&gt;' </code></pre> <p>If I use Expresson application works fine.</p> <p>EDIT[05/26/2009 16:38]: Sorry, about my explanation. I'll try to explain better.</p> <p>I have to get some text from a page. I have the url of that page and I have the regex to get that text. The first thing I thought was the regex was wrong. I checked it with Expresso and works fine, I got the text I wanted. So, the second thing I thought was to print the content of the page and that was when I saw that the content was not what I see in the source code of the web page. The differences are the non ascii characters like á, é, í, etc. Now, I don't know what I have to do and if the problem is in the encoding of the page content or in the pattern text of the regex. One of the regex I've defined is the previous one.</p> <p>The question wolud be: is there any problem using regex which pattern text has non ascii characters???</p>
0
2009-05-26T13:53:18Z
910,886
<p>I would use <code>ord()</code> to find out if a character is ASCII/special:</p> <pre><code>if ord(c) &gt; 127: # special character </code></pre> <p>This probably won't work with multibyte encodings such as UTF-8. In this case, I would convert to Unicode before testing.</p> <p>If you get special characters from a web page, you should know the encoding. Then decode it, see <a href="http://docs.python.org/howto/unicode.html" rel="nofollow">Unicode HOWTO</a>.</p> <p>Edit: I'm definitely not sure what this question is about... It may be a good idea to clarify it.</p>
1
2009-05-26T14:07:17Z
[ "python", "urllib2" ]
How to show characters non ascii in python?
910,809
<p>I'm using the Python Shell in this way:</p> <pre><code>&gt;&gt;&gt; s = 'Ã' &gt;&gt;&gt; s '\xc3' </code></pre> <p>How can I print s variable to show the character Ã??? This is the first and easiest question. Really, I'm getting the content from a web page that has non ascii characters like the previous and others with tilde like á, é, í, ñ, etc. Also, I'm trying to execute a regex with these characters in the pattern expression against the content of the web page. </p> <p>How can solve this problem??</p> <p>This is an example of one regex: </p> <pre><code>u'&lt;td[^&gt;]*&gt;\s*Definición\s*&lt;/td&gt;&lt;td class="value"[^&gt;]*&gt;\s*(?P&lt;data&gt;[\w ,-:\.\(\)]+)\s*&lt;/td&gt;' </code></pre> <p>If I use Expresson application works fine.</p> <p>EDIT[05/26/2009 16:38]: Sorry, about my explanation. I'll try to explain better.</p> <p>I have to get some text from a page. I have the url of that page and I have the regex to get that text. The first thing I thought was the regex was wrong. I checked it with Expresso and works fine, I got the text I wanted. So, the second thing I thought was to print the content of the page and that was when I saw that the content was not what I see in the source code of the web page. The differences are the non ascii characters like á, é, í, etc. Now, I don't know what I have to do and if the problem is in the encoding of the page content or in the pattern text of the regex. One of the regex I've defined is the previous one.</p> <p>The question wolud be: is there any problem using regex which pattern text has non ascii characters???</p>
0
2009-05-26T13:53:18Z
911,365
<p>Suppose you want to print it as utf-8. Before python 3, the best is to specifically encode it</p> <pre><code>print u'Ã'.encode('utf-8') </code></pre> <p>if you get the text externally then you have to specifically decode('utf-8) such as</p> <pre><code>f = open(my_file) a = f.next().decode('utf-8') # you have a unicode line in a print a.encode('utf-8') </code></pre>
2
2009-05-26T15:41:53Z
[ "python", "urllib2" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
910,954
<p>Well ... If you expect to really <em>fill</em> that space, then you're probably best off with a densely packed matrix-like structure, basically <a href="http://en.wikipedia.org/wiki/Voxel" rel="nofollow">voxels</a>.</p> <p>If you don't expect to fill it, look into something a bit more optimized. I would start by looking at <a href="http://en.wikipedia.org/wiki/Octree" rel="nofollow">octrees</a>, which are often used for things like this.</p>
3
2009-05-26T14:20:43Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
910,981
<p>It depends upon the precise configuration of your system, but from the example you give you are using integers and discrete points, so it would probably be appropriate to consider <a href="http://en.wikipedia.org/wiki/Sparse%5Fmatrix" rel="nofollow">Sparse Matrix</a> data structures. </p>
-1
2009-05-26T14:27:14Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
911,057
<p>You can do the first 2 queries with slicing in numpy :</p> <pre><code>a = numpy.zeros((4, 4, 4)) a[1, 2, 3] # The point at x=1,y=2,z=3 a[:, 2, :] # All points where y=2 </code></pre> <p>For the third one if you mean "getting all points within a sphere of radius 3 and centered at x=1,y=2,z=3", you will have to write a custom function to do that ; if you want a cube you can proceed with slicing, e.g.:</p> <pre><code>a[1:3, 1:3, 1:3] # The 2x2x2 array sliced from the center of 'a' </code></pre> <p>For the fourth query if the only data stored in your array is the cells type, you could encode it as integers:</p> <pre><code>FOO = 1 BAR = 2 a = numpy.zeros((4, 4, 4), dtype="i") a[1, 2, 3] = FOO a[3, 2, 1] = BAR def filter(a, type_code): coords = [] for z in range(4): for y in range(4): for x in range(4): if a[x, y, z] == type_code: coords.append((x, y, z)) return coords filter(a, FOO) # =&gt; [(1, 2, 3)] </code></pre> <p>numpy looks like the good tool for doing what you want, as the arrays will be smaller in memory, easily accessible in C (or even better, <a href="http://www.cython.org/" rel="nofollow">cython</a> !) and extended slicing syntax will avoid you writing code.</p>
0
2009-05-26T14:40:16Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
911,111
<p>One advantage of numpy is that it is blazingly fast, e.g. calculating the pagerank of a 8000x8000 adjacency matrix takes milliseconds. Even though <code>numpy.ndarray</code> will only accept numbers, you can store number/id-object mappings in an external hash-table i.e. dictionary (which in again is a highly optimized datastructure). </p> <p>The slicing would be as easy as list slicing in python:</p> <pre><code>&gt;&gt;&gt; from numpy import arange &gt;&gt;&gt; the_matrix = arange(64).reshape(4, 4, 4) &gt;&gt;&gt; print the_matrix[0][1][2] 6 &gt;&gt;&gt; print the_matrix[0][1] [4 5 6 7] &gt;&gt;&gt; print the_matrix[0] [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] </code></pre> <p>If you wrap some of your desired functions (distances) around some core matrix and a id-object-mapping hash, you could have your application running within a short period of time.</p> <p>Good luck!</p>
1
2009-05-26T14:50:21Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
911,115
<p>Here's an approach that may work.</p> <p>Each point is a 4-tuple (x,y,z,data), and your database looks like this:</p> <pre><code>database = [ (x,y,z,data), (x,y,z,data), ... ] </code></pre> <p>Let's look at your use cases.</p> <p>Get the point where x=1,y=2,z=3.</p> <pre><code>[ (x,y,z,data) for x,y,z,data in database if (x,y,z) == (1,2,3) ] </code></pre> <p>Getting all points where y=2.</p> <pre><code>[ (x,y,z,data) for x,y,z,data in database if y == 2 ] </code></pre> <p>Getting all points within 3 units of position x=1,y=2,z=3.</p> <pre><code>[ (x,y,z,data) for x,y,z,data in database if math.sqrt((x-1)**2+(y-2)**2+(z-3)**2)&lt;=3.0 ] </code></pre> <p>Getting all points where point.getType() == "Foo"</p> <pre><code>[ (x,y,z,data) for x,y,z,data in database if type(data) == Foo ] </code></pre>
0
2009-05-26T14:51:03Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
911,318
<p>Here's another common approach</p> <pre><code>class Point( object ): def __init__( self, x, y, z, data ): self.x, self.y, self.z = x, y, z self.data = data def distFrom( self, x, y, z ) return math.sqrt( (self.x-x)**2 + (self.y-y)**2 + (self.z-z)**2 ) database = [ Point(x,y,z,data), Point(x,y,z,data), ... ] </code></pre> <p>Let's look at your use cases.</p> <p>Get the point where x=1,y=2,z=3.</p> <pre><code>[ p for p in database if (p.x, p.y, p.z) == ( 1, 2, 3 ) ] </code></pre> <p>Getting all points where y=2.</p> <pre><code>[ p for p in database if p.y == 2 ] </code></pre> <p>Getting all points within 3 units of position x=1,y=2,z=3.</p> <pre><code>[ p for p in database if p.distFrom( 1, 2, 3 ) &lt;= 3.0 ] </code></pre> <p>Getting all points where point.getType() == "Foo"</p> <pre><code>[ p for p in database if type(p.data) == Foo ] </code></pre>
3
2009-05-26T15:30:30Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
911,444
<p><a href="http://stackoverflow.com/questions/99796/when-to-use-binary-space-partitioning-quadtree-octree">When to use Binary Space Partitioning, Quadtree, Octree?</a></p> <p>3d array imo is worthless. Especially if your world is dynamic. You should decide between BSP, Quadtree or Octtree. BSP would do just fine. Since your world is in 3d, you need planes when splitting the bsp, not lines.</p> <p>Cheers !</p> <p>Edit</p> <blockquote> <p>I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p> </blockquote> <p>I guess this is alright if always know how large you data set is and that it never changes, i.e. if more points are added to it that in turn are out of bound. You would have to resize the 3d array in that case. </p>
0
2009-05-26T15:59:24Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Storing information on points in a 3d space
910,930
<p>I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like:</p> <ul> <li>Get the point where x=1,y=2,z=3.</li> <li>Getting all points where y=2.</li> <li>Getting all points within 3 units of position x=1,y=2,z=3.</li> <li>Getting all points where point.getType() == "Foo"</li> </ul> <p>In all of the above, I'd need to end up with some sort of output that would give me the original position in the space, and the data stored at that point.</p> <p>Apparently numpy can do what I want, but it seems highly optimised for scientific computing and working out how to get the data like I want above has so far eluded me.</p> <p>Is there a better alternative or should I return to banging my head on the numpy wall? :)</p> <p>EDIT: some more info the first three answers made me realise I should include: I'm not worried about performance, this is purely a proof-of-concept where I'd prefer clean code to good performance. I will also have data for every point in the given 3d space, so I guess a Spare Matrix is bad?</p>
4
2009-05-26T14:17:04Z
911,746
<p>Using a dictionary with x,y,z tuples as keys is another solution, if you want a relatively simple solution with the standard library.</p> <pre><code>import math #use indexing to get point at (1,2,3): points[(1,2,3)] get_points(points, x=None, y=None, x=None): """returns dict of all points with given x,y and/or z values. Call using keywords (eg get_points(points, x=3)""" filteredPoints = points.items() if x: filteredPoints = [p for p in filteredPoints if p[0][0] == x] if y: filteredPoints = [p for p in filteredPoints if p[0][1] == y] if z: filteredPoints = [p for p in filteredPoints if p[0][0] == x] return dict(filteredPoints) get_point_with_type(points, type_): """returns dict of points with point.getType() == type_""" filteredPoints = points.items() return dict((position,data) for position,data in points.iterItems() if data.getType == type_) get_points_in_radius(points,x,y,z,r): """Returns a dict of points within radius r of point (x,y,z)""" def get_dist(x1,y1,z1,x2,y2,z3): return math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2)) return dict((position,data) for position,data in points.iterItems() if get_dist(x,y,z, *position) &lt;= r)) </code></pre> <p>And due to python referencing, you can alter "points" in the returned dictionaries, and have the original points change as well (I think).</p>
0
2009-05-26T17:06:27Z
[ "python", "data-structures", "3d", "matrix", "numpy" ]
Django/Python EnvironmentError?
911,085
<p>I am getting an error when I try to use <code>syncdb</code>:</p> <pre><code>python manage.py syncdb </code></pre> <p>Error message:</p> <pre><code>File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 83, in __init__ raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) EnvironmentError: Could not import settings '/home/simi/workspace/hssn_svn/hssn' (Is it on sys.path? Does ti have syntax errors?): Import by filename is not supported. </code></pre> <p>I'm a newbie with Django/Python, but I can't figure this error out after having researched online for a while now.</p>
2
2009-05-26T14:45:21Z
911,121
<p>Make sure your settings.py file is in the same directory as manage.py (you will also have to run manage.py from this directory, i.e. ./manage.py syncdb), or make the environment variable DJANGO_SETTINGS_MODULE point to it.</p>
1
2009-05-26T14:52:23Z
[ "python", "django", "django-syncdb" ]
Django/Python EnvironmentError?
911,085
<p>I am getting an error when I try to use <code>syncdb</code>:</p> <pre><code>python manage.py syncdb </code></pre> <p>Error message:</p> <pre><code>File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 83, in __init__ raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) EnvironmentError: Could not import settings '/home/simi/workspace/hssn_svn/hssn' (Is it on sys.path? Does ti have syntax errors?): Import by filename is not supported. </code></pre> <p>I'm a newbie with Django/Python, but I can't figure this error out after having researched online for a while now.</p>
2
2009-05-26T14:45:21Z
911,176
<p>Your trace states:</p> <pre><code>Import by filename is not supported. </code></pre> <p>Which might indicate that you try to import (or maybe set the DJANGO_SETTINGS_MODULE) to the full python filename, where it should be a module path: <code>your.module.settings</code></p> <p>You could also try to specify your DJANGO_SETTINGS_MODULE directly from command line, like:</p> <pre><code>$ DJANGO_SETTINGS_MODULE=your.module.settings ./manage.py syncdb </code></pre>
12
2009-05-26T15:04:41Z
[ "python", "django", "django-syncdb" ]
Django/Python EnvironmentError?
911,085
<p>I am getting an error when I try to use <code>syncdb</code>:</p> <pre><code>python manage.py syncdb </code></pre> <p>Error message:</p> <pre><code>File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 83, in __init__ raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e) EnvironmentError: Could not import settings '/home/simi/workspace/hssn_svn/hssn' (Is it on sys.path? Does ti have syntax errors?): Import by filename is not supported. </code></pre> <p>I'm a newbie with Django/Python, but I can't figure this error out after having researched online for a while now.</p>
2
2009-05-26T14:45:21Z
983,548
<p>Another thing that gives this error is permissions - very hard to track down.</p> <p>Solution for me was to move <code>&lt;myproject&gt;</code> to /var/www/<code>&lt;myproject&gt;</code> and do chown -R root:root /var/www/<code>&lt;myproject&gt;</code></p>
1
2009-06-11T20:44:36Z
[ "python", "django", "django-syncdb" ]
python monitoring over serial port
911,089
<p>Good afternoon,</p> <p>I would ask some suggestion about the best way to monitor events over the serial port.</p> <p>I'm using PySerial to write "commands" over the serial port towards some devices and</p> <p>I would like to receive feedback about the status of this devices.</p> <p>Wich is the best way: 1) fullfill a pipe and read into, 2) a new thread delegated to read only, or what?</p> <p>Can I also ask for a simple code to implement the solution?</p>
2
2009-05-26T14:46:20Z
911,772
<p>For general tips on working with pyserial, look at the search S.Lott suggested in the comment.</p> <p>Regarding the best strategy to implement your application - it all depends on how your protocols are defined. Do the devices immediately respond to queries? Or do they continually send data that must be monitored? This is important to define, as it certainly affects the way you'll want to handle the communication.</p> <p>Generally, I've found it simple and stable to have a separate thread reading everything from the serial port and just pumping the data into a <code>Queue</code>. The main application logic then can query this queue whenever it needs to and read the data.</p>
3
2009-05-26T17:13:46Z
[ "python", "pyserial" ]
python monitoring over serial port
911,089
<p>Good afternoon,</p> <p>I would ask some suggestion about the best way to monitor events over the serial port.</p> <p>I'm using PySerial to write "commands" over the serial port towards some devices and</p> <p>I would like to receive feedback about the status of this devices.</p> <p>Wich is the best way: 1) fullfill a pipe and read into, 2) a new thread delegated to read only, or what?</p> <p>Can I also ask for a simple code to implement the solution?</p>
2
2009-05-26T14:46:20Z
919,620
<p>The strategy choosen is to use python multiprocessing and queue see:</p> <ol> <li><p><a href="http://www.ibm.com/developerworks/aix/library/au-threadingpython/index.html" rel="nofollow">http://www.ibm.com/developerworks/aix/library/au-threadingpython/index.html</a> and</p></li> <li><p><a href="http://www.ibm.com/developerworks/aix/library/au-multiprocessing/index.html?ca=dgr-lnxw9dPython-Multi&amp;S_TACT=105AGX59&amp;S_CMP=grsitelnxw9d" rel="nofollow">http://www.ibm.com/developerworks/aix/library/au-multiprocessing/index.html?ca=dgr-lnxw9dPython-Multi&amp;S_TACT=105AGX59&amp;S_CMP=grsitelnxw9d</a></p></li> </ol> <p>for reference </p>
1
2009-05-28T07:32:21Z
[ "python", "pyserial" ]
Python and Qt (PyQt) - calling method before resize event
911,167
<p>i have a question. There is application class in my program. It is inherited from QtGui.QMainWindow. In <strong>ini</strong> I call my own method which works with graphic. And it should be called before resize event. How can i do that? Thanks.</p> <p>EDIT: As you can se <a href="http://doc.trolltech.com/4.2/qevent.html" rel="nofollow">here</a> the value of resize event is 14, and show event is 17. So i should find event with less than 14 value.</p> <p>I found my problem. In constructor before creating handle of image i'm moving window to some position... So during that action resizeEvent calls. Sorry for this question.</p>
1
2009-05-26T15:03:22Z
911,392
<p>You could override in your class the <code>resizeEvent</code> method (which <code>QMainWindows</code> inherits from <code>QWidget</code>), see <a href="http://doc.trolltech.com/4.4/qwidget.html#resizeEvent" rel="nofollow">http://doc.trolltech.com/4.4/qwidget.html#resizeEvent</a> -- in your override, call your other code, then delegate the rest of the work to the parent's version of the method.</p>
1
2009-05-26T15:47:47Z
[ "python", "constructor", "pyqt" ]
Django/Python UserWarning Error
911,273
<p>I keep getting this error/warning, which is annoying, and wanted to see if I can fix it, but I'm not sure where to start (I'm a newbie):</p> <pre><code>/home/simi/workspace/hssn_svn/hssn/../hssn/log/loggers.py:28: UserWarning: ERROR: Could not configure logging warnings.warn('ERROR: Could not configure logging', UserWarning) </code></pre> <p>I'm getting this when I do:</p> <pre><code>python manage.py runserver python manage.py syncdb python manane.py shell </code></pre> <p>Any guidance is greatly appreciated.</p> <p>Thanks, --simi</p>
0
2009-05-26T15:22:09Z
911,596
<p>Do you have write permissions to all the files within the application you are working with. Also make sure you have everything in settings.py setup correctly, make sure specified paths exist and you have permissions.</p>
1
2009-05-26T16:33:10Z
[ "python", "django" ]
Python: Inheriting from Built-In Types
911,375
<p>I have a question concerning subtypes of built-in types and their constructors. I want a class to inherit both from tuple and from a custom class.</p> <p>Let me give you the concrete example. I work a lot with graphs, meaning nodes connected with edges. I am starting to do some work on my own graph framework.</p> <p>There is a class Edge, which has its own attributes and methods. It should also inherit from a class GraphElement. (A GraphElement is every object that has no meaning outside the context of a specific graph.) But at the most basic level, an edge is just a tuple containing two nodes. It would be nice syntactic sugar if you could do the following:</p> <pre><code>edge = graph.create_edge("Spam","Eggs") (u, v) = edge </code></pre> <p>So (u,v) would contain "Spam" and "Eggs". It would also support iteration like</p> <pre><code>for node in edge: ... </code></pre> <p>I hope you see why I would want to subtype tuple (or other basic types like set).</p> <p>So here is my Edge class and its <strong>init</strong>:</p> <pre><code>class Edge(GraphElement, tuple): def __init__(self, graph, (source, target)): GraphElement.__init__(self, graph) tuple.__init__((source, target)) </code></pre> <p>When i call</p> <pre><code>Edge(aGraph, (source, target)) </code></pre> <p>I get a TypeError: tuple() takes at most 1 argument (2 given). What am I doing wrong?</p>
2
2009-05-26T15:43:52Z
911,413
<p>Since tuples are immutable, you need to override the __new__ method as well. See <a href="http://www.python.org/download/releases/2.2.3/descrintro/" rel="nofollow">http://www.python.org/download/releases/2.2.3/descrintro/</a>#__new__</p> <pre><code>class GraphElement: def __init__(self, graph): pass class Edge(GraphElement, tuple): def __new__(cls, graph, (source, target)): return tuple.__new__(cls, (source, target)) def __init__(self, graph, (source, target)): GraphElement.__init__(self, graph) </code></pre>
9
2009-05-26T15:53:07Z
[ "python", "oop", "graph" ]
Python: Inheriting from Built-In Types
911,375
<p>I have a question concerning subtypes of built-in types and their constructors. I want a class to inherit both from tuple and from a custom class.</p> <p>Let me give you the concrete example. I work a lot with graphs, meaning nodes connected with edges. I am starting to do some work on my own graph framework.</p> <p>There is a class Edge, which has its own attributes and methods. It should also inherit from a class GraphElement. (A GraphElement is every object that has no meaning outside the context of a specific graph.) But at the most basic level, an edge is just a tuple containing two nodes. It would be nice syntactic sugar if you could do the following:</p> <pre><code>edge = graph.create_edge("Spam","Eggs") (u, v) = edge </code></pre> <p>So (u,v) would contain "Spam" and "Eggs". It would also support iteration like</p> <pre><code>for node in edge: ... </code></pre> <p>I hope you see why I would want to subtype tuple (or other basic types like set).</p> <p>So here is my Edge class and its <strong>init</strong>:</p> <pre><code>class Edge(GraphElement, tuple): def __init__(self, graph, (source, target)): GraphElement.__init__(self, graph) tuple.__init__((source, target)) </code></pre> <p>When i call</p> <pre><code>Edge(aGraph, (source, target)) </code></pre> <p>I get a TypeError: tuple() takes at most 1 argument (2 given). What am I doing wrong?</p>
2
2009-05-26T15:43:52Z
911,415
<p>You need to override <code>__new__</code> -- currently <code>tuple.__new__</code> is getting called (as you don't override it) with all the arguments you're passing to <code>Edge</code>.</p>
3
2009-05-26T15:53:59Z
[ "python", "oop", "graph" ]
Python: Inheriting from Built-In Types
911,375
<p>I have a question concerning subtypes of built-in types and their constructors. I want a class to inherit both from tuple and from a custom class.</p> <p>Let me give you the concrete example. I work a lot with graphs, meaning nodes connected with edges. I am starting to do some work on my own graph framework.</p> <p>There is a class Edge, which has its own attributes and methods. It should also inherit from a class GraphElement. (A GraphElement is every object that has no meaning outside the context of a specific graph.) But at the most basic level, an edge is just a tuple containing two nodes. It would be nice syntactic sugar if you could do the following:</p> <pre><code>edge = graph.create_edge("Spam","Eggs") (u, v) = edge </code></pre> <p>So (u,v) would contain "Spam" and "Eggs". It would also support iteration like</p> <pre><code>for node in edge: ... </code></pre> <p>I hope you see why I would want to subtype tuple (or other basic types like set).</p> <p>So here is my Edge class and its <strong>init</strong>:</p> <pre><code>class Edge(GraphElement, tuple): def __init__(self, graph, (source, target)): GraphElement.__init__(self, graph) tuple.__init__((source, target)) </code></pre> <p>When i call</p> <pre><code>Edge(aGraph, (source, target)) </code></pre> <p>I get a TypeError: tuple() takes at most 1 argument (2 given). What am I doing wrong?</p>
2
2009-05-26T15:43:52Z
911,452
<p>For what you need, I would avoid multiple inheritance and would implement an iterator using generator:</p> <pre><code>class GraphElement: def __init__(self, graph): pass class Edge(GraphElement): def __init__(self, graph, (source, target)): GraphElement.__init__(self, graph) self.source = source self.target = target def __iter__(self): yield self.source yield self.target </code></pre> <p>In this case both usages work just fine:</p> <pre><code>e = Edge(None, ("Spam","Eggs")) (s, t) = e print s, t for p in e: print p </code></pre>
6
2009-05-26T16:00:22Z
[ "python", "oop", "graph" ]
gnuplot vs Matplotlib
911,655
<p>I've started on a project graphing <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> logs using <a href="http://gnuplot-py.sourceforge.net/">gnuplot-py</a>, specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs <a href="http://matplotlib.sourceforge.net/">Matplotlib</a> for Python graphing. Are there better graphing libraries out there I haven't heard of?</p> <p>My general considerations are:</p> <ul> <li>While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib?</li> <li>Are there things which gnuplot can do, but gnuplot-py can't? </li> <li>Does Matplotlib have better Python support?</li> <li>Are there are big show stopping bugs in either? Annoyances?</li> <li>Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this?</li> <li>Ease of use, turnaround time for gnuplot vs Matplotlib?</li> <li>How easy would it be to port existing gnuplot-py code to Matplotlib?</li> </ul> <p>How would you approach this task?</p>
57
2009-05-26T16:49:02Z
911,754
<p><code>matplotlib</code> has pretty good documentation, and seems to be quite stable. The plots it produces are beautiful - "publication quality" for sure. Due to the good documentation and the amount of example code available online, it's easy to learn and use, and I don't think you'll have much trouble translating <code>gnuplot</code> code to it. After all, matplotlib is being used by scientists to plot data and prepare reports - so it includes everything one needs.</p> <p>One marked advantage of matplotlib is that you can integrate it with Python GUIs (<a href="http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/">wxPython</a> and <a href="http://eli.thegreenplace.net/2009/01/20/matplotlib-with-pyqt-guis/">PyQt</a>, at least) and create GUI application with nice plots.</p>
16
2009-05-26T17:09:47Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
gnuplot vs Matplotlib
911,655
<p>I've started on a project graphing <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> logs using <a href="http://gnuplot-py.sourceforge.net/">gnuplot-py</a>, specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs <a href="http://matplotlib.sourceforge.net/">Matplotlib</a> for Python graphing. Are there better graphing libraries out there I haven't heard of?</p> <p>My general considerations are:</p> <ul> <li>While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib?</li> <li>Are there things which gnuplot can do, but gnuplot-py can't? </li> <li>Does Matplotlib have better Python support?</li> <li>Are there are big show stopping bugs in either? Annoyances?</li> <li>Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this?</li> <li>Ease of use, turnaround time for gnuplot vs Matplotlib?</li> <li>How easy would it be to port existing gnuplot-py code to Matplotlib?</li> </ul> <p>How would you approach this task?</p>
57
2009-05-26T16:49:02Z
911,765
<ul> <li>you can check the <a href="http://matplotlib.sourceforge.net/contents.html">documentation</a> yourself. I find it quite comprehensive.</li> <li>I have very little experience with gnuplot-py, so I can not say.</li> <li>Matplotlib is written in and designed specifically for Python, so it fits very nicely with Python idioms and such.</li> <li>Matplotlib is a mature project. NASA uses it for some stuff.</li> <li>I've plotted tens of millions of points in Matplotlib, and it still looked beautiful and responded quickly.</li> <li>beyond the object-oriented way of using Matplotlib is the pylab interface, which makes plotting as easy as it is in MATLAB -- that is, very easy.</li> <li>as for porting, I have no idea.</li> </ul>
36
2009-05-26T17:12:05Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
gnuplot vs Matplotlib
911,655
<p>I've started on a project graphing <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> logs using <a href="http://gnuplot-py.sourceforge.net/">gnuplot-py</a>, specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs <a href="http://matplotlib.sourceforge.net/">Matplotlib</a> for Python graphing. Are there better graphing libraries out there I haven't heard of?</p> <p>My general considerations are:</p> <ul> <li>While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib?</li> <li>Are there things which gnuplot can do, but gnuplot-py can't? </li> <li>Does Matplotlib have better Python support?</li> <li>Are there are big show stopping bugs in either? Annoyances?</li> <li>Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this?</li> <li>Ease of use, turnaround time for gnuplot vs Matplotlib?</li> <li>How easy would it be to port existing gnuplot-py code to Matplotlib?</li> </ul> <p>How would you approach this task?</p>
57
2009-05-26T16:49:02Z
911,779
<p>I have played with both, and I like Matplotlib much better in terms of Python integration, options, and quality of graphs/plots.</p>
7
2009-05-26T17:15:51Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
gnuplot vs Matplotlib
911,655
<p>I've started on a project graphing <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> logs using <a href="http://gnuplot-py.sourceforge.net/">gnuplot-py</a>, specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs <a href="http://matplotlib.sourceforge.net/">Matplotlib</a> for Python graphing. Are there better graphing libraries out there I haven't heard of?</p> <p>My general considerations are:</p> <ul> <li>While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib?</li> <li>Are there things which gnuplot can do, but gnuplot-py can't? </li> <li>Does Matplotlib have better Python support?</li> <li>Are there are big show stopping bugs in either? Annoyances?</li> <li>Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this?</li> <li>Ease of use, turnaround time for gnuplot vs Matplotlib?</li> <li>How easy would it be to port existing gnuplot-py code to Matplotlib?</li> </ul> <p>How would you approach this task?</p>
57
2009-05-26T16:49:02Z
1,960,904
<p>After using GNUplot (with my own Python wrapper) for a long time (and really not liking the 80s-looking output), I just started having a look at matplotlib. I must say I like it very much, the output looks really nice and the docs are high quality and extensive (although that also goes for GNUplot). The one thing I spent ages looking for in the matplotlib docs is how to write to an image file rather than to the screen! Luckily this page explains it pretty well: <a href="http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib%5Fwithout%5Fgui.html">http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib%5Fwithout%5Fgui.html</a></p>
12
2009-12-25T10:01:31Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
gnuplot vs Matplotlib
911,655
<p>I've started on a project graphing <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> logs using <a href="http://gnuplot-py.sourceforge.net/">gnuplot-py</a>, specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs <a href="http://matplotlib.sourceforge.net/">Matplotlib</a> for Python graphing. Are there better graphing libraries out there I haven't heard of?</p> <p>My general considerations are:</p> <ul> <li>While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib?</li> <li>Are there things which gnuplot can do, but gnuplot-py can't? </li> <li>Does Matplotlib have better Python support?</li> <li>Are there are big show stopping bugs in either? Annoyances?</li> <li>Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this?</li> <li>Ease of use, turnaround time for gnuplot vs Matplotlib?</li> <li>How easy would it be to port existing gnuplot-py code to Matplotlib?</li> </ul> <p>How would you approach this task?</p>
57
2009-05-26T16:49:02Z
15,175,597
<p>What Gnuplot can do Gnuplot-Py can do too. Because Gnuplot can be driven by pipe(pgnuplot). Gnuplot-Py is just a thin layer for it. So you don't need worry about it.</p> <p>Why I prefer gnuplot maybe the many output format(PDF, PS and LaTex), which is very useful in papers, and the default output looks more scientific-style :)</p>
3
2013-03-02T14:29:39Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
gnuplot vs Matplotlib
911,655
<p>I've started on a project graphing <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> logs using <a href="http://gnuplot-py.sourceforge.net/">gnuplot-py</a>, specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs <a href="http://matplotlib.sourceforge.net/">Matplotlib</a> for Python graphing. Are there better graphing libraries out there I haven't heard of?</p> <p>My general considerations are:</p> <ul> <li>While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib?</li> <li>Are there things which gnuplot can do, but gnuplot-py can't? </li> <li>Does Matplotlib have better Python support?</li> <li>Are there are big show stopping bugs in either? Annoyances?</li> <li>Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this?</li> <li>Ease of use, turnaround time for gnuplot vs Matplotlib?</li> <li>How easy would it be to port existing gnuplot-py code to Matplotlib?</li> </ul> <p>How would you approach this task?</p>
57
2009-05-26T16:49:02Z
23,883,352
<h2>Matplotlib = ease of use, Gnuplot = performance</h2> <p>I know this post is old and answered but I was passing by and wanted to put my two cents. Here is my conclusion: as said above, if you have a not-so-big data set, you should use Matplotlib. It's easier and looks better. However, if you need performance, I would recommend that you use Gnuplot. The following graph represents the required time to plot and save random scatter plots and it's self explanatory. </p> <p><img src="http://i.stack.imgur.com/aNQrb.jpg" alt="Gnuplot VS Matplotlib"></p> <p>Moreover, as mentionned in the comments, you can get equivalent quality of plots. But you will have to put more sweat into that to do it with Gnuplot.</p>
17
2014-05-27T07:21:57Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
gnuplot vs Matplotlib
911,655
<p>I've started on a project graphing <a href="http://en.wikipedia.org/wiki/Apache_Tomcat">Tomcat</a> logs using <a href="http://gnuplot-py.sourceforge.net/">gnuplot-py</a>, specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs <a href="http://matplotlib.sourceforge.net/">Matplotlib</a> for Python graphing. Are there better graphing libraries out there I haven't heard of?</p> <p>My general considerations are:</p> <ul> <li>While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib?</li> <li>Are there things which gnuplot can do, but gnuplot-py can't? </li> <li>Does Matplotlib have better Python support?</li> <li>Are there are big show stopping bugs in either? Annoyances?</li> <li>Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this?</li> <li>Ease of use, turnaround time for gnuplot vs Matplotlib?</li> <li>How easy would it be to port existing gnuplot-py code to Matplotlib?</li> </ul> <p>How would you approach this task?</p>
57
2009-05-26T16:49:02Z
27,881,374
<p>About performance and plotting a great number of points: I compared this for a scatterplot of 500.000 points loaded from a text file and saved to a png, using gnuplot* and matplotlib.</p> <pre><code>500.000 points scatterplot gnuplot: 5.171 s matplotlib: 230.693 s </code></pre> <p>I ran it only once and the results don't look identical, but I think the idea is clear: gnuplot wins at performance.</p> <p>*I used gnuplot directly since the gnuplotpy demo doesn't work out-of-the-box for me. Matplotlib wins at Python integration.</p>
3
2015-01-10T21:26:25Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
Extracting titles from PDF files?
911,672
<p>I want to write a script to rename downloaded papers with their titles automatically, I'm wondering if there is any library or tricks i can make use of? The PDFs are all generated by TeX and should have some 'formal' structures.</p>
9
2009-05-26T16:52:40Z
911,707
<p>I would probably start with perl (seeing as it's always the first thing I reach for). There are <a href="http://search.cpan.org/search?mode=module&amp;query=PDF" rel="nofollow">several modules for handling PDFs</a>. If you have a consistent structure, you could use regex to snag the titles.</p>
1
2009-05-26T16:58:14Z
[ "python", "pdf" ]
Extracting titles from PDF files?
911,672
<p>I want to write a script to rename downloaded papers with their titles automatically, I'm wondering if there is any library or tricks i can make use of? The PDFs are all generated by TeX and should have some 'formal' structures.</p>
9
2009-05-26T16:52:40Z
911,708
<p>You could try to use <a href="http://pybrary.net/pyPdf/" rel="nofollow">pyPdf</a> and <a href="http://blog.isnotworking.com/2006/08/extract-pdf-title-from-all-files-on.html" rel="nofollow">this example</a>.</p> <p><strong>for example:</strong></p> <pre><code>from pyPdf import PdfFileWriter, PdfFileReader def get_pdf_title(pdf_file_path): with open(pdf_file_path) as f: pdf_reader = PdfFileReader(f) return pdf_reader.getDocumentInfo().title title = get_pdf_title('/home/user/Desktop/my.pdf') </code></pre>
11
2009-05-26T16:58:14Z
[ "python", "pdf" ]
Extracting titles from PDF files?
911,672
<p>I want to write a script to rename downloaded papers with their titles automatically, I'm wondering if there is any library or tricks i can make use of? The PDFs are all generated by TeX and should have some 'formal' structures.</p>
9
2009-05-26T16:52:40Z
911,719
<p>You can try using <a href="http://www.lowagie.com/iText/" rel="nofollow">iText</a> with <a href="http://www.jython.org/Project/" rel="nofollow">Jython</a></p>
1
2009-05-26T17:00:36Z
[ "python", "pdf" ]
detecting idle time using python
911,856
<p>How do I detect if the system is idle on Windows using Python (i.e. no keyboard or mouse activity). This has already been asked <a href="http://stackoverflow.com/questions/217157/how-can-i-determine-the-display-idle-time-from-python-in-windows-linux-and-maco">before</a>, but there doesn't seem to be a <code>GetLastInputInfo</code> in the <code>pywin32</code> module.</p>
14
2009-05-26T17:39:35Z
911,982
<p>Actually, you can access <code>GetLastInputInfo</code> via the <code>cytpes</code> library:</p> <pre><code>import ctypes GetLastInputInfo = ctypes.windll.User32.GetLastInputInfo # callable function pointer </code></pre> <p>This might not be what you want though, as it does not provide idle information across the whole system, but only about the session that called the function. <a href="http://msdn.microsoft.com/en-us/library/ms646302%28VS.85%29.aspx" rel="nofollow">See MSDN docs.</a></p> <p>Alternatively, you could <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/see%5Fif%5Fmy%5Fworkstation%5Fis%5Flocked.html" rel="nofollow">check if the system is locked</a>, or if the screen-saver has been started.</p>
2
2009-05-26T18:15:37Z
[ "python", "winapi" ]
detecting idle time using python
911,856
<p>How do I detect if the system is idle on Windows using Python (i.e. no keyboard or mouse activity). This has already been asked <a href="http://stackoverflow.com/questions/217157/how-can-i-determine-the-display-idle-time-from-python-in-windows-linux-and-maco">before</a>, but there doesn't seem to be a <code>GetLastInputInfo</code> in the <code>pywin32</code> module.</p>
14
2009-05-26T17:39:35Z
912,223
<pre><code>from ctypes import Structure, windll, c_uint, sizeof, byref class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_uint), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) windll.user32.GetLastInputInfo(byref(lastInputInfo)) millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime return millis / 1000.0 </code></pre> <p>Call <code>get_idle_duration()</code> to get idle time in seconds.</p>
16
2009-05-26T19:17:19Z
[ "python", "winapi" ]
detecting idle time using python
911,856
<p>How do I detect if the system is idle on Windows using Python (i.e. no keyboard or mouse activity). This has already been asked <a href="http://stackoverflow.com/questions/217157/how-can-i-determine-the-display-idle-time-from-python-in-windows-linux-and-maco">before</a>, but there doesn't seem to be a <code>GetLastInputInfo</code> in the <code>pywin32</code> module.</p>
14
2009-05-26T17:39:35Z
3,483,654
<p>Seems like <code>GetLastInputInfo</code> is now available in pywin32:</p> <pre><code>win32api.GetLastInputInfo() </code></pre> <p>does the trick and returns the timer tick from the last user input action. </p> <p>Here with an example program</p> <pre><code>import time import win32api for i in range(10): print(win32api.GetLastInputInfo()) time.sleep(1) </code></pre> <p>If one presses a key/moves the mouse while the script sleeps, the printed number changes. </p>
4
2010-08-14T14:06:35Z
[ "python", "winapi" ]
detecting idle time using python
911,856
<p>How do I detect if the system is idle on Windows using Python (i.e. no keyboard or mouse activity). This has already been asked <a href="http://stackoverflow.com/questions/217157/how-can-i-determine-the-display-idle-time-from-python-in-windows-linux-and-maco">before</a>, but there doesn't seem to be a <code>GetLastInputInfo</code> in the <code>pywin32</code> module.</p>
14
2009-05-26T17:39:35Z
29,730,972
<p>@FogleBird's answer is pretty cool and working, but in a hurry i wasn't sure how it works, so a little test example here. A thread is starting, looking for last idle time every 10 seconds. If any movement is made within this time window, it will be printed out.</p> <pre><code>from ctypes import Structure, windll, c_uint, sizeof, byref import threading //Print out every n seconds the idle time, when moving mouse, this should be &lt; 10 def printit(): threading.Timer(10.0, printit).start() print get_idle_duration() class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_uint), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) windll.user32.GetLastInputInfo(byref(lastInputInfo)) millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime return millis / 1000.0 printit() </code></pre>
0
2015-04-19T14:10:47Z
[ "python", "winapi" ]
detecting idle time using python
911,856
<p>How do I detect if the system is idle on Windows using Python (i.e. no keyboard or mouse activity). This has already been asked <a href="http://stackoverflow.com/questions/217157/how-can-i-determine-the-display-idle-time-from-python-in-windows-linux-and-maco">before</a>, but there doesn't seem to be a <code>GetLastInputInfo</code> in the <code>pywin32</code> module.</p>
14
2009-05-26T17:39:35Z
33,765,403
<pre><code>import win32api def getIdleTime(): return (win32api.GetTickCount() - win32api.GetLastInputInfo()) / 1000.0 </code></pre>
1
2015-11-17T19:27:52Z
[ "python", "winapi" ]
Detect if a NumPy array contains at least one non-numeric value?
911,871
<p>I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the calculation should only return a numeric value). The number of dimensions of the input array is not known in advance - the function should give the correct value regardless of ndim. As an extra complication the input could be a single float or <code>numpy.float64</code> or even something oddball like a zero-dimensional array. </p> <p>The obvious way to solve this is to write a recursive function which iterates over every iterable object in the array until it finds a non-iterabe. It will apply the <code>numpy.isnan()</code> function over every non-iterable object. If at least one non-numeric value is found then the function will return False immediately. Otherwise if all the values in the iterable are numeric it will eventually return True. </p> <p>That works just fine, but it's pretty slow and I expect that <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> has a much better way to do it. What is an alternative that is faster and more numpyish?</p> <p>Here's my mockup:</p> <pre><code>def contains_nan( myarray ): """ @param myarray : An n-dimensional array or a single float @type myarray : numpy.ndarray, numpy.array, float @returns: bool Returns true if myarray is numeric or only contains numeric values. Returns false if at least one non-numeric value exists Not-A-Number is given by the numpy.isnan() function. """ return True </code></pre>
34
2009-05-26T17:43:47Z
913,499
<p>This should be faster than iterating and will work regardless of shape.</p> <pre><code>numpy.isnan(myarray).any() </code></pre> <p>Edit: 30x faster:</p> <pre><code>import timeit s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan' ms = [ 'numpy.isnan(a).any()', 'any(numpy.isnan(x) for x in a.flatten())'] for m in ms: print " %.2f s" % timeit.Timer(m, s).timeit(1000), m </code></pre> <p>Results:</p> <pre><code> 0.11 s numpy.isnan(a).any() 3.75 s any(numpy.isnan(x) for x in a.flatten()) </code></pre> <p>Bonus: it works fine for non-array NumPy types:</p> <pre><code>&gt;&gt;&gt; a = numpy.float64(42.) &gt;&gt;&gt; numpy.isnan(a).any() False &gt;&gt;&gt; a = numpy.float64(numpy.nan) &gt;&gt;&gt; numpy.isnan(a).any() True </code></pre>
49
2009-05-27T00:55:50Z
[ "python", "numpy" ]
Detect if a NumPy array contains at least one non-numeric value?
911,871
<p>I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the calculation should only return a numeric value). The number of dimensions of the input array is not known in advance - the function should give the correct value regardless of ndim. As an extra complication the input could be a single float or <code>numpy.float64</code> or even something oddball like a zero-dimensional array. </p> <p>The obvious way to solve this is to write a recursive function which iterates over every iterable object in the array until it finds a non-iterabe. It will apply the <code>numpy.isnan()</code> function over every non-iterable object. If at least one non-numeric value is found then the function will return False immediately. Otherwise if all the values in the iterable are numeric it will eventually return True. </p> <p>That works just fine, but it's pretty slow and I expect that <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> has a much better way to do it. What is an alternative that is faster and more numpyish?</p> <p>Here's my mockup:</p> <pre><code>def contains_nan( myarray ): """ @param myarray : An n-dimensional array or a single float @type myarray : numpy.ndarray, numpy.array, float @returns: bool Returns true if myarray is numeric or only contains numeric values. Returns false if at least one non-numeric value exists Not-A-Number is given by the numpy.isnan() function. """ return True </code></pre>
34
2009-05-26T17:43:47Z
1,325,396
<p>With numpy 1.3 or svn you can do this</p> <pre><code>In [1]: a = arange(10000.).reshape(100,100) In [3]: isnan(a.max()) Out[3]: False In [4]: a[50,50] = nan In [5]: isnan(a.max()) Out[5]: True In [6]: timeit isnan(a.max()) 10000 loops, best of 3: 66.3 µs per loop </code></pre> <p>The treatment of nans in comparisons was not consistent in earlier versions.</p>
2
2009-08-25T00:04:43Z
[ "python", "numpy" ]
Detect if a NumPy array contains at least one non-numeric value?
911,871
<p>I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the calculation should only return a numeric value). The number of dimensions of the input array is not known in advance - the function should give the correct value regardless of ndim. As an extra complication the input could be a single float or <code>numpy.float64</code> or even something oddball like a zero-dimensional array. </p> <p>The obvious way to solve this is to write a recursive function which iterates over every iterable object in the array until it finds a non-iterabe. It will apply the <code>numpy.isnan()</code> function over every non-iterable object. If at least one non-numeric value is found then the function will return False immediately. Otherwise if all the values in the iterable are numeric it will eventually return True. </p> <p>That works just fine, but it's pretty slow and I expect that <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> has a much better way to do it. What is an alternative that is faster and more numpyish?</p> <p>Here's my mockup:</p> <pre><code>def contains_nan( myarray ): """ @param myarray : An n-dimensional array or a single float @type myarray : numpy.ndarray, numpy.array, float @returns: bool Returns true if myarray is numeric or only contains numeric values. Returns false if at least one non-numeric value exists Not-A-Number is given by the numpy.isnan() function. """ return True </code></pre>
34
2009-05-26T17:43:47Z
33,043,793
<p>If infinity is a possible value, I would use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.isfinite.html#numpy.isfinite" rel="nofollow">numpy.isfinite</a></p> <pre><code>numpy.isfinite(myarray).all() </code></pre> <p>If the above evaluates to <code>True</code>, then <code>myarray</code> contains no, <code>numpy.nan</code>, <code>numpy.inf</code> or <code>-numpy.inf</code> values.</p> <p><code>numpy.nan</code> will be OK with <code>numpy.inf</code> values, for example:</p> <pre><code>In [11]: import numpy as np In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]]) In [13]: np.isnan(b) Out[13]: array([[False, False], [ True, False]], dtype=bool) In [14]: np.isfinite(b) Out[14]: array([[ True, False], [False, False]], dtype=bool) </code></pre>
4
2015-10-09T17:13:34Z
[ "python", "numpy" ]
Is there a way to access the formal parameters if you implement __getattribute__
911,905
<p>It seems as though <code>__getattribute__</code> has only 2 parameters <code>(self, name)</code>.</p> <p>However, in the actual code, the method I am intercepting actually takes arguments.</p> <p>Is there anyway to access those arguments?</p> <p>Thanks,</p> <p>Charlie</p>
2
2009-05-26T17:53:29Z
911,918
<p>Honestly I'm not sure I understand your question. If you want a way to override getattribute and yet keep the original attributes you can use <a href="http://docs.python.org/library/stdtypes.html#object.%5F%5Fdict%5F%5F" rel="nofollow"><code>__dict__</code></a></p> <pre><code>def __getattribute__(self, attr): if attr in self.__dict__: return self.__dict__[attr] # Add your changes here </code></pre>
1
2009-05-26T17:58:47Z
[ "python", "python-datamodel" ]
Is there a way to access the formal parameters if you implement __getattribute__
911,905
<p>It seems as though <code>__getattribute__</code> has only 2 parameters <code>(self, name)</code>.</p> <p>However, in the actual code, the method I am intercepting actually takes arguments.</p> <p>Is there anyway to access those arguments?</p> <p>Thanks,</p> <p>Charlie</p>
2
2009-05-26T17:53:29Z
911,943
<p>Method invocation in Python is two step process, first a function is looked up, then it is invoked. For a more involved discussion see my answer to <a href="http://stackoverflow.com/questions/852308/how-the-method-resolution-and-invocation-works-internally-in-python/870650#870650">this question</a>.</p> <p>So you would need to do something like this:</p> <pre><code>def __getattribute__(self, key): if key == "something_interesting": def func(*args, **kwargs): # use arguments, and possibly the self variable from outer scope return func else: return object.__getattribute__(self, key) </code></pre> <p>Also, overriding __getattribute__ is usually a bad idea. Because it is called on all attribute accesses it is really easy to end up in an infinite loop, and even if you do everything correctly it ends up being a pretty big performance hit. Are you sure that __getattr__ won't be enough for your purposes? Or maybe even a descriptor object that returns functions. Descriptors are usually a lot better at reuse.</p>
3
2009-05-26T18:06:50Z
[ "python", "python-datamodel" ]
Is there a way to access the formal parameters if you implement __getattribute__
911,905
<p>It seems as though <code>__getattribute__</code> has only 2 parameters <code>(self, name)</code>.</p> <p>However, in the actual code, the method I am intercepting actually takes arguments.</p> <p>Is there anyway to access those arguments?</p> <p>Thanks,</p> <p>Charlie</p>
2
2009-05-26T17:53:29Z
911,944
<p><strong>__getattribute__</strong> simply returns the attribute that was requested, in case of a method, the <strong>__call__</strong> interface is then used to call it.</p> <p>Instead of returning the method, return a wrapper around it, for instance:</p> <pre><code>def __getattribute__(self, attr): def make_interceptor(callble): def func(*args, **kwargs): print args, kwargs return callble(*args, **kwargs) return func att = self.__dict__[attr] if callable(att): return make_interceptor(att) </code></pre>
4
2009-05-26T18:06:57Z
[ "python", "python-datamodel" ]
Is there a way to access the formal parameters if you implement __getattribute__
911,905
<p>It seems as though <code>__getattribute__</code> has only 2 parameters <code>(self, name)</code>.</p> <p>However, in the actual code, the method I am intercepting actually takes arguments.</p> <p>Is there anyway to access those arguments?</p> <p>Thanks,</p> <p>Charlie</p>
2
2009-05-26T17:53:29Z
911,953
<p>I don't think you can. <code>__getattribute__</code> doesn't intercept the method call, it only intercepts the method name lookup. So it should return a function (or callable object), which will then be called with whatever parameters specified at the call site.</p> <p>In particular, if it returns a function which takes <code>(*args, **kwargs)</code>, then in that function you can examine the arguments however you want.</p> <p>I think. I'm not a Python expert.</p>
1
2009-05-26T18:08:57Z
[ "python", "python-datamodel" ]
Is there a way to access the formal parameters if you implement __getattribute__
911,905
<p>It seems as though <code>__getattribute__</code> has only 2 parameters <code>(self, name)</code>.</p> <p>However, in the actual code, the method I am intercepting actually takes arguments.</p> <p>Is there anyway to access those arguments?</p> <p>Thanks,</p> <p>Charlie</p>
2
2009-05-26T17:53:29Z
912,110
<p>Yes</p> <pre><code>def argumentViewer(func): def newfunc(*args, **kwargs): print "Calling %r with %r %r" % (func, args, kwargs) return func(*args, **kwargs) return newfunc class Foo(object): def __getattribute__(self, name): print "retrieving data" return object.__getattribute__(self, name) @argumentViewer def bar(self, a, b): return a+b # Output &gt;&gt;&gt; a=Foo() &gt;&gt;&gt; a.bar retrieving data &lt;bound method Foo.newfunc of &lt;__main__.Foo object at 0x01B0E3D0&gt;&gt; &gt;&gt;&gt; a.bar(2,5) retrieving data Calling &lt;function bar at 0x01B0ACF0&gt; with (&lt;__main__.Foo object at 0x01B0E3D0&gt;, 2, 5) {} 7 </code></pre>
0
2009-05-26T18:45:48Z
[ "python", "python-datamodel" ]
Is there a way to access the formal parameters if you implement __getattribute__
911,905
<p>It seems as though <code>__getattribute__</code> has only 2 parameters <code>(self, name)</code>.</p> <p>However, in the actual code, the method I am intercepting actually takes arguments.</p> <p>Is there anyway to access those arguments?</p> <p>Thanks,</p> <p>Charlie</p>
2
2009-05-26T17:53:29Z
1,880,279
<p>Here is a variation on Unknown's suggestion that returns a callable "wrapper" instance in place of the requested function. This does not require decorating any methods:</p> <pre><code>class F(object): def __init__(self, func): self.func = func return def __call__(self, *args, **kw): print "Calling %r:" % self.func print " args: %r" % (args,) print " kw: %r" % kw return self.func(*args,**kw) class C(object): def __init__(self): self.a = 'an attribute that is not callable.' return def __getattribute__(self,name): attr = object.__getattribute__(self,name) if callable(attr): # Return a callable object that can examine, and even # modify the arguments prior to calling the method. return F(attr) # Return the reference to any non-callable attribute. return attr def m(self, *a, **kw): print "hello from m!" return &gt;&gt;&gt; c=C() &gt;&gt;&gt; c.a 'an attribute that is not callable.' &gt;&gt;&gt; c.m &lt;__main__.F object at 0x63ff30&gt; &gt;&gt;&gt; c.m(1,2,y=25,z=26) Calling &lt;bound method C.m of &lt;__main__.C object at 0x63fe90&gt;&gt;: args: (1, 2) kw: {'y': 25, 'z': 26} hello from m! &gt;&gt;&gt; </code></pre> <p><a href="http://stackoverflow.com/questions/911905/is-there-a-way-to-access-the-formal-parameters-if-you-implement-getattribute/911943#911943">Ants Aasma above</a> makes an important point regarding recursion when using <code>__getattribute__</code>. It is called by <strong>all</strong> attribute lookups on <code>self</code>, even those inside of the <code>__getattribute__</code> method. Several of the other examples include references to <code>self.__dict__</code> inside of <code>__getattribute__</code> which will result in recursing until you exceed the maximum stack depth! To avoid this, use one of the base class' versions of <code>__getattribute__</code> (e.g. <code>object.__getattribute__(self,name)</code>.)</p>
0
2009-12-10T11:08:25Z
[ "python", "python-datamodel" ]
Is there a way to access the formal parameters if you implement __getattribute__
911,905
<p>It seems as though <code>__getattribute__</code> has only 2 parameters <code>(self, name)</code>.</p> <p>However, in the actual code, the method I am intercepting actually takes arguments.</p> <p>Is there anyway to access those arguments?</p> <p>Thanks,</p> <p>Charlie</p>
2
2009-05-26T17:53:29Z
17,655,819
<p>Thanks to <a href="http://stackoverflow.com/users/62569/ask">ASk</a> <a href="http://stackoverflow.com/a/911944/1322849">answer</a> (big thank you mate) I managed to solve my problem, however I had to replace</p> <pre><code> att = self.__dict__[attr] </code></pre> <p>with</p> <pre><code>att = type(self).__dict__[attr].__get__(self, type(self)) </code></pre> <p>and here is working example with class decorator:</p> <pre><code>def getattribute(self, name): if name.startswith('__') and name.endswith('__'): return object.__getattribute__(self, name) s = '*** method "%s" of instance "%s" of class "%s" called with'\ ' following' print s % (name, id(self), self.__class__.__name__), def intercept(call, name): def func(*args, **kwargs): print 'args: {}, kwargs: {} ***'.format(args, kwargs) c = call(*args, **kwargs) print '*** "%s" finished ***' % name return c return func a = type(self).__dict__[name].__get__(self, type(self)) if callable(a): return intercept(a, name) return object.__getattribute__(self, name) def inject(cls): setattr(cls, '__getattribute__', getattribute) return cls @inject class My_Str(object): def qwer(self, word='qwer'): print 'qwer done something here...' </code></pre>
0
2013-07-15T13:47:37Z
[ "python", "python-datamodel" ]
Python Best Practices: Abstract Syntax Trees
911,930
<h2>Modifying Abstract Syntax Trees</h2> <p>I would like to be able to build and modify an <code>ast</code> and then optionally write it out as python byte code for execution later without overhead.</p> <p>I have been hacking around with the <a href="http://docs.python.org/dev/py3k/library/ast.html" rel="nofollow">ast docs</a> for <code>python3.0</code> and <code>python2.6</code>, but I can't seem to find any good sources on best practices for this type of code.</p> <h2>Question</h2> <p>What are some best practices and guidelines for modifying abstract syntax trees in python?</p> <h2>[edit]</h2> <p><a href="http://stackoverflow.com/users/57757/unknown">Unknown</a> states that <a href="http://code.google.com/p/byteplay/" rel="nofollow">byteplay</a> is a good example of such a library.</p> <p>Also, <a href="http://stackoverflow.com/users/103377/benford">benford</a> cites <a href="http://www.aminus.net/geniusql" rel="nofollow">GeniuSQL</a> which uses abstract syntax trees to transform python code to SQL.</p>
8
2009-05-26T18:02:13Z
912,140
<p>Other than the manual and the source code, you are on your own. This subject and python bytecode are very undocumented.</p> <p>Alternatively you could try using this python bytecode library which I have heard good thing about but haven't tried it yet:</p> <p><a href="http://code.google.com/p/byteplay/" rel="nofollow">http://code.google.com/p/byteplay/</a></p>
4
2009-05-26T18:55:35Z
[ "python", "abstract-syntax-tree" ]
Python Best Practices: Abstract Syntax Trees
911,930
<h2>Modifying Abstract Syntax Trees</h2> <p>I would like to be able to build and modify an <code>ast</code> and then optionally write it out as python byte code for execution later without overhead.</p> <p>I have been hacking around with the <a href="http://docs.python.org/dev/py3k/library/ast.html" rel="nofollow">ast docs</a> for <code>python3.0</code> and <code>python2.6</code>, but I can't seem to find any good sources on best practices for this type of code.</p> <h2>Question</h2> <p>What are some best practices and guidelines for modifying abstract syntax trees in python?</p> <h2>[edit]</h2> <p><a href="http://stackoverflow.com/users/57757/unknown">Unknown</a> states that <a href="http://code.google.com/p/byteplay/" rel="nofollow">byteplay</a> is a good example of such a library.</p> <p>Also, <a href="http://stackoverflow.com/users/103377/benford">benford</a> cites <a href="http://www.aminus.net/geniusql" rel="nofollow">GeniuSQL</a> which uses abstract syntax trees to transform python code to SQL.</p>
8
2009-05-26T18:02:13Z
916,597
<p>I think geniusql is doing something along those lines to translate an ast into sql... There was a talk on it but I can't find it - and I'm not allowed to link anyway :-(</p>
2
2009-05-27T16:05:56Z
[ "python", "abstract-syntax-tree" ]
How to find all child modules in Python?
912,025
<p>While it is fairly trivial in Python to import a "child" module into another module and list its attributes, it becomes slightly more difficult when you want to import <em>all</em> child modules.</p> <p>I'm building a library of tools for an existing 3D application. Each tool has its own menu item and sub menus. I'd like the tool to be responsible for creating its own menus as many of them change based on context and templates. I'd like my base module to be able to find all child modules and check for a <code>create_menu()</code> function and call it if it finds it.</p> <p>What is the easiest way to discover all child modules?</p>
12
2009-05-26T18:25:15Z
912,061
<p>using <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow">dir()</a> and <a href="http://docs.python.org/library/imp.html" rel="nofollow">imp module</a></p>
0
2009-05-26T18:34:05Z
[ "python", "module", "package", "python-import" ]
How to find all child modules in Python?
912,025
<p>While it is fairly trivial in Python to import a "child" module into another module and list its attributes, it becomes slightly more difficult when you want to import <em>all</em> child modules.</p> <p>I'm building a library of tools for an existing 3D application. Each tool has its own menu item and sub menus. I'd like the tool to be responsible for creating its own menus as many of them change based on context and templates. I'd like my base module to be able to find all child modules and check for a <code>create_menu()</code> function and call it if it finds it.</p> <p>What is the easiest way to discover all child modules?</p>
12
2009-05-26T18:25:15Z
912,067
<p>When I was a kind and just beginning programming in Python I've written this for my modular IRC bot:</p> <pre><code> # Load plugins _plugins = [] def ifName(name): try: return re.match('([^_.].+)\.[^.]+', a).group(1) except: return None def isValidPlugin(obj): from common.base import PluginBase try: if obj.__base__ == PluginBase: return True else: return False except: return False plugin_names = set(ifilter(lambda a: a!=None, [ifName(a) for a in os.listdir(os.path.join(os.getcwd(), 'plugins'))])) for plugin_name in plugin_names: try: plugin = __import__('plugins.'+plugin_name, fromlist=['plugins']) valid_plugins = filter(lambda a: isValidPlugin(a), [plugin.__getattribute__(a) for a in dir(plugin)]) _plugins.extend(valid_plugins) except Exception, e: logger.exception('Error loading plugin %s', plugin_name) # Run plugins _plugins = [klass() for klass in _plugins] </code></pre> <p>It's not secure or "right" way, but maybe it we'll be useful nevertheless. It's <strong>very</strong> old code so please don't beat me.</p>
1
2009-05-26T18:37:09Z
[ "python", "module", "package", "python-import" ]
How to find all child modules in Python?
912,025
<p>While it is fairly trivial in Python to import a "child" module into another module and list its attributes, it becomes slightly more difficult when you want to import <em>all</em> child modules.</p> <p>I'm building a library of tools for an existing 3D application. Each tool has its own menu item and sub menus. I'd like the tool to be responsible for creating its own menus as many of them change based on context and templates. I'd like my base module to be able to find all child modules and check for a <code>create_menu()</code> function and call it if it finds it.</p> <p>What is the easiest way to discover all child modules?</p>
12
2009-05-26T18:25:15Z
912,094
<p>You can try <code>glob</code>bing the directory:</p> <pre><code>import os import glob modules = glob.glob(os.path.join('/some/path/to/modules', '*.py')) </code></pre> <p>Then you can try importing them:</p> <pre><code>checked_modules for module in modules: try: __import__(module, globals(), locals()) # returns module object except ImportError: pass else: checked_modules.append(module) </code></pre>
-1
2009-05-26T18:41:25Z
[ "python", "module", "package", "python-import" ]
How to find all child modules in Python?
912,025
<p>While it is fairly trivial in Python to import a "child" module into another module and list its attributes, it becomes slightly more difficult when you want to import <em>all</em> child modules.</p> <p>I'm building a library of tools for an existing 3D application. Each tool has its own menu item and sub menus. I'd like the tool to be responsible for creating its own menus as many of them change based on context and templates. I'd like my base module to be able to find all child modules and check for a <code>create_menu()</code> function and call it if it finds it.</p> <p>What is the easiest way to discover all child modules?</p>
12
2009-05-26T18:25:15Z
7,320,937
<p>I think the best way to do this sort of plugin thing is using <a href="http://pythonhosted.org/setuptools/setuptools.html#dynamic-discovery-of-services-and-plugins" rel="nofollow"><code>entry_points</code></a> and the <a href="http://pythonhosted.org/setuptools/pkg_resources.html#convenience-api" rel="nofollow">API for querying them</a>.</p>
2
2011-09-06T13:44:00Z
[ "python", "module", "package", "python-import" ]
How to find all child modules in Python?
912,025
<p>While it is fairly trivial in Python to import a "child" module into another module and list its attributes, it becomes slightly more difficult when you want to import <em>all</em> child modules.</p> <p>I'm building a library of tools for an existing 3D application. Each tool has its own menu item and sub menus. I'd like the tool to be responsible for creating its own menus as many of them change based on context and templates. I'd like my base module to be able to find all child modules and check for a <code>create_menu()</code> function and call it if it finds it.</p> <p>What is the easiest way to discover all child modules?</p>
12
2009-05-26T18:25:15Z
7,338,242
<p>The solution above traversing the filesystem for finding submodules is ok as long as you implement every plugin as a filesystem based module.</p> <p>A more flexible way would be an explicit plugin list in your main module, and have every plugin (whether a module created by file, dynamically, or even instance of a class) adding itself to that list explicitly. Maybe via a registerPlugin function.</p> <p>Remember: "explicit is better than implicit" is part of the zen of python.</p>
1
2011-09-07T17:48:02Z
[ "python", "module", "package", "python-import" ]
Class attributes with a "calculated" name
912,412
<p>When defining class attributes through "calculated" names, as in:</p> <pre><code>class C(object): for name in (....): exec("%s = ..." % (name,...)) </code></pre> <p>is there a different way of handling the numerous attribute definitions than by using an exec? getattr(C, name) does not work because C is not defined, during class construction...</p>
3
2009-05-26T19:57:28Z
912,428
<p>How about:</p> <pre><code>class C(object): blah blah for name in (...): setattr(C, name, "....") </code></pre> <p>That is, do the attribute setting after the definition.</p>
11
2009-05-26T20:03:41Z
[ "python", "exec", "class-attributes" ]
Class attributes with a "calculated" name
912,412
<p>When defining class attributes through "calculated" names, as in:</p> <pre><code>class C(object): for name in (....): exec("%s = ..." % (name,...)) </code></pre> <p>is there a different way of handling the numerous attribute definitions than by using an exec? getattr(C, name) does not work because C is not defined, during class construction...</p>
3
2009-05-26T19:57:28Z
912,739
<p>What about using metaclasses for this purpose?</p> <p>Check out <a href="http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python">Question 100003 : What is a metaclass in Python?</a>.</p>
0
2009-05-26T20:59:58Z
[ "python", "exec", "class-attributes" ]
Class attributes with a "calculated" name
912,412
<p>When defining class attributes through "calculated" names, as in:</p> <pre><code>class C(object): for name in (....): exec("%s = ..." % (name,...)) </code></pre> <p>is there a different way of handling the numerous attribute definitions than by using an exec? getattr(C, name) does not work because C is not defined, during class construction...</p>
3
2009-05-26T19:57:28Z
912,790
<pre><code>class C (object): pass c = C() c.__dict__['foo'] = 42 c.foo # returns 42 </code></pre>
3
2009-05-26T21:13:02Z
[ "python", "exec", "class-attributes" ]
Class attributes with a "calculated" name
912,412
<p>When defining class attributes through "calculated" names, as in:</p> <pre><code>class C(object): for name in (....): exec("%s = ..." % (name,...)) </code></pre> <p>is there a different way of handling the numerous attribute definitions than by using an exec? getattr(C, name) does not work because C is not defined, during class construction...</p>
3
2009-05-26T19:57:28Z
914,245
<p>If your entire class is "calculated", then may I suggest the <code>type</code> callable. This is especially useful if your original container was a dict:</p> <pre><code>d = dict(('member-%d' % k, k*100) for k in range(10)) C = type('C', (), d) </code></pre> <p>This would give you the same results as</p> <pre><code>class C(object): member-0 = 0 member-1 = 100 ... </code></pre> <p>If your needs are really complex, consider metaclasses. (In fact, <code>type</code> <em>is</em> a metaclass =)</p>
2
2009-05-27T06:28:22Z
[ "python", "exec", "class-attributes" ]
How do I pass lots of variables to and from a function in Python?
912,526
<p>I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the variable (string, float, int), the prompt, and the variable's current value. You then place all of these lists in one big list, and my utility creates a neatly formated wxPython panel with prompts and the current values which can be edited.</p> <p>When I started, I only had a few variables, so I would write out each variable.</p> <pre><code>s='this is a string'; i=1; f=3.14 my_list=[ ['s','your string here',s], ['i','your int here',i], ['f','your float here'],] input_panel = Input(my_list) # the rest of the window is created, the input_panel is added to the window, the user is # allowed to make choices, and control returns when the user hits the calculate button s,i,f = input_panel.results() # the .results() function returns the values in a list </code></pre> <p>Now I want to use this routine for a lot of variables (10-30), and this approach is breaking down. I can create the input list to the function over multiple lines using the list.append() statements. When the code returns from the function, though, I get this huge list that needs to be unpacked into the right variables. This is difficult to manage, and it looks like it will be easy to get the input list and output list out of sync. And worse than that, it looks kludgy.</p> <p>What is the best way to pass lots of variables to a function in Python with extra information so that they can be edited, and then get the variables back so that I can use them in the rest of the program? </p> <p>If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function. I would only need to build the input list over multiple lines, and there wouldn't be any possiblity of the input list getting out of sync with the output list. But Python doesn't allow this.</p> <p>Should I break the big lists into smaller lists that then get combined into big lists for passing into and out of the functions? Or does this just add more places to make errors?</p>
3
2009-05-26T20:20:05Z
912,558
<p>The simplest thing to do would be to create a class. Instead of dealing with a list of variables, the class will have attributes. Then you just use a single instance of the class.</p>
15
2009-05-26T20:25:40Z
[ "python", "pass-by-reference", "pass-by-value" ]
How do I pass lots of variables to and from a function in Python?
912,526
<p>I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the variable (string, float, int), the prompt, and the variable's current value. You then place all of these lists in one big list, and my utility creates a neatly formated wxPython panel with prompts and the current values which can be edited.</p> <p>When I started, I only had a few variables, so I would write out each variable.</p> <pre><code>s='this is a string'; i=1; f=3.14 my_list=[ ['s','your string here',s], ['i','your int here',i], ['f','your float here'],] input_panel = Input(my_list) # the rest of the window is created, the input_panel is added to the window, the user is # allowed to make choices, and control returns when the user hits the calculate button s,i,f = input_panel.results() # the .results() function returns the values in a list </code></pre> <p>Now I want to use this routine for a lot of variables (10-30), and this approach is breaking down. I can create the input list to the function over multiple lines using the list.append() statements. When the code returns from the function, though, I get this huge list that needs to be unpacked into the right variables. This is difficult to manage, and it looks like it will be easy to get the input list and output list out of sync. And worse than that, it looks kludgy.</p> <p>What is the best way to pass lots of variables to a function in Python with extra information so that they can be edited, and then get the variables back so that I can use them in the rest of the program? </p> <p>If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function. I would only need to build the input list over multiple lines, and there wouldn't be any possiblity of the input list getting out of sync with the output list. But Python doesn't allow this.</p> <p>Should I break the big lists into smaller lists that then get combined into big lists for passing into and out of the functions? Or does this just add more places to make errors?</p>
3
2009-05-26T20:20:05Z
912,561
<p>if you have a finite set of these cases, you could write specific wrapper functions for each one. Each wrapper would do the work of building and unpacking lists taht are passed to the internal function.</p>
0
2009-05-26T20:26:20Z
[ "python", "pass-by-reference", "pass-by-value" ]
How do I pass lots of variables to and from a function in Python?
912,526
<p>I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the variable (string, float, int), the prompt, and the variable's current value. You then place all of these lists in one big list, and my utility creates a neatly formated wxPython panel with prompts and the current values which can be edited.</p> <p>When I started, I only had a few variables, so I would write out each variable.</p> <pre><code>s='this is a string'; i=1; f=3.14 my_list=[ ['s','your string here',s], ['i','your int here',i], ['f','your float here'],] input_panel = Input(my_list) # the rest of the window is created, the input_panel is added to the window, the user is # allowed to make choices, and control returns when the user hits the calculate button s,i,f = input_panel.results() # the .results() function returns the values in a list </code></pre> <p>Now I want to use this routine for a lot of variables (10-30), and this approach is breaking down. I can create the input list to the function over multiple lines using the list.append() statements. When the code returns from the function, though, I get this huge list that needs to be unpacked into the right variables. This is difficult to manage, and it looks like it will be easy to get the input list and output list out of sync. And worse than that, it looks kludgy.</p> <p>What is the best way to pass lots of variables to a function in Python with extra information so that they can be edited, and then get the variables back so that I can use them in the rest of the program? </p> <p>If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function. I would only need to build the input list over multiple lines, and there wouldn't be any possiblity of the input list getting out of sync with the output list. But Python doesn't allow this.</p> <p>Should I break the big lists into smaller lists that then get combined into big lists for passing into and out of the functions? Or does this just add more places to make errors?</p>
3
2009-05-26T20:20:05Z
912,571
<blockquote> <p>If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function.</p> </blockquote> <p>You can obtain much the same effect as "pass by reference" by passing a <code>dict</code> (or for syntactic convenience a <code>Bunch</code>, see <a href="http://code.activestate.com/recipes/52308/" rel="nofollow">http://code.activestate.com/recipes/52308/</a>).</p>
1
2009-05-26T20:27:47Z
[ "python", "pass-by-reference", "pass-by-value" ]
How do I pass lots of variables to and from a function in Python?
912,526
<p>I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the variable (string, float, int), the prompt, and the variable's current value. You then place all of these lists in one big list, and my utility creates a neatly formated wxPython panel with prompts and the current values which can be edited.</p> <p>When I started, I only had a few variables, so I would write out each variable.</p> <pre><code>s='this is a string'; i=1; f=3.14 my_list=[ ['s','your string here',s], ['i','your int here',i], ['f','your float here'],] input_panel = Input(my_list) # the rest of the window is created, the input_panel is added to the window, the user is # allowed to make choices, and control returns when the user hits the calculate button s,i,f = input_panel.results() # the .results() function returns the values in a list </code></pre> <p>Now I want to use this routine for a lot of variables (10-30), and this approach is breaking down. I can create the input list to the function over multiple lines using the list.append() statements. When the code returns from the function, though, I get this huge list that needs to be unpacked into the right variables. This is difficult to manage, and it looks like it will be easy to get the input list and output list out of sync. And worse than that, it looks kludgy.</p> <p>What is the best way to pass lots of variables to a function in Python with extra information so that they can be edited, and then get the variables back so that I can use them in the rest of the program? </p> <p>If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function. I would only need to build the input list over multiple lines, and there wouldn't be any possiblity of the input list getting out of sync with the output list. But Python doesn't allow this.</p> <p>Should I break the big lists into smaller lists that then get combined into big lists for passing into and out of the functions? Or does this just add more places to make errors?</p>
3
2009-05-26T20:20:05Z
912,578
<p>There are two decent options that come to mind.</p> <p>The first is to use a dictionary to gather all the variables in one place:</p> <pre><code>d = {} d['var1'] = [1,2,3] d['var2'] = 'asdf' foo(d) </code></pre> <p>The second is to use a class to bundle all the arguments. This could be something as simple as:</p> <pre><code>class Foo(object): pass f = Foo() f.var1 = [1,2,3] f.var2 = 'asdf' foo(f) </code></pre> <p>In this case I would prefer the class over the dictionary, simply because you could eventually provide a definition for the class to make its use clearer or to provide methods that handle some of the packing and unpacking work. </p>
9
2009-05-26T20:29:08Z
[ "python", "pass-by-reference", "pass-by-value" ]
How do I pass lots of variables to and from a function in Python?
912,526
<p>I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the variable (string, float, int), the prompt, and the variable's current value. You then place all of these lists in one big list, and my utility creates a neatly formated wxPython panel with prompts and the current values which can be edited.</p> <p>When I started, I only had a few variables, so I would write out each variable.</p> <pre><code>s='this is a string'; i=1; f=3.14 my_list=[ ['s','your string here',s], ['i','your int here',i], ['f','your float here'],] input_panel = Input(my_list) # the rest of the window is created, the input_panel is added to the window, the user is # allowed to make choices, and control returns when the user hits the calculate button s,i,f = input_panel.results() # the .results() function returns the values in a list </code></pre> <p>Now I want to use this routine for a lot of variables (10-30), and this approach is breaking down. I can create the input list to the function over multiple lines using the list.append() statements. When the code returns from the function, though, I get this huge list that needs to be unpacked into the right variables. This is difficult to manage, and it looks like it will be easy to get the input list and output list out of sync. And worse than that, it looks kludgy.</p> <p>What is the best way to pass lots of variables to a function in Python with extra information so that they can be edited, and then get the variables back so that I can use them in the rest of the program? </p> <p>If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function. I would only need to build the input list over multiple lines, and there wouldn't be any possiblity of the input list getting out of sync with the output list. But Python doesn't allow this.</p> <p>Should I break the big lists into smaller lists that then get combined into big lists for passing into and out of the functions? Or does this just add more places to make errors?</p>
3
2009-05-26T20:20:05Z
912,582
<p>To me, the ideal solution is to use a class like this:</p> <pre><code>&gt;&gt;&gt; class Vars(object): ... def __init__(self, **argd): ... self.__dict__.update(argd) ... &gt;&gt;&gt; x = Vars(x=1, y=2) &gt;&gt;&gt; x.x 1 &gt;&gt;&gt; x.y 2 </code></pre> <p>You can also build a dictionary and pass it like this:</p> <pre><code>&gt;&gt;&gt; some_dict = {'x' : 1, 'y' : 2} &gt;&gt;&gt; #the two stars below mean to pass the dict as keyword arguments &gt;&gt;&gt; x = Vars(**some_dict) &gt;&gt;&gt; x.x 1 &gt;&gt;&gt; x.y 2 </code></pre> <p>You may then get data or alter it as need be when passing it to a function:</p> <pre><code>&gt;&gt;&gt; def foo(some_vars): ... some_vars.z = 3 #note that we're creating the member z ... &gt;&gt;&gt; foo(x) &gt;&gt;&gt; x.z 3 </code></pre>
2
2009-05-26T20:29:25Z
[ "python", "pass-by-reference", "pass-by-value" ]
How do I pass lots of variables to and from a function in Python?
912,526
<p>I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the variable (string, float, int), the prompt, and the variable's current value. You then place all of these lists in one big list, and my utility creates a neatly formated wxPython panel with prompts and the current values which can be edited.</p> <p>When I started, I only had a few variables, so I would write out each variable.</p> <pre><code>s='this is a string'; i=1; f=3.14 my_list=[ ['s','your string here',s], ['i','your int here',i], ['f','your float here'],] input_panel = Input(my_list) # the rest of the window is created, the input_panel is added to the window, the user is # allowed to make choices, and control returns when the user hits the calculate button s,i,f = input_panel.results() # the .results() function returns the values in a list </code></pre> <p>Now I want to use this routine for a lot of variables (10-30), and this approach is breaking down. I can create the input list to the function over multiple lines using the list.append() statements. When the code returns from the function, though, I get this huge list that needs to be unpacked into the right variables. This is difficult to manage, and it looks like it will be easy to get the input list and output list out of sync. And worse than that, it looks kludgy.</p> <p>What is the best way to pass lots of variables to a function in Python with extra information so that they can be edited, and then get the variables back so that I can use them in the rest of the program? </p> <p>If I could pass the variables by reference into the function, then users could change them or not, and I would use the values once the program returned from the function. I would only need to build the input list over multiple lines, and there wouldn't be any possiblity of the input list getting out of sync with the output list. But Python doesn't allow this.</p> <p>Should I break the big lists into smaller lists that then get combined into big lists for passing into and out of the functions? Or does this just add more places to make errors?</p>
3
2009-05-26T20:20:05Z
913,540
<ol> <li>I would recommend using a dictionary or a class to accumulate all details about your variables <ul> <li>value</li> <li>prompt text</li> </ul></li> <li>A list to store the order in which you want them to be displayed</li> <li>Then use good old iteration to prepare input and collect output</li> </ol> <p>This way you will only be modifying a small manageable section of the code time and again. Of course you should encapsulate all this into a class if your comfortable working with classes.</p> <pre><code>"""Store all variables """ vars = {} """Store the order of display """ order = [] """Define a function that will store details and order of the variable definitions """ def makeVar(parent, order, name, value, prompt): parent[name] = dict(zip(('value', 'prompt'), (value, prompt))) order.append(name) """Create your variable definitions in order """ makeVar(vars, order, 's', 'this is a string', 'your string here') makeVar(vars, order, 'i', 1, 'your int here') makeVar(vars, order, 'f', 3.14, 'your float here') """Use a list comprehension to prepare your input """ my_list = [[name, vars[name]['prompt'], vars[name]['value']] for name in order] input_panel = Input(my_list) out_list = input_panel.results(); """Collect your output """ for i in range(0, len(order)): vars[order[i]]['value'] = out_list[i]; </code></pre>
0
2009-05-27T01:18:09Z
[ "python", "pass-by-reference", "pass-by-value" ]
Using subprocess to run Python script on Windows
912,830
<p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p> <p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p> <pre><code>Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functional.py", line 49, in tvnamerifiy stdout = PIPE File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 193] %1 is not a valid Win32 application </code></pre> <p><hr /></p> <blockquote> <p><em><a href="http://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p> </blockquote> <p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p> <p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p> <pre><code>import sys import tvnamer sys.argv.append("-b", "/the/folder") try: tvnamer.main() except BaseException, errormsg: print type(errormsg) </code></pre> <p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p> <p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p> <p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb%5Fapi/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test%5Ffunctional.py">here</a></p>
31
2009-05-26T21:22:12Z
912,847
<p>Just found <code>sys.executable</code> - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)</p> <pre><code>import sys import subprocess theproc = subprocess.Popen([sys.executable, "myscript.py"]) theproc.communicate() </code></pre>
45
2009-05-26T21:26:10Z
[ "python", "windows", "subprocess" ]
Using subprocess to run Python script on Windows
912,830
<p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p> <p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p> <pre><code>Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functional.py", line 49, in tvnamerifiy stdout = PIPE File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 193] %1 is not a valid Win32 application </code></pre> <p><hr /></p> <blockquote> <p><em><a href="http://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p> </blockquote> <p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p> <p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p> <pre><code>import sys import tvnamer sys.argv.append("-b", "/the/folder") try: tvnamer.main() except BaseException, errormsg: print type(errormsg) </code></pre> <p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p> <p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p> <p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb%5Fapi/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test%5Ffunctional.py">here</a></p>
31
2009-05-26T21:22:12Z
912,851
<p>When you are running a python script on windows in subprocess you should use python in front of the script name. Try:</p> <pre><code>process = subprocess.Popen("python /the/script.py") </code></pre>
1
2009-05-26T21:26:41Z
[ "python", "windows", "subprocess" ]
Using subprocess to run Python script on Windows
912,830
<p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p> <p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p> <pre><code>Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functional.py", line 49, in tvnamerifiy stdout = PIPE File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 193] %1 is not a valid Win32 application </code></pre> <p><hr /></p> <blockquote> <p><em><a href="http://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p> </blockquote> <p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p> <p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p> <pre><code>import sys import tvnamer sys.argv.append("-b", "/the/folder") try: tvnamer.main() except BaseException, errormsg: print type(errormsg) </code></pre> <p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p> <p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p> <p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb%5Fapi/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test%5Ffunctional.py">here</a></p>
31
2009-05-26T21:22:12Z
912,862
<p>It looks like windows tries to run the script using its own EXE framework rather than call it like </p> <pre><code>python /the/script.py </code></pre> <p>Try,</p> <pre><code>subprocess.Popen(["python", "/the/script.py"]) </code></pre> <p>Edit: "python" would need to be on your path.</p>
4
2009-05-26T21:29:03Z
[ "python", "windows", "subprocess" ]
Using subprocess to run Python script on Windows
912,830
<p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p> <p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p> <pre><code>Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functional.py", line 49, in tvnamerifiy stdout = PIPE File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 193] %1 is not a valid Win32 application </code></pre> <p><hr /></p> <blockquote> <p><em><a href="http://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p> </blockquote> <p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p> <p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p> <pre><code>import sys import tvnamer sys.argv.append("-b", "/the/folder") try: tvnamer.main() except BaseException, errormsg: print type(errormsg) </code></pre> <p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p> <p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p> <p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb%5Fapi/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test%5Ffunctional.py">here</a></p>
31
2009-05-26T21:22:12Z
914,522
<p>You are using a pathname separator which is platform dependent. Windows uses "\" and Unix uses "/".</p>
2
2009-05-27T08:08:52Z
[ "python", "windows", "subprocess" ]
Using subprocess to run Python script on Windows
912,830
<p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p> <p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p> <pre><code>Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functional.py", line 49, in tvnamerifiy stdout = PIPE File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 193] %1 is not a valid Win32 application </code></pre> <p><hr /></p> <blockquote> <p><em><a href="http://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p> </blockquote> <p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p> <p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p> <pre><code>import sys import tvnamer sys.argv.append("-b", "/the/folder") try: tvnamer.main() except BaseException, errormsg: print type(errormsg) </code></pre> <p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p> <p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p> <p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb%5Fapi/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test%5Ffunctional.py">here</a></p>
31
2009-05-26T21:22:12Z
1,036,086
<p>How about this:</p> <pre><code>import sys import subprocess theproc = subprocess.Popen("myscript.py", shell = True) theproc.communicate() # ^^^^^^^^^^^^ </code></pre> <p>This tells <code>subprocess</code> to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.</p> <p>Additionally, this will search the PATH for "myscript.py" - which could be desirable.</p>
15
2009-06-24T01:48:17Z
[ "python", "windows", "subprocess" ]
Using subprocess to run Python script on Windows
912,830
<p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p> <p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p> <pre><code>Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functional.py", line 49, in tvnamerifiy stdout = PIPE File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 193] %1 is not a valid Win32 application </code></pre> <p><hr /></p> <blockquote> <p><em><a href="http://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p> </blockquote> <p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p> <p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p> <pre><code>import sys import tvnamer sys.argv.append("-b", "/the/folder") try: tvnamer.main() except BaseException, errormsg: print type(errormsg) </code></pre> <p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p> <p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p> <p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb%5Fapi/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test%5Ffunctional.py">here</a></p>
31
2009-05-26T21:22:12Z
6,329,130
<p>Yes <code>subprocess.Popen(cmd, ..., shell=True)</code> works like a charm. On Windows the <code>.py</code> file extension is recognized, so Python is invoked to process it (on *NIX just the usual shebang). The path environment controls whether things are seen. So the first arg to <code>Popen</code> is <em>just the name of the script</em>.</p> <pre><code>subprocess.Popen(['myscript.py', 'arg1', ...], ..., shell=True) </code></pre>
5
2011-06-13T10:15:57Z
[ "python", "windows", "subprocess" ]
Using subprocess to run Python script on Windows
912,830
<p>Is there a simple way to run a Python script on Windows/Linux/OS X?</p> <p>On the latter two, <code>subprocess.Popen("/the/script.py")</code> works, but on Windows I get the following error:</p> <pre><code>Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functional.py", line 49, in tvnamerifiy stdout = PIPE File "C:\Python26\lib\subprocess.py", line 595, in __init__ errread, errwrite) File "C:\Python26\lib\subprocess.py", line 804, in _execute_child startupinfo) WindowsError: [Error 193] %1 is not a valid Win32 application </code></pre> <p><hr /></p> <blockquote> <p><em><a href="http://stackoverflow.com/users/24718/monkut">monkut's</a> comment</em>: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?</p> </blockquote> <p>I was writing a quick script to test the overall functionality of a Python-command-line tool (to test it on various platforms). Basically it had to create a bunch of files in a temp folder, run the script on this and check the files were renamed correctly.</p> <p>I could have imported the script and called the function, but since it relies on <code>sys.argv</code> and uses <code>sys.exit()</code>, I would have needed to do something like..</p> <pre><code>import sys import tvnamer sys.argv.append("-b", "/the/folder") try: tvnamer.main() except BaseException, errormsg: print type(errormsg) </code></pre> <p>Also, I wanted to capture the stdout and stderr for debugging incase something went wrong.</p> <p>Of course a better way would be to write the script in more unit-testable way, but the script is basically "done" and I'm doing a final batch of testing before doing a "1.0" release (after which I'm going to do a rewrite/restructure, which will be far tidier and more testable)</p> <p>Basically, it was much easier to simply run the script as a process, after finding the <code>sys.executable</code> variable. I would have written it as a shell-script, but that wouldn't have been cross-platform. The final script can be found <a href="http://github.com/dbr/tvdb%5Fapi/blob/c8d7b356cd1a7bb2ab22b510ea74e03a7d27fad6/tests/test%5Ffunctional.py">here</a></p>
31
2009-05-26T21:22:12Z
24,752,537
<p>For example, to execute following with command prompt or BATCH file we can use this: </p> <pre><code>C:\Python27\python.exe "C:\Program files(x86)\dev_appserver.py" --host 0.0.0.0 --post 8080 "C:\blabla\" </code></pre> <p>Same thing to do with Python, we can do this:</p> <pre><code>subprocess.Popen(['C:/Python27/python.exe', 'C:\\Program files(x86)\\dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:\\blabla'], shell=True) </code></pre> <p>or</p> <pre><code>subprocess.Popen(['C:/Python27/python.exe', 'C:/Program files(x86)/dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:/blabla'], shell=True) </code></pre>
1
2014-07-15T07:40:06Z
[ "python", "windows", "subprocess" ]
Dynamic Finders and Method Missing in Python
913,020
<p>I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this:</p> <ul> <li>Your Person has some fields: name, age and email.</li> <li>Suppose you want to find all the users whose name is "Robot". </li> </ul> <p>The Person class has a method called "find_by_name" that receives the name and returns the result of the query:</p> <pre><code> @classmethod def find_by_name(cls, name): return Person.gql("WHERE name = :1", name).get() </code></pre> <p>Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method_missing that allows me to do it. </p> <p>So far I've seen these 2 blog posts: <a href="http://blog.iffy.us/?p=43">http://blog.iffy.us/?p=43</a> and <a href="http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm">http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm</a> but I'd like to hear what's the "most appropiate" way of doing it.</p>
5
2009-05-26T22:10:42Z
913,109
<pre><code>class Person(object): def __getattr__(self, name): if not name.startswith("find_by"): raise AttributeError(name) field_name = name.split("find_by_",1)[1] return lambda name: Person.gql("WHERE %s = :1" % field_name, name).get() </code></pre>
0
2009-05-26T22:31:23Z
[ "python", "google-app-engine", "web-applications" ]
Dynamic Finders and Method Missing in Python
913,020
<p>I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this:</p> <ul> <li>Your Person has some fields: name, age and email.</li> <li>Suppose you want to find all the users whose name is "Robot". </li> </ul> <p>The Person class has a method called "find_by_name" that receives the name and returns the result of the query:</p> <pre><code> @classmethod def find_by_name(cls, name): return Person.gql("WHERE name = :1", name).get() </code></pre> <p>Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method_missing that allows me to do it. </p> <p>So far I've seen these 2 blog posts: <a href="http://blog.iffy.us/?p=43">http://blog.iffy.us/?p=43</a> and <a href="http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm">http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm</a> but I'd like to hear what's the "most appropiate" way of doing it.</p>
5
2009-05-26T22:10:42Z
913,145
<p>You could use a 'find_by' method and keywords, like Django does:</p> <pre><code>class Person (object): def find_by(self, *kw): qspec = ' AND '.join('%s=%s' % kv for kv in kw.items()) return self.gql('WHERE ' + qspec) person.find_by(name='Robot') person.find_by(name='Robot', age='2') </code></pre> <p>Down this road you may end up designing your own query syntax. Take a look at what Django does...</p>
1
2009-05-26T22:40:52Z
[ "python", "google-app-engine", "web-applications" ]
Dynamic Finders and Method Missing in Python
913,020
<p>I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this:</p> <ul> <li>Your Person has some fields: name, age and email.</li> <li>Suppose you want to find all the users whose name is "Robot". </li> </ul> <p>The Person class has a method called "find_by_name" that receives the name and returns the result of the query:</p> <pre><code> @classmethod def find_by_name(cls, name): return Person.gql("WHERE name = :1", name).get() </code></pre> <p>Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method_missing that allows me to do it. </p> <p>So far I've seen these 2 blog posts: <a href="http://blog.iffy.us/?p=43">http://blog.iffy.us/?p=43</a> and <a href="http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm">http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm</a> but I'd like to hear what's the "most appropiate" way of doing it.</p>
5
2009-05-26T22:10:42Z
913,438
<p>There's really no need to use GQL here - it just complicates matters. Here's a simple implementation:</p> <pre><code>class FindableModel(db.Model): def __getattr__(self, name): if not name.startswith("find_by_"): raise AttributeError(name) field = name[len("find_by_"):] return lambda value: self.all().filter(field, value) </code></pre> <p>Note that it returns a Query object, which you can call .get(), .fetch() etc on; this is more versatile, but if you want you can of course make it just return a single entity.</p>
7
2009-05-27T00:34:53Z
[ "python", "google-app-engine", "web-applications" ]
Dynamic Finders and Method Missing in Python
913,020
<p>I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this:</p> <ul> <li>Your Person has some fields: name, age and email.</li> <li>Suppose you want to find all the users whose name is "Robot". </li> </ul> <p>The Person class has a method called "find_by_name" that receives the name and returns the result of the query:</p> <pre><code> @classmethod def find_by_name(cls, name): return Person.gql("WHERE name = :1", name).get() </code></pre> <p>Instead of having to write a method like that for each attribute, I'd like to have something like Ruby's method_missing that allows me to do it. </p> <p>So far I've seen these 2 blog posts: <a href="http://blog.iffy.us/?p=43">http://blog.iffy.us/?p=43</a> and <a href="http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm">http://www.whatspop.com/blog/2008/08/method-missing-in-python.cfm</a> but I'd like to hear what's the "most appropiate" way of doing it.</p>
5
2009-05-26T22:10:42Z
1,554,403
<p>class Person:</p> <pre><code> name = "" age = 0 salary = 0 def __init__(self, name, age): self.name = name self.age = age </code></pre> <p>def find(clsobj, *args): return Person(name="Jack", age=20)</p> <p>The for loop below inserts @classmethod for all class attributes. This makes "find_by_name", "find_by_age" and "sinf_by_salary" bound methods available.</p> <pre><code>for attr in Person.__dict__.keys(): setattr(Person, 'find_by_'+attr, find) setattr(Person, 'find_by_'+attr, classmethod(find)) </code></pre> <p>print Person.find_by_name("jack").age # will print value 20.</p> <p>I'm not sure if this the right way of doing things. But if you are able to implement a unified "find" for all attributes, then the above script works.</p>
0
2009-10-12T12:50:08Z
[ "python", "google-app-engine", "web-applications" ]
Is it possible to install python 3 and 2.6 on same PC?
913,204
<p>How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet.</p> <p>EDIT:: im on a windows vista 64-bit</p>
3
2009-05-26T23:02:23Z
913,212
<p>I would assume it'd be the same as running two versions of 2.x; as long as they're each in their own directory you should be OK.</p>
1
2009-05-26T23:05:02Z
[ "python", "python-3.x" ]
Is it possible to install python 3 and 2.6 on same PC?
913,204
<p>How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet.</p> <p>EDIT:: im on a windows vista 64-bit</p>
3
2009-05-26T23:02:23Z
913,216
<p>If you are on Windows, then just install another version of Python using the installer. It would be installed into another directory.</p> <p>Then if you install other packages using the installer, it would ask you for which python installation to apply. If you use installation from source or easy_install, then just make sure that when you install, you are using the one of the proper version.</p> <p>If you have many packages installed in your current python-3, then just make a zip backup of your current installation just in case.</p>
9
2009-05-26T23:06:24Z
[ "python", "python-3.x" ]
Is it possible to install python 3 and 2.6 on same PC?
913,204
<p>How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet.</p> <p>EDIT:: im on a windows vista 64-bit</p>
3
2009-05-26T23:02:23Z
913,222
<p>You certainly can. On Mac Ports, there's a tool called python_select that lets you switch among python versions; if nothing like it exists on Windows (momentary googling didn't reveal one), it could certainly be written.</p>
1
2009-05-26T23:07:14Z
[ "python", "python-3.x" ]
Is it possible to install python 3 and 2.6 on same PC?
913,204
<p>How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet.</p> <p>EDIT:: im on a windows vista 64-bit</p>
3
2009-05-26T23:02:23Z
913,223
<p>Erm... yes. I just installed Python 3.0 on this computer to test it. You haven't specified your operating system, but I'm running Ubuntu 9.04 and I can explicitly specify the version of Python I want to run by typing <code>python2.5 myscript.py</code> or <code>python3.0 myscript.py</code>, depending on my needs.</p>
3
2009-05-26T23:07:25Z
[ "python", "python-3.x" ]
Is it possible to install python 3 and 2.6 on same PC?
913,204
<p>How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet.</p> <p>EDIT:: im on a windows vista 64-bit</p>
3
2009-05-26T23:02:23Z
913,225
<p>Typically python is installed with a name like <code>python2.6</code>, so you can have more than one. There <em>may</em> be a symlink from <code>python</code> to one of the numbered files. Quite workable.</p>
3
2009-05-26T23:07:40Z
[ "python", "python-3.x" ]
Is it possible to install python 3 and 2.6 on same PC?
913,204
<p>How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet.</p> <p>EDIT:: im on a windows vista 64-bit</p>
3
2009-05-26T23:02:23Z
913,269
<p>Yes, it is possible. </p> <p>I maintain 3 python installations (2.5, 2.6, 3.0). The only issue that could be confusing is figuring out which Python version takes precedence in PATH variable (if any) . To execute a script for a specific version, you would go into the python directory for that version</p> <p>C:\Python25\ , C:\Python26\, C:\Python30\, etc. </p> <p>Drop the file in there, and run "python.exe file.py" from command-line.</p> <p>You could even rename each python.exe to python25.exe python26.exe python30.exe and have each directory in PATH so it would be easy to execute any script on any version.</p>
2
2009-05-26T23:22:37Z
[ "python", "python-3.x" ]
Is it possible to install python 3 and 2.6 on same PC?
913,204
<p>How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet.</p> <p>EDIT:: im on a windows vista 64-bit</p>
3
2009-05-26T23:02:23Z
913,294
<p>You can set up <a href="http://dumbotics.com/2009/05/24/virtual-pythonenvironments/" rel="nofollow">virtual python environments</a> using <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>.</p>
0
2009-05-26T23:32:41Z
[ "python", "python-3.x" ]
mod_wsgi 2.5 on Ubuntu 9.04 with Python 2.6.2 installation
913,232
<p>Has anybody succeeded with mod_wsgi 2.5 on Ubuntu 9.04 with default Python installation (2.6.2)?</p> <p>I got compilation errors:</p> <pre><code>mod_wsgi.c:119:2: error: #error Sorry, mod_wsgi requires at least Python 2.3.0. mod_wsgi.c:123:2: error: #error Sorry, mod_wsgi requires that Python supporting thread. </code></pre> <p><strong>which Python</strong> gives /usr/bin/python and <strong>/usr/bin/python -V</strong> returns Python 2.6.2 so I'm not sure what's wrong with the 1st one, and honestly I don't know how to check options used in compiling default Python on Ubuntu.</p> <p>There are a lot of other errors but those 2 looks most relevant.</p> <p>What else could be possibly wrong??</p>
1
2009-05-26T23:09:29Z
913,251
<p>Perhaps the user that the server is running as does not have /usr/bin on its path, and there is another version of python somewhere else on the path that is &lt; 2.3</p> <p>Try:</p> <pre><code>which -a python </code></pre> <p>to find all of the pythons on your path. Perhaps one of these is what the server is running.</p>
2
2009-05-26T23:15:25Z
[ "python", "compiler-construction", "ubuntu", "mod-wsgi", "wsgi" ]
mod_wsgi 2.5 on Ubuntu 9.04 with Python 2.6.2 installation
913,232
<p>Has anybody succeeded with mod_wsgi 2.5 on Ubuntu 9.04 with default Python installation (2.6.2)?</p> <p>I got compilation errors:</p> <pre><code>mod_wsgi.c:119:2: error: #error Sorry, mod_wsgi requires at least Python 2.3.0. mod_wsgi.c:123:2: error: #error Sorry, mod_wsgi requires that Python supporting thread. </code></pre> <p><strong>which Python</strong> gives /usr/bin/python and <strong>/usr/bin/python -V</strong> returns Python 2.6.2 so I'm not sure what's wrong with the 1st one, and honestly I don't know how to check options used in compiling default Python on Ubuntu.</p> <p>There are a lot of other errors but those 2 looks most relevant.</p> <p>What else could be possibly wrong??</p>
1
2009-05-26T23:09:29Z
913,271
<p>From your errors I see that you're having to compile python extensions. If you haven't already, I suggest you install the python-dev package because it's usually required for compiling python extensions and it's not part of the default installation.</p> <p>Installing the package is as easy as running:</p> <blockquote> <p>sudo apt-get install python-dev</p> </blockquote> <p>from a command line.</p>
5
2009-05-26T23:23:29Z
[ "python", "compiler-construction", "ubuntu", "mod-wsgi", "wsgi" ]
Can't catch exception!
913,396
<p>I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!</p> <p>The class PyMonitor.cc describes the swig interface to the desired class, Monitor. Monitor's constructor throws an exception if it fails to connect. I'd like to handle this exception in PyMonitor, e.g.:</p> <p>PyMonitor.cc:</p> <pre><code>#include "Monitor.h" // ... bool PyMonitor::connect() { try { _monitor = new Monitor(_host, _calibration); } catch (...) { printf("oops!\n"); } } // ... </code></pre> <p>However, the connect() method never catches the exception, I just get a "terminate called after throwing ..." error, and the program aborts.</p> <p>I don't know too much about swig, but it seems to me that this is all fine C++ and the exception should propagate to the connect() method before killing the program.</p> <p>Any thoughts?</p>
4
2009-05-27T00:14:37Z
913,526
<p>I'm not familiar with swig, or with using C++ and Python together, but if this is under a recent version of Microsoft Visual C++, then the <code>Monitor</code> class is probably throwing a C structured exception, rather than a C++ typed exception. C structured exceptions aren't caught by C++ exception handlers, even the <code>catch(...)</code> one.</p> <p>If that's the case, you can use the <code>__try/__except</code> keywords (instead of <code>try/catch</code>), or use the <code>_set_se_translator</code> function to translate the C structured exception into a C++ typed exception.</p> <p>(Older versions of MSVC++ treated C structured exceptions as C++ <code>int</code> types, and <em>are</em> caught by C++ handlers, if I remember correctly.)</p> <p>If this <em>isn't</em> under Microsoft Visual C++, then I'm not sure how this could be happening.</p> <p>EDIT: Since you say that this isn't MSVC, perhaps something else is catching the exception (and terminating the program) before your code gets it, or maybe there's something in your catch block that's throwing another exception? Without more detail to work with, those are the only cases I can think of that would cause those symptoms.</p>
1
2009-05-27T01:07:33Z
[ "c++", "python", "exception", "swig" ]
Can't catch exception!
913,396
<p>I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!</p> <p>The class PyMonitor.cc describes the swig interface to the desired class, Monitor. Monitor's constructor throws an exception if it fails to connect. I'd like to handle this exception in PyMonitor, e.g.:</p> <p>PyMonitor.cc:</p> <pre><code>#include "Monitor.h" // ... bool PyMonitor::connect() { try { _monitor = new Monitor(_host, _calibration); } catch (...) { printf("oops!\n"); } } // ... </code></pre> <p>However, the connect() method never catches the exception, I just get a "terminate called after throwing ..." error, and the program aborts.</p> <p>I don't know too much about swig, but it seems to me that this is all fine C++ and the exception should propagate to the connect() method before killing the program.</p> <p>Any thoughts?</p>
4
2009-05-27T00:14:37Z
919,573
<p>It's possible that a function called directly or indirectly by the Monitor <code>constructor</code> is violating its exception specification and doesn't allow <code>std::bad_exception</code> to be thrown. If you haven't replaced the standard function for trapping this, then it would explain the behaviour that you are seeing.</p> <p>To test this hypothesis you could try defining your own handler:</p> <pre><code>void my_unexpected() { std::cerr &lt;&lt; "Bad things have happened!\n"; std::terminate(); } bool PyMonitor::connect() { std::set_unexpected( my_unexpected ); try { _monitor = new Monitor(_host, _calibration); } catch (...) { printf("oops!\n"); } } </code></pre> <p>If you get the "Bad things have happened!" error message then you have confirmed that this is the case, but unfortunately there may not be a lot that you can do. If you're 'lucky', you may be able to throw an exception from <code>my_unexpected</code> that is allowed by the exception specification of the function that is currently failing, but in any case your unexpected handler is not allowed to terminate normally. It must throw or otherwise terminate.</p> <p>To fix this you really need to get into the called code and either correct it so that the exception specification is not violated, either by fixing the specification itself or by fixing the code so that it doesn't throw the exception that isn't expected.</p> <p>Another possibility is that an exception is being thrown during stack unwinding caused by the original exception being thrown. This also would cause termination of the process. In this case, although you can replace the standard terminate function, you have no option but to abort the program. A terminate handler isn't allowed to throw or return, it must terminate the program.</p>
1
2009-05-28T07:18:07Z
[ "c++", "python", "exception", "swig" ]
Can't catch exception!
913,396
<p>I'm using swig to wrap a class from a C++ library with python. It works overall, but there is an exception that is thrown from within the library and I can't seem to catch it in the swig interface, so it just crashes the python application!</p> <p>The class PyMonitor.cc describes the swig interface to the desired class, Monitor. Monitor's constructor throws an exception if it fails to connect. I'd like to handle this exception in PyMonitor, e.g.:</p> <p>PyMonitor.cc:</p> <pre><code>#include "Monitor.h" // ... bool PyMonitor::connect() { try { _monitor = new Monitor(_host, _calibration); } catch (...) { printf("oops!\n"); } } // ... </code></pre> <p>However, the connect() method never catches the exception, I just get a "terminate called after throwing ..." error, and the program aborts.</p> <p>I don't know too much about swig, but it seems to me that this is all fine C++ and the exception should propagate to the connect() method before killing the program.</p> <p>Any thoughts?</p>
4
2009-05-27T00:14:37Z
7,443,941
<p>You have to forward the exceptions to Python if you want to parse them there. See the <a href="http://www.swig.org/Doc1.3/Customization.html#exception" rel="nofollow">SWIG Documentation</a>. In order to forward exceptions, you only have to add some code in the SWIG interface (.i) file. Basically, this can be anywhere in the .i file.</p> <p>All types of exceptions should be specified here, and SWIG <strong>only</strong> catches the listed exception types (in this case std::runtime_error, std::invalid_argument, std::out_of_range), all other exceptions are caught as unknown exceptions (and are thus forwarded correctly!).</p> <pre><code>// Handle standard exceptions. // NOTE: needs to be before the %import! %include "exception.i" %exception { try { $action } catch (const std::runtime_error&amp; e) { SWIG_exception(SWIG_RuntimeError, e.what()); } catch (const std::invalid_argument&amp; e) { SWIG_exception(SWIG_ValueError, e.what()); } catch (const std::out_of_range&amp; e) { SWIG_exception(SWIG_IndexError, e.what()); } catch (...) { SWIG_exception(SWIG_RuntimeError, "unknown exception"); } } </code></pre>
4
2011-09-16T11:21:28Z
[ "c++", "python", "exception", "swig" ]
Python3.0: tokenize & BytesIO
913,409
<p>When attempting to <code>tokenize</code> a string in python3.0, why do I get a leading <code>'utf-8'</code> before the tokens start?</p> <p>From the <a href="http://docs.python.org/3.0/library/tokenize.html" rel="nofollow">python3 docs</a>, <code>tokenize</code> should now be used as follows:</p> <pre><code>g = tokenize(BytesIO(s.encode('utf-8')).readline) </code></pre> <p>However, when attempting this at the terminal, the following happens:</p> <pre><code>&gt;&gt;&gt; from tokenize import tokenize &gt;&gt;&gt; from io import BytesIO &gt;&gt;&gt; g = tokenize(BytesIO('foo'.encode()).readline) &gt;&gt;&gt; next(g) (57, 'utf-8', (0, 0), (0, 0), '') &gt;&gt;&gt; next(g) (1, 'foo', (1, 0), (1, 3), 'foo') &gt;&gt;&gt; next(g) (0, '', (2, 0), (2, 0), '') &gt;&gt;&gt; next(g) </code></pre> <p>What's with the <code>utf-8</code> token that precedes the others? Is this supposed to happen? If so, then should I just always skip the first token?</p> <h2>[edit]</h2> <p>I have found that token type 57 is <a href="http://docs.python.org/3.0/library/tokenize.html#tokenize.ENCODING" rel="nofollow">tokenize.ENCODING</a>, which can easily be filtered out of the token stream if need be.</p>
1
2009-05-27T00:22:37Z
913,427
<p>That's the coding cookie of the source. You can specify one explicitly:</p> <pre><code># -*- coding: utf-8 -*- do_it() </code></pre> <p>Otherwise Python assumes the default encoding, utf-8 in Python 3.</p>
2
2009-05-27T00:29:10Z
[ "python", "io", "tokenize", "bytesio" ]
Django forms, inheritance and order of form fields
913,589
<p>I'm using Django forms in my website and would like to control the order of the fields.</p> <p>Here's how I define my forms:</p> <pre><code>class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() </code></pre> <p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p> <p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p> <p>So, how can I override this behavior?</p> <p><strong>Edit:</strong></p> <p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p> <p>In short the code would become something like this:</p> <pre><code>class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): def __init__(self,*args,**kwargs): forms.Form.__init__(self,*args,**kwargs) self.fields.insert(0,'name',forms.CharField()) </code></pre> <p>That shut me up :) </p>
53
2009-05-27T01:46:50Z
913,629
<p>See the notes in <a href="http://stackoverflow.com/questions/350799/how-does-django-know-the-order-to-render-form-fields">this SO question</a> on the way Django's internals keep track of field order; the answers include suggestions on how to "reorder" fields to your liking (in the end it boils down to messing with the <code>.fields</code> attribute).</p>
3
2009-05-27T02:05:53Z
[ "python", "django", "django-forms" ]
Django forms, inheritance and order of form fields
913,589
<p>I'm using Django forms in my website and would like to control the order of the fields.</p> <p>Here's how I define my forms:</p> <pre><code>class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() </code></pre> <p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p> <p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p> <p>So, how can I override this behavior?</p> <p><strong>Edit:</strong></p> <p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p> <p>In short the code would become something like this:</p> <pre><code>class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): def __init__(self,*args,**kwargs): forms.Form.__init__(self,*args,**kwargs) self.fields.insert(0,'name',forms.CharField()) </code></pre> <p>That shut me up :) </p>
53
2009-05-27T01:46:50Z
1,133,470
<p>I had this same problem and I found another technique for reordering fields in the <a href="http://code.djangoproject.com/wiki/CookBookNewFormsFieldOrdering">Django CookBook</a>:</p> <pre><code>class EditForm(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class CreateForm(EditForm): name = forms.CharField() def __init__(self, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields.keyOrder = ['name', 'summary', 'description'] </code></pre>
94
2009-07-15T19:29:22Z
[ "python", "django", "django-forms" ]
Django forms, inheritance and order of form fields
913,589
<p>I'm using Django forms in my website and would like to control the order of the fields.</p> <p>Here's how I define my forms:</p> <pre><code>class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() </code></pre> <p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p> <p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p> <p>So, how can I override this behavior?</p> <p><strong>Edit:</strong></p> <p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p> <p>In short the code would become something like this:</p> <pre><code>class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): def __init__(self,*args,**kwargs): forms.Form.__init__(self,*args,**kwargs) self.fields.insert(0,'name',forms.CharField()) </code></pre> <p>That shut me up :) </p>
53
2009-05-27T01:46:50Z
1,703,912
<p>Alternate methods for changing the field order:</p> <p>Pop-and-insert:</p> <pre><code>self.fields.insert(0, 'name', self.fields.pop('name')) </code></pre> <p>Pop-and-append:</p> <pre><code>self.fields['summary'] = self.fields.pop('summary') self.fields['description'] = self.fields.pop('description') </code></pre> <p>Pop-and-append-all:</p> <pre><code>for key in ('name', 'summary', 'description'): self.fields[key] = self.fields.pop(key) </code></pre> <p>Ordered-copy:</p> <pre><code>self.fields = SortedDict( [ (key, self.fields[key]) for key in ('name', 'summary' ,'description') ] ) </code></pre> <p>But Selene's approach from the Django CookBook still feels clearest of all.</p>
2
2009-11-09T21:22:10Z
[ "python", "django", "django-forms" ]