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
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
1,024,852
<p>Yeah, it's pretty easy. Just do the following:</p> <pre><code>dict["key"] = "value" </code></pre>
95
2009-06-21T22:09:09Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
1,165,836
<pre><code>&gt;&gt;&gt; x = {1:2} &gt;&gt;&gt; print x {1: 2} &gt;&gt;&gt; x.update({3:4}) &gt;&gt;&gt; print x {1: 2, 3: 4} </code></pre>
658
2009-07-22T14:48:17Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
8,381,589
<p>I feel like consolidating info about Python dictionaries:</p> <pre><code>### Making a dictionary ### data = {} # OR data = dict() ### Initially adding values ### data = {'a':1,'b':2,'c':3} # OR data = dict(a=1, b=2, c=3) ### Inserting/Updating value ### data['a']=1 # updates if 'a' exists, else adds 'a' # OR data.update({'a':1}) # OR data.update(dict(a=1)) # OR data.update(a=1) ### Merging 2 dictionaries ### data.update(data2) # Where data2 is also a dict. ### Deleting items in dictionary ### del data[key] #Remove specific element in a dictionary data.pop(key) #Removes the key &amp; returns the value data.clear() #Clear entire dictionary </code></pre> <p>Feel free to add more!</p>
268
2011-12-05T06:07:36Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
8,381,704
<pre><code>data = {} data['a'] = 'A' data['b'] = 'B' for key, value in data.iteritems(): print "%s-%s" % (key, value) </code></pre> <p>results in </p> <pre><code>a-A b-B </code></pre>
12
2011-12-05T06:26:24Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
10,339,748
<p>If you want to add a dictionary within a dictionary you can do it this way. </p> <p>Example: Add a new entry to your dictionary &amp; sub dictionary</p> <pre><code>dictionary = {} dictionary["new key"] = "some new entry" # add new dictionary entry dictionary["dictionary_within_a_dictionary"] = {} # this is required by python dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"} print (dictionary) </code></pre> <p><strong>Output:</strong></p> <pre><code>{'new key': 'some value entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}} </code></pre> <p><strong>NOTE:</strong> Python requires that you first add a sub </p> <pre><code>dictionary["dictionary_within_a_dictionary"] = {} </code></pre> <p>before adding entries.</p>
26
2012-04-26T19:04:33Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
15,994,607
<p>The orthodox syntax is <code>d[key] = value</code>, but if your keyboard is missing the square bracket keys you could do:</p> <pre><code>d.__setitem__(key, value) </code></pre> <p>In fact, defining <code>__getitem__</code> and <code>__setitem__</code> methods is how you can make your own class support the square bracket syntax. See <a href="http://www.diveintopython.net/object_oriented_framework/special_class_methods.html">http://www.diveintopython.net/object_oriented_framework/special_class_methods.html</a></p>
24
2013-04-14T00:58:27Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
16,750,088
<p>you can create one</p> <pre><code>class myDict(dict): def __init__(self): self = dict() def add(self, key, value): self[key] = value ## example myd = myDict() myd.add('apples',6) myd.add('bananas',3) print(myd) </code></pre> <p>gives</p> <pre><code>&gt;&gt;&gt; {'apples': 6, 'bananas': 3} </code></pre>
17
2013-05-25T13:33:35Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
18,294,122
<p><a href="http://stackoverflow.com/questions/38987/how-can-i-merge-union-two-python-dictionaries-in-a-single-expression">This popular question</a> addresses <em>functional</em> methods of merging dictionaries <code>a</code> and <code>b</code>.</p> <p>Here are some of the more straightforward methods (tested in Python 3)...</p> <pre><code>c = dict( a, **b ) ## see also http://stackoverflow.com/q/2255878 c = dict( list(a.items()) + list(b.items()) ) c = dict( i for d in [a,b] for i in d.items() ) </code></pre> <p><em>Note: The first method above only works if the keys in <code>b</code> are strings.</em></p> <p><strong>To add or modify a single element</strong>, the <code>b</code> dictionary would contain only that one element...</p> <pre><code>c = dict( a, **{'d':'dog'} ) ## returns a dictionary based on 'a' </code></pre> <p>This is equivalent to...</p> <pre><code>def functional_dict_add( dictionary, key, value ): temp = dictionary.copy() temp[key] = value return temp c = functional_dict_add( a, 'd', 'dog' ) </code></pre>
14
2013-08-17T23:04:12Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
27,208,535
<blockquote> <h1>"Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method."</h1> </blockquote> <p>Yes it is possible, and it does have a method that implements this, but you don't want to use it directly.</p> <p>To demonstrate how and how not to use it, let's create an empty dict with the dict literal, <code>{}</code>:</p> <pre><code>my_dict = {} </code></pre> <h2>Best Practice 1: Subscript notation</h2> <p>To update this dict with a single new key and value, you can use <a href="https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy">the subscript notation (see Mappings here)</a> that provides for item assignment: </p> <pre><code>my_dict['new key'] = 'new value' </code></pre> <p><code>my_dict</code> is now:</p> <pre><code>{'new key': 'new value'} </code></pre> <h2>Best Practice 2: The <code>update</code> method - 2 ways</h2> <p>We can also update the dict with multiple values efficiently as well using <a href="https://docs.python.org/2/library/stdtypes.html#dict.update">the <code>update</code> method</a>. We may be unnecessarily creating an extra <code>dict</code> here, so we hope our <code>dict</code> has already been created and came from or was used for another purpose:</p> <pre><code>my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'}) </code></pre> <p><code>my_dict</code> is now:</p> <pre><code>{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'} </code></pre> <p>Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can't have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary <code>dict</code>:</p> <pre><code>my_dict.update(foo='bar', foo2='baz') </code></pre> <p>and <code>my_dict</code> is now:</p> <pre><code>{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value', 'foo': 'bar', 'foo2': 'baz'} </code></pre> <p>So now we have covered three Pythonic ways of updating a <code>dict</code>. </p> <hr> <h1>Magic method, <code>__setitem__</code>, and why it should be avoided</h1> <p>There's another way of updating a <code>dict</code> that you shouldn't use, which uses the <code>__setitem__</code> method. Here's an example of how one might use the <code>__setitem__</code> method to add a key-value pair to a <code>dict</code>, and a demonstration of the poor performance of using it:</p> <pre><code>&gt;&gt;&gt; d = {} &gt;&gt;&gt; d.__setitem__('foo', 'bar') &gt;&gt;&gt; d {'foo': 'bar'} &gt;&gt;&gt; def f(): ... d = {} ... for i in xrange(100): ... d['foo'] = i ... &gt;&gt;&gt; def g(): ... d = {} ... for i in xrange(100): ... d.__setitem__('foo', i) ... &gt;&gt;&gt; import timeit &gt;&gt;&gt; number = 100 &gt;&gt;&gt; min(timeit.repeat(f, number=number)) 0.0020880699157714844 &gt;&gt;&gt; min(timeit.repeat(g, number=number)) 0.005071878433227539 </code></pre> <p>So we see that using the subscript notation is actually much faster than using <code>__setitem__</code>. Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.</p>
42
2014-11-29T23:57:59Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
30,541,405
<p>This is exactly how I would do it: # fixed data with sapce</p> <pre><code>data = {} data['f'] = 'F' data['c'] = 'C' for key, value in data.iteritems(): print "%s-%s" % (key, value) </code></pre> <p>This works for me. Enjoy!</p>
5
2015-05-30T01:52:47Z
[ "python", "dictionary" ]
Add key to a dictionary in Python?
1,024,847
<p>Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an <code>.add()</code> method.</p>
1,201
2009-06-21T22:07:39Z
37,935,160
<p>we can add new keys to dictionary by this way:</p> <blockquote> <p>Dictionary_Name[New_Key_Name] = New_Key_Value</p> </blockquote> <p>Here is the Example:</p> <pre><code># This is my dictionary my_dict = {'Key1': 'Value1', 'Key2': 'Value2'} # Now add new key in my dictionary my_dict['key3'] = 'Value3' # Print updated dictionary print my_dict </code></pre> <p>Output:</p> <pre><code>{'key3': 'Value3', 'Key2': 'Value2', 'Key1': 'Value1'} </code></pre>
1
2016-06-21T03:39:57Z
[ "python", "dictionary" ]
How do I install GASP for Python 2.6.2 on a Mac
1,024,862
<p>I'm currently trying to learn Python and am going through How to Think Like a Computer Scientist: Learning With Python. I have installed Python 2.6.2 on Mac OSX 10.4.11 and am using the IDLE.</p> <p>At the end of chapter 4 Elkner et al. refer to GASP. However their instructions don't work as when I enter:</p> <pre><code>&gt;&gt;&gt; from gasp import* </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#17&gt;", line 1, in &lt;module&gt; from gasp import* ImportError: No module named gasp </code></pre> <p>I've had a look around on google and can only find outdated methods of installation or pages of gobbledegook. I believe I have to install PyObjC first and haven't been able to accomplish this either.</p> <p>Can anyone please help me out with some plain English instructions? </p>
1
2009-06-21T22:14:07Z
1,024,868
<p>This is actually somewhat of a coincidence; I'm one of the packagers of GASP. On our <a href="http://dev.laptop.org/pub/gasp/downloads/" rel="nofollow">download page</a>, which is linked by our main <a href="https://edge.launchpad.net/gasp-code" rel="nofollow">project page</a>, there are instructions on how to install it on most major platforms. Hadn't considered OSX, however. Will write something up shortly.</p> <p>Essentially, install the <a href="http://python.org" rel="nofollow">Official Python</a> from the PSF. Then add <a href="http://www.macports.org/" rel="nofollow">MacPorts</a> and run</p> <pre><code>sudo ports install py-game </code></pre> <p>Extract the source tarball from the download page linked above to your site-packages directory.</p> <p>There are also some <a href="http://www.theartfulscientist.com/2008/03/16/how-to-install-pyobjc-pygame-and-gasp-on-mac-os-x-for-python-tutorial/" rel="nofollow">alternative instructions</a> I found that might work better, as I have not tested the above.</p>
1
2009-06-21T22:18:10Z
[ "python", "pyobjc", "gasp" ]
How do I install GASP for Python 2.6.2 on a Mac
1,024,862
<p>I'm currently trying to learn Python and am going through How to Think Like a Computer Scientist: Learning With Python. I have installed Python 2.6.2 on Mac OSX 10.4.11 and am using the IDLE.</p> <p>At the end of chapter 4 Elkner et al. refer to GASP. However their instructions don't work as when I enter:</p> <pre><code>&gt;&gt;&gt; from gasp import* </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#17&gt;", line 1, in &lt;module&gt; from gasp import* ImportError: No module named gasp </code></pre> <p>I've had a look around on google and can only find outdated methods of installation or pages of gobbledegook. I believe I have to install PyObjC first and haven't been able to accomplish this either.</p> <p>Can anyone please help me out with some plain English instructions? </p>
1
2009-06-21T22:14:07Z
7,506,693
<p>Well everybody, sorry for the incomplete sentences and overall poor English but I wanted to make this simple to read and understand for someone who is completely inexperienced in any sort of programming, as I am (very first day messing with this stuff, e.g., terminal). This is the result of hours of Googling that was all done in one day. Perhaps someone who is familiar with the commands below (in bold) wouldn’t mind explaining what exactly is taking place. Additionally, this was all done in terminal on a MacBook Pro running Mac OS Lion.</p> <ol> <li>Install macport binary (comes with installer; easy)</li> <li><p><code>sudo port install py-game</code></p> <p>not sure if this is necessary, as it doesn’t appear to cause pygame to be functional for python version 2.7.1 (stock python on lion)</p></li> <li><p><code>sudo port select --set python python 2.7</code></p> <p>I believe this set the default python version to 2.7.2 which I also believe was downloaded during step 2 (therefore why I think this ends up being a necessary step)</p></li> <li>Download setuptools-0.6c11-py2.7.tar</li> <li>In folder gasp-0.3.4, which appears after clicking on the .tar, place <code>setup.py</code> in the<br> gasp folder</li> <li><p><code>sudo python gasp/setup.py install</code></p> <p>make sure your directory is the folder gasp-0.3.4</p></li> <li><p><code>sudo port –v install py27-pygtk</code> </p> <p>takes about an hour for this step to complete</p></li> <li><p><code>sudo port uninstall py-game</code></p> <p>this step is not necessary for gasp to work; I simply didn’t want any unnecessary stuff on my computer that was downloaded during the second step; however, this step put python 2.7.2 on my computer; could install 2.7.2 separately I guess but this way worked for me; a lot of other unnecessary stuff is installed during this step too but I think it’ll remain even after this command, oh well</p></li> </ol>
2
2011-09-21T21:10:48Z
[ "python", "pyobjc", "gasp" ]
How do I install GASP for Python 2.6.2 on a Mac
1,024,862
<p>I'm currently trying to learn Python and am going through How to Think Like a Computer Scientist: Learning With Python. I have installed Python 2.6.2 on Mac OSX 10.4.11 and am using the IDLE.</p> <p>At the end of chapter 4 Elkner et al. refer to GASP. However their instructions don't work as when I enter:</p> <pre><code>&gt;&gt;&gt; from gasp import* </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#17&gt;", line 1, in &lt;module&gt; from gasp import* ImportError: No module named gasp </code></pre> <p>I've had a look around on google and can only find outdated methods of installation or pages of gobbledegook. I believe I have to install PyObjC first and haven't been able to accomplish this either.</p> <p>Can anyone please help me out with some plain English instructions? </p>
1
2009-06-21T22:14:07Z
11,143,564
<p>This is an interesting problem faced by most of the readers using "How to Think Like a Computer Scientist : Learning with Python", when they reach 4th chapter.</p> <p>Now to install GASP, you need to check whether you have python installed on your machine.</p> <p>Assumption: I am going to assume that you are using Mac.</p> <p>Type the following command on your terminal,</p> <pre><code>`$ python -V` </code></pre> <p><em>{If your system has python installed on it, you will get an answer like Python 2.7.1 ( if the version is 2.7.1).}</em></p> <p>Once you have python available on your system, you should install PyObjC.</p> <p>An easy way out is to type on to your terminal prompt,</p> <pre><code>`$ easy_install pyobjc==2.2` </code></pre> <p><em>{this will install the version 2.2}</em></p> <p>Next step is to install pygame package , you can do this in two ways either by downloading the .dmg file or using "homebrew". I prefer the second method.</p> <p>to install pygame package using "brew" you have to install mercurial first. It's a simple procedure, just type in </p> <pre><code>$ brew install mercurial </code></pre> <p>Then type in the following commands,</p> <pre><code>$ brew install sdl sdl_image sdl_mixer sdl_ttf smpeg portmidi $ sudo pip install hg+http://bitbucket.org/pygame/pygame </code></pre> <p>Next step is to install GASP. Download gasp from <a href="https://launchpad.net/gasp-core/+download" rel="nofollow">https://launchpad.net/gasp-core/+download</a></p> <p>Extract the .tar file, you will get a folder structure. Our aim is to copy the folder named "gasp" to the Systems Library folder. To check which folder or version of python is used and to know their correct path type in the following command on terminal.</p> <pre><code>$ python -c 'import sys, pprint; pprint.pprint(sys.path)' </code></pre> <p>generally it will print a path similar to '/Library/Python/2.7/site-packages' , you can notice this either as the last line or the second last line of the output that above commands generate.</p> <p>Copy the gasp folder to the site-packages folder,</p> <pre><code>$ sudo cp -R ~/Desktop/python-gasp-0.1.1/gasp/ /Library/Python/2.7/site-packages/gasp </code></pre> <p>This should copy all the required files to the location specified as the second argument.</p> <p>Now go to terminal and type</p> <pre><code>$ python &gt;&gt;&gt; import gasp </code></pre> <p>If everything goes fine, you will not get any error or any messages.</p> <p>PS: Ensure that in your site-packages directory there are no duplicate copies of pygame/gasp. In case of duplicates, it may throw lots of tantrums. Also, if any of the steps go wrong you may get error "import cairo" some 25th or 26th line on base.py in gasp package.In that event, please clean up your site packages directory by removing pygame and gasp and re-install them, that should solve it.</p> <p>Also while installing mercurial you may get some warning related to Certificates. You can solve them by typing in following commands,</p> <pre><code>$ openssl req -new -x509 -extensions v3_ca -keyout /dev/null -out dummycert.pem -days 3650 $ sudo cp dummycert.pem /etc/hg-dummy-cert.pem $ cd ~ $ nano .hgrc </code></pre> <p>{ This will open up an empty .hgrc file }</p> <p>Type in the following</p> <p>[web]</p> <p>cacerts = /etc/hg-dummy-cert.pem</p> <p>save the above 2 lines by pressing ctrl+ o exit nano by pressing ctrl + x</p> <p>Thats it. This should solve your problems with GASP installation and enjoy the book " How to Think Like a Computer Scientist" it's a wonderful introduction to the world of computing.</p>
0
2012-06-21T17:31:22Z
[ "python", "pyobjc", "gasp" ]
What's the best way to implement web service for ajax autocomplete
1,025,018
<p>I'm implementing a "Google Suggest" like autocomplete feature for tag searching using jQuery's autocomplete. </p> <p>I need to provide a web service to jQuery giving it a list of suggestions based on what the user has typed. I see 2 ways of implementing the web service:</p> <p>1) just store all the tags in a database and search the DB using user input as prefix. This is simple, but I'm concerned about latency.</p> <p>2) Use an in-process trie to store all the tags and search it for matching results. As everything will be in-process, I expect this to have much lower latency. But there are several difficulties: -What's a good way to initialize the trie on process start up? Presumable I'll store the tag data in a DB and retrieve them and turn them into a trie when I frist start up the process. But I'm not sure how. I'm using Python/Django. -When a new tag is created by a user, I need to insert the new tag into the trie. But let's say I have 5 Django processes and hence 5 tries, how do I tell the other 4 tries that they need to insert a new tag too? -How to make sure the trie is threadsafe as my Django processes will be threaded (I'm using mod_wsgi). Or do I not have to worry about threadsafty because of Python's GIL? -Any way I can store the tag's frequency of use within the trie as well? How do I tell when does the tag's string end and when does the frequency start - eg. if I store apple213 into the trie, is it "apple" with frequency 213 or is it "apple2" with frequency 13??</p> <p>Any help on the issues above or any suggestions on a different approach would be really appreciated.</p>
2
2009-06-21T23:31:10Z
1,025,027
<p>I would use the first option. 'KISS' - (Keep It Simple Stupid).</p> <p>For small amounts of data there shouldn't be much latency. We run the same kind of thing for a name search and results appear pretty quickly on a few thousand rows.</p> <p>Hope that helps,</p> <p>Josh</p>
1
2009-06-21T23:36:37Z
[ "python", "ajax", "autocomplete", "trie" ]
What's the best way to implement web service for ajax autocomplete
1,025,018
<p>I'm implementing a "Google Suggest" like autocomplete feature for tag searching using jQuery's autocomplete. </p> <p>I need to provide a web service to jQuery giving it a list of suggestions based on what the user has typed. I see 2 ways of implementing the web service:</p> <p>1) just store all the tags in a database and search the DB using user input as prefix. This is simple, but I'm concerned about latency.</p> <p>2) Use an in-process trie to store all the tags and search it for matching results. As everything will be in-process, I expect this to have much lower latency. But there are several difficulties: -What's a good way to initialize the trie on process start up? Presumable I'll store the tag data in a DB and retrieve them and turn them into a trie when I frist start up the process. But I'm not sure how. I'm using Python/Django. -When a new tag is created by a user, I need to insert the new tag into the trie. But let's say I have 5 Django processes and hence 5 tries, how do I tell the other 4 tries that they need to insert a new tag too? -How to make sure the trie is threadsafe as my Django processes will be threaded (I'm using mod_wsgi). Or do I not have to worry about threadsafty because of Python's GIL? -Any way I can store the tag's frequency of use within the trie as well? How do I tell when does the tag's string end and when does the frequency start - eg. if I store apple213 into the trie, is it "apple" with frequency 213 or is it "apple2" with frequency 13??</p> <p>Any help on the issues above or any suggestions on a different approach would be really appreciated.</p>
2
2009-06-21T23:31:10Z
1,025,355
<p>Don't be concerned about latency before you <em>measure</em> things -- make up a bunch of pseudo-tags, stick them in the DB, and measure latencies for typical queries. Depending on your DB setup, your latency may be just fine and you're spared wasted worries.</p> <p><em>Do</em> always worry about threading, though - the GIL doesn't make race conditions go away (control might switch among threads at any pseudocode instruction boundary, as well as when C code in an underlying extension or builtin is executing). You need first to check the <code>threadsafety</code> attribute of the DB API module you're using (see <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP 249</a>), and then use locking appropriately <em>or</em> spawn a small pool of dedicated threads that perform DB interactions (receiving requests on a Queue.Queue and returning results on another, the normal architecture for sound and easy threading in Python).</p>
4
2009-06-22T03:16:08Z
[ "python", "ajax", "autocomplete", "trie" ]
Django Context Processor Trouble
1,025,025
<p>So I am just starting out on learning Django, and I'm attempting to complete one of the sample applications from the book. I'm getting stuck now on creating DRY URL's. More specifically, I cannot get my context processor to work. I create my context processor as so:</p> <pre><code>from django.conf import settings #from mysite.settings import ROOT_URL def root_url_processor(request): return {'ROOT_URL': settings.ROOT_URL} </code></pre> <p>and I placed this file in my app, specifically, mysite/photogallery/context_processors.py . My settings.py file in the root of my project contains:</p> <pre><code>TEMPLATE_CONTEXT_PROCESSORS = ('mysite.context_processors',) </code></pre> <p>When I try to go to the ROOT_URL that I've also specified in my settings.py, I receive this error:</p> <p>TypeError at /gallery/</p> <p>'module' object is not callable</p> <p>/gallery/ is the ROOT_URL of this particular application. I realize that perhpas this could mean a naming conflict, but I cannot find one. Furthermore, when I comment out the TEMPLATE_CONTEXT_PROCESSORS definition from settings.py, the application actually does load, however my thumbnail images do not appear (probably because my templates do not know about ROOT_URL, right?). Anyone have any ideas as to what the problem could be? </p> <p><strong>EDIT</strong>: Here's some information about my settings.py in case it is of use:</p> <pre><code>ROOT_URLCONF = 'mysite.urls' ROOT_URL = '/gallery/' LOGIN_URL = ROOT_URL + 'login/' MEDIA_URL = ROOT_URL + 'media/' ADMIN_MEDIA_PREFIX = MEDIA_URL + 'admin/' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) TEMPLATE_CONTEXT_PROCESSORS = ('mysite.photogallery.context_processors',) </code></pre> <p><strong>EDIT2</strong>: I'm going to add some information about my url files. Essentially I have a root urls.py, a real_urls.py which is also located at the root, and a urls.py that exists in the application. Basically, root/urls.py hides ROOT_URL from real_urls.py, which then includes my app's urls.py.</p> <p>root/urls.py:</p> <pre><code>from django.conf.urls.defaults import * #from mysite.settings import ROOT_URL from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: (r'^blog/', include('mysite.blog.urls')), url(r'^%s' % settings.ROOT_URL[1:], include('mysite.real_urls')), ) </code></pre> <p>root/real_urls.py:</p> <pre><code>from django.conf.urls.defaults import * from django.contrib import admin urlpatterns = patterns('', url(r'^admin/(.*)', admin.site.root), url(r'^', include('mysite.photogallery.urls')), ) </code></pre> <p>root/photogallery/urls.py (note that this one probably is not causing any of the problems, but I'm adding it here in case anyone wants to see it.):</p> <pre><code>from django.conf.urls.defaults import * from mysite.photogallery.models import Item, Photo urlpatterns = patterns('django.views.generic', url(r'^$', 'simple.direct_to_template', kwargs={'template': 'index.html', 'extra_context': {'item_list': lambda: Item.objects.all()} }, name='index'), url(r'^items/$', 'list_detail.object_list', kwargs={'queryset': Item.objects.all(), 'template_name': 'items_list.html', 'allow_empty': True }, name='item_list'), url(r'^items/(?P&lt;object_id&gt;\d+)/$', 'list_detail.object_detail', kwargs={'queryset': Item.objects.all(), 'template_name': 'items_detail.html' }, name='item_detail' ), url(r'^photos/(?P&lt;object_id&gt;\d+)/$', 'list_detail.object_detail', kwargs={'queryset': Photo.objects.all(), 'template_name': 'photos_detail.html' }, name='photo_detail'),) </code></pre>
1
2009-06-21T23:35:27Z
1,025,210
<p><code>TEMPLATE_CONTEXT_PROCESSORS</code> should contain a list of callable objects, not modules. List the actual functions that will transform the template contexts. <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#id1" rel="nofollow">Link to docs</a>. </p>
4
2009-06-22T01:26:06Z
[ "python", "django", "django-urls" ]
How to use win32 API's with python?
1,025,029
<p>How can I use win32 API in Python?<br> What is the best and easiest way to do it?<br> Can you please provide some examples?</p>
45
2009-06-21T23:37:04Z
1,025,056
<p>PyWin32, as mentioned by @chaos, is probably the most popular choice; the alternative is <a href="http://docs.python.org/library/ctypes.html">ctypes</a> which is part of Python's standard library. For example, <code>print ctypes.windll.kernel32.GetModuleHandleA(None)</code> will show the module-handle of the current module (EXE or DLL). A more extensive example of using ctypes to get at win32 APIs is <a href="http://web.archive.org/web/20081016104309/http://mail.python.org/pipermail/python-list/2005-March/314328.html">here</a>.</p>
15
2009-06-21T23:51:31Z
[ "python", "winapi", "api" ]
How to use win32 API's with python?
1,025,029
<p>How can I use win32 API in Python?<br> What is the best and easiest way to do it?<br> Can you please provide some examples?</p>
45
2009-06-21T23:37:04Z
1,025,331
<p>PyWin32 is the way to go - but how to use it? One approach is to begin with a concrete problem you're having and attempting to solve it. PyWin32 provides bindings for the Win32 API functions for which there are many, and you really have to pick a specific goal first.</p> <p>In my Python 2.5 installation (ActiveState on Windows) the win32 package has a Demos folder packed with sample code of various parts of the library. </p> <p>For example, here's CopyFileEx.py:</p> <pre><code>import win32file, win32api import os def ProgressRoutine(TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred, StreamNumber, CallbackReason, SourceFile, DestinationFile, Data): print Data print TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred, StreamNumber, CallbackReason, SourceFile, DestinationFile ##if TotalBytesTransferred &gt; 100000: ## return win32file.PROGRESS_STOP return win32file.PROGRESS_CONTINUE temp_dir=win32api.GetTempPath() fsrc=win32api.GetTempFileName(temp_dir,'cfe')[0] fdst=win32api.GetTempFileName(temp_dir,'cfe')[0] print fsrc, fdst f=open(fsrc,'w') f.write('xxxxxxxxxxxxxxxx\n'*32768) f.close() ## add a couple of extra data streams f=open(fsrc+':stream_y','w') f.write('yyyyyyyyyyyyyyyy\n'*32768) f.close() f=open(fsrc+':stream_z','w') f.write('zzzzzzzzzzzzzzzz\n'*32768) f.close() operation_desc='Copying '+fsrc+' to '+fdst win32file.CopyFileEx(fsrc, fdst, ProgressRoutine, operation_desc, False, win32file.COPY_FILE_RESTARTABLE) </code></pre> <p>It shows how to use the CopyFileEx function with a few others (such as GetTempPath and GetTempFileName). From this example you can get a "general feel" of how to work with this library. </p>
32
2009-06-22T03:04:13Z
[ "python", "winapi", "api" ]
How to use win32 API's with python?
1,025,029
<p>How can I use win32 API in Python?<br> What is the best and easiest way to do it?<br> Can you please provide some examples?</p>
45
2009-06-21T23:37:04Z
11,831,060
<p>The important functions that you can to use in win32 Python are the message boxes, this is classical example of OK or Cancel.</p> <pre><code>result = win32api.MessageBox(None,"Do you want to open a file?", "title",1) if result == 1: print 'Ok' elif result == 2: print 'cancel' </code></pre> <p>The collection: </p> <pre><code>win32api.MessageBox(0,"msgbox", "title") win32api.MessageBox(0,"ok cancel?", "title",1) win32api.MessageBox(0,"abort retry ignore?", "title",2) win32api.MessageBox(0,"yes no cancel?", "title",3) </code></pre>
2
2012-08-06T15:16:13Z
[ "python", "winapi", "api" ]
Finding the parent tag of a text string with ElementTree/lxml
1,025,129
<p>I'm trying to take a string of text, and "extract" the rest of the text in the paragraph/document from the html.</p> <p>My current is approach is trying to find the "parent tag" of the string in the html that has been parsed with lxml. (if you know of a better way to tackle this problem, I'm all ears!)</p> <p>For example, search the tree for "TEXT STRING HERE" and return the "p" tag. (note that I won't know the exact layout of the html beforehand)</p> <pre><code>&lt;html&gt; &lt;head&gt; ... &lt;/head&gt; &lt;body&gt; .... &lt;div&gt; ... &lt;p&gt;TEXT STRING HERE ......&lt;/p&gt; ... &lt;/html&gt; </code></pre> <p>Thanks for your help!</p>
2
2009-06-22T00:29:02Z
1,025,206
<p>This is a simple way to do it with ElementTree. It does require that your HTML input is valid XML (so I have added the appropriate end tags to your HTML):</p> <pre><code>import elementtree.ElementTree as ET html = """&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;p&gt;TEXT STRING HERE ......&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;""" for e in ET.fromstring(html).getiterator(): if e.text.find('TEXT STRING HERE') != -1: print "Found string %r, element = %r" % (e.text, e) </code></pre>
3
2009-06-22T01:19:18Z
[ "python", "lxml", "elementtree" ]
Units conversion in Python
1,025,145
<p><a href="http://en.wikipedia.org/wiki/SymPy">SymPy</a> is a great tool for doing units conversions in Python:</p> <pre><code>&gt;&gt;&gt; from sympy.physics import units &gt;&gt;&gt; 12. * units.inch / units.m 0.304800000000000 </code></pre> <p>You can easily roll your own:</p> <pre><code>&gt;&gt;&gt; units.BTU = 1055.05585 * units.J &gt;&gt;&gt; units.BTU 1055.05585*m**2*kg/s**2 </code></pre> <p>However, I cannot implement this into my application unless I can convert degrees C (absolute) to K to degrees F to degrees R, or any combo thereof.</p> <p>I thought maybe something like this would work:</p> <pre><code>units.degC = &lt;&lt;somefunc of units.K&gt;&gt; </code></pre> <p>But clearly that is the wrong path to go down. Any suggestions for cleanly implementing "offset"-type units conversions in SymPy?</p> <p>Note: I'm open to trying other units conversion modules, but don't know of any besides <a href="http://home.scarlet.be/be052320/Unum.html">Unum</a>, and found it to be cumbersome.</p> <p>Edit: OK, it is now clear that what I want to do is first determine if the two quantities to be compared are in the same coordinate system. (like time units reference to different epochs or time zones or dB to straight amplitude), make the appropriate transformation, then make the conversion. Are there any general coordinate system management tools? That would be great. </p> <p>I would make the assumption that °F and °C always refer to Δ°F Δ°C within an expression but refer to absolute when standing alone. I was just wondering if there was a way to make <code>units.degF</code> a function and slap a decorator <code>property()</code> on it to deal with those two conditions.</p> <p>But for now, I'll set <code>units.C == units.K</code> and try to make it very clear in the documentation to use functions <code>convertCtoK(...)</code> and <code>convertFtoR(...)</code> when dealing with absolute units. (Just kidding. No I won't.)</p>
11
2009-06-22T00:41:10Z
1,025,173
<p>The Unum documentation has a pretty good writeup on why this is hard:</p> <blockquote> <p>Unum is unable to handle reliably conversions between °Celsius and Kelvin. The issue is referred as the 'false origin problem' : the 0°Celsius is defined as 273.15 K. This is really a special and annoying case, since in general the value 0 is unaffected by unit conversion, e.g. 0 [m] = 0 [miles] = ... . Here, the conversion Kelvin/°Celsius is characterized by a factor 1 and an offset of 273.15 K. The offset is not feasible in the current version of Unum.</p> <p>Moreover it will presumably never be integrated in a future version because there is also a conceptual problem : the offset should be applied if the quantity represents an absolute temperature, but it shouldn't if the quantity represents a difference of temperatures. For instance, a raise of temperature of 1° Celsius is equivalent to a raise of 1 K. It is impossible to guess what is in the user mind, whether it's an absolute or a relative temperature. The question of absolute vs relative quantities is unimportant for other units since the answer does not impact the conversion rule. Unum is unable to make the distinction between the two cases.</p> </blockquote> <p>It's pretty easy to conceptually see the problems with trying to represent absolute temperature conversion symbolically. With any normal relative unit, <code>(x unit) * 2 == (x * 2) unit</code>—unit math is commutative. With absolute temperatures, that breaks down—it's difficult to do anything more complex than straight temperature conversions with no other unit dimensions. You're probably best off keeping all calculations in Kelvin, and converting to and from other temperature units only at the entry and exit points of your code.</p>
8
2009-06-22T01:00:47Z
[ "python", "math", "symbolic-math", "sympy" ]
Units conversion in Python
1,025,145
<p><a href="http://en.wikipedia.org/wiki/SymPy">SymPy</a> is a great tool for doing units conversions in Python:</p> <pre><code>&gt;&gt;&gt; from sympy.physics import units &gt;&gt;&gt; 12. * units.inch / units.m 0.304800000000000 </code></pre> <p>You can easily roll your own:</p> <pre><code>&gt;&gt;&gt; units.BTU = 1055.05585 * units.J &gt;&gt;&gt; units.BTU 1055.05585*m**2*kg/s**2 </code></pre> <p>However, I cannot implement this into my application unless I can convert degrees C (absolute) to K to degrees F to degrees R, or any combo thereof.</p> <p>I thought maybe something like this would work:</p> <pre><code>units.degC = &lt;&lt;somefunc of units.K&gt;&gt; </code></pre> <p>But clearly that is the wrong path to go down. Any suggestions for cleanly implementing "offset"-type units conversions in SymPy?</p> <p>Note: I'm open to trying other units conversion modules, but don't know of any besides <a href="http://home.scarlet.be/be052320/Unum.html">Unum</a>, and found it to be cumbersome.</p> <p>Edit: OK, it is now clear that what I want to do is first determine if the two quantities to be compared are in the same coordinate system. (like time units reference to different epochs or time zones or dB to straight amplitude), make the appropriate transformation, then make the conversion. Are there any general coordinate system management tools? That would be great. </p> <p>I would make the assumption that °F and °C always refer to Δ°F Δ°C within an expression but refer to absolute when standing alone. I was just wondering if there was a way to make <code>units.degF</code> a function and slap a decorator <code>property()</code> on it to deal with those two conditions.</p> <p>But for now, I'll set <code>units.C == units.K</code> and try to make it very clear in the documentation to use functions <code>convertCtoK(...)</code> and <code>convertFtoR(...)</code> when dealing with absolute units. (Just kidding. No I won't.)</p>
11
2009-06-22T00:41:10Z
1,025,184
<p>I personally like <a href="http://packages.python.org/quantities/" rel="nofollow">Quantities</a> thanks to its <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a> integration, however it only does relative temperatures, not absolute.</p>
4
2009-06-22T01:07:29Z
[ "python", "math", "symbolic-math", "sympy" ]
Units conversion in Python
1,025,145
<p><a href="http://en.wikipedia.org/wiki/SymPy">SymPy</a> is a great tool for doing units conversions in Python:</p> <pre><code>&gt;&gt;&gt; from sympy.physics import units &gt;&gt;&gt; 12. * units.inch / units.m 0.304800000000000 </code></pre> <p>You can easily roll your own:</p> <pre><code>&gt;&gt;&gt; units.BTU = 1055.05585 * units.J &gt;&gt;&gt; units.BTU 1055.05585*m**2*kg/s**2 </code></pre> <p>However, I cannot implement this into my application unless I can convert degrees C (absolute) to K to degrees F to degrees R, or any combo thereof.</p> <p>I thought maybe something like this would work:</p> <pre><code>units.degC = &lt;&lt;somefunc of units.K&gt;&gt; </code></pre> <p>But clearly that is the wrong path to go down. Any suggestions for cleanly implementing "offset"-type units conversions in SymPy?</p> <p>Note: I'm open to trying other units conversion modules, but don't know of any besides <a href="http://home.scarlet.be/be052320/Unum.html">Unum</a>, and found it to be cumbersome.</p> <p>Edit: OK, it is now clear that what I want to do is first determine if the two quantities to be compared are in the same coordinate system. (like time units reference to different epochs or time zones or dB to straight amplitude), make the appropriate transformation, then make the conversion. Are there any general coordinate system management tools? That would be great. </p> <p>I would make the assumption that °F and °C always refer to Δ°F Δ°C within an expression but refer to absolute when standing alone. I was just wondering if there was a way to make <code>units.degF</code> a function and slap a decorator <code>property()</code> on it to deal with those two conditions.</p> <p>But for now, I'll set <code>units.C == units.K</code> and try to make it very clear in the documentation to use functions <code>convertCtoK(...)</code> and <code>convertFtoR(...)</code> when dealing with absolute units. (Just kidding. No I won't.)</p>
11
2009-06-22T00:41:10Z
1,025,258
<p>Example, how it could work:</p> <pre><code>&gt;&gt;&gt; T(0*F) + 10*C T(265.37222222222221*K) # or T(47767/180*K) &gt;&gt;&gt; T(0*F + 10*C) T(283.15*K) &gt;&gt;&gt; 0*F + T(10*C) T(283.15*K) &gt;&gt;&gt; 0*F + 10*C 10*K &gt;&gt;&gt; T(0*F) + T(10*C) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for +: 'absolute_temperature' and \ 'absolute_temperature' &gt;&gt;&gt; T(0*F) - T(10*C) T(245.37222222222223*K) # or T(44167/180*K) &gt;&gt;&gt; 0*F - 10*C -10*K </code></pre>
0
2009-06-22T02:04:54Z
[ "python", "math", "symbolic-math", "sympy" ]
Units conversion in Python
1,025,145
<p><a href="http://en.wikipedia.org/wiki/SymPy">SymPy</a> is a great tool for doing units conversions in Python:</p> <pre><code>&gt;&gt;&gt; from sympy.physics import units &gt;&gt;&gt; 12. * units.inch / units.m 0.304800000000000 </code></pre> <p>You can easily roll your own:</p> <pre><code>&gt;&gt;&gt; units.BTU = 1055.05585 * units.J &gt;&gt;&gt; units.BTU 1055.05585*m**2*kg/s**2 </code></pre> <p>However, I cannot implement this into my application unless I can convert degrees C (absolute) to K to degrees F to degrees R, or any combo thereof.</p> <p>I thought maybe something like this would work:</p> <pre><code>units.degC = &lt;&lt;somefunc of units.K&gt;&gt; </code></pre> <p>But clearly that is the wrong path to go down. Any suggestions for cleanly implementing "offset"-type units conversions in SymPy?</p> <p>Note: I'm open to trying other units conversion modules, but don't know of any besides <a href="http://home.scarlet.be/be052320/Unum.html">Unum</a>, and found it to be cumbersome.</p> <p>Edit: OK, it is now clear that what I want to do is first determine if the two quantities to be compared are in the same coordinate system. (like time units reference to different epochs or time zones or dB to straight amplitude), make the appropriate transformation, then make the conversion. Are there any general coordinate system management tools? That would be great. </p> <p>I would make the assumption that °F and °C always refer to Δ°F Δ°C within an expression but refer to absolute when standing alone. I was just wondering if there was a way to make <code>units.degF</code> a function and slap a decorator <code>property()</code> on it to deal with those two conditions.</p> <p>But for now, I'll set <code>units.C == units.K</code> and try to make it very clear in the documentation to use functions <code>convertCtoK(...)</code> and <code>convertFtoR(...)</code> when dealing with absolute units. (Just kidding. No I won't.)</p>
11
2009-06-22T00:41:10Z
25,211,381
<p>The <a href="http://kdavies4.github.io/natu/" rel="nofollow">natu</a> package handles units of temperature. For instance, you can do this:</p> <pre><code>&gt;&gt;&gt; from natu.units import K, degC, degF &gt;&gt;&gt; T = 25*degC &gt;&gt;&gt; T/K 298.1500 &gt;&gt;&gt; T/degF 77.0000 &gt;&gt;&gt; 0*degC + 100*K 100.0 degC </code></pre> <p>Prefixes are supported too:</p> <pre><code>&gt;&gt;&gt; from natu.units import mdegC &gt;&gt;&gt; 100*mdegC/K 273.2500 </code></pre> <p><a href="http://kdavies4.github.io/natu/" rel="nofollow">natu</a> also handles nonlinear units such as the <a href="http://en.wikipedia.org/wiki/Decibel" rel="nofollow">decibel</a>, not just those with offsets like <a href="http://en.wikipedia.org/wiki/Celsius" rel="nofollow">degree Celsius</a> and <a href="http://en.wikipedia.org/wiki/Fahrenheit" rel="nofollow">degree Fahrenheit</a>.</p> <p>Relating to the first example you gave, you can do this:</p> <pre><code>&gt;&gt;&gt; from natu import units &gt;&gt;&gt; 12*units.inch/units.m 0.3048 </code></pre> <p><a href="http://en.wikipedia.org/wiki/British_thermal_unit" rel="nofollow">BTU</a> is already built in. You can change its display unit to m**2*kg/s**2, but by default <a href="http://kdavies4.github.io/natu/" rel="nofollow">natu</a> simplifies the unit to J:</p> <pre><code>&gt;&gt;&gt; from natu.units import BTU &gt;&gt;&gt; BTU.display = 'm2*kg/s2' &gt;&gt;&gt; 1*BTU 1055.05585262 J </code></pre>
0
2014-08-08T20:01:45Z
[ "python", "math", "symbolic-math", "sympy" ]
With Python's optparse module, how do you create an option that takes a variable number of arguments?
1,025,214
<p>With Perl's <code>Getopt::Long</code> you can easily define command-line options that take a variable number of arguments:</p> <pre><code>foo.pl --files a.txt --verbose foo.pl --files a.txt b.txt c.txt --verbose </code></pre> <p>Is there a way to do this directly with Python's <code>optparse</code> module? As far as I can tell, the <code>nargs</code> option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.</p>
10
2009-06-22T01:28:04Z
1,025,230
<p>My mistake: just found this <a href="http://docs.python.org/library/optparse.html#callback-example-6-variable-arguments">Callback Example 6</a>.</p>
9
2009-06-22T01:40:37Z
[ "python", "optparse" ]
With Python's optparse module, how do you create an option that takes a variable number of arguments?
1,025,214
<p>With Perl's <code>Getopt::Long</code> you can easily define command-line options that take a variable number of arguments:</p> <pre><code>foo.pl --files a.txt --verbose foo.pl --files a.txt b.txt c.txt --verbose </code></pre> <p>Is there a way to do this directly with Python's <code>optparse</code> module? As far as I can tell, the <code>nargs</code> option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.</p>
10
2009-06-22T01:28:04Z
1,025,232
<p>I believe <code>optparse</code> does not support what you require (not directly -- as you noticed, you can do it if you're willing to do all the extra work of a callback!-). You could also do it most simply with the third-party extension <a href="http://code.google.com/p/argparse/">argparse</a>, which does support variable numbers of arguments (and also adds several other handy bits of functionality).</p> <p><a href="http://argparse.googlecode.com/svn/trunk/doc/add%5Fargument.html#add%5Fargument">This URL</a> documents <code>argparse</code>'s <code>add_argument</code> -- passing <code>nargs='*'</code> lets the option take zero or more arguments, <code>'+'</code> lets it take one or more arguments, etc.</p>
8
2009-06-22T01:41:19Z
[ "python", "optparse" ]
With Python's optparse module, how do you create an option that takes a variable number of arguments?
1,025,214
<p>With Perl's <code>Getopt::Long</code> you can easily define command-line options that take a variable number of arguments:</p> <pre><code>foo.pl --files a.txt --verbose foo.pl --files a.txt b.txt c.txt --verbose </code></pre> <p>Is there a way to do this directly with Python's <code>optparse</code> module? As far as I can tell, the <code>nargs</code> option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.</p>
10
2009-06-22T01:28:04Z
1,025,239
<p>Wouldn't you be better off with this?</p> <pre><code>foo.pl --files a.txt,b.txt,c.txt --verbose </code></pre>
1
2009-06-22T01:48:31Z
[ "python", "optparse" ]
With Python's optparse module, how do you create an option that takes a variable number of arguments?
1,025,214
<p>With Perl's <code>Getopt::Long</code> you can easily define command-line options that take a variable number of arguments:</p> <pre><code>foo.pl --files a.txt --verbose foo.pl --files a.txt b.txt c.txt --verbose </code></pre> <p>Is there a way to do this directly with Python's <code>optparse</code> module? As far as I can tell, the <code>nargs</code> option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.</p>
10
2009-06-22T01:28:04Z
2,205,552
<p>This took me a little while to figure out, but you can use the callback action to your options to get this done. Checkout how I grab an arbitrary number of args to the "--file" flag in this example.</p> <pre><code>from optparse import OptionParser, def cb(option, opt_str, value, parser): args=[] for arg in parser.rargs: if arg[0] != "-": args.append(arg) else: del parser.rargs[:len(args)] break if getattr(parser.values, option.dest): args.extend(getattr(parser.values, option.dest)) setattr(parser.values, option.dest, args) parser=OptionParser() parser.add_option("-q", "--quiet", action="store_false", dest="verbose", help="be vewwy quiet (I'm hunting wabbits)") parser.add_option("-f", "--filename", action="callback", callback=cb, dest="file") (options, args) = parser.parse_args() print options.file print args </code></pre> <p>Only side effect is that you get your args in a list instead of tuple. But that could be easily fixed, for my particular use case a list is desirable.</p>
20
2010-02-05T07:06:31Z
[ "python", "optparse" ]
With Python's optparse module, how do you create an option that takes a variable number of arguments?
1,025,214
<p>With Perl's <code>Getopt::Long</code> you can easily define command-line options that take a variable number of arguments:</p> <pre><code>foo.pl --files a.txt --verbose foo.pl --files a.txt b.txt c.txt --verbose </code></pre> <p>Is there a way to do this directly with Python's <code>optparse</code> module? As far as I can tell, the <code>nargs</code> option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.</p>
10
2009-06-22T01:28:04Z
15,162,881
<p>Here's one way: Take the fileLst generating string in as a string and then use <a href="http://docs.python.org/2/library/glob.html" rel="nofollow">http://docs.python.org/2/library/glob.html</a> to do the expansion ugh this might not work without escaping the *</p> <p>Actually, got a better way: python myprog.py -V -l 1000 /home/dominic/radar/*.json &lt;- If this is your command line</p> <p>parser, opts = parse_args()</p> <p>inFileLst = parser.largs</p>
0
2013-03-01T16:57:35Z
[ "python", "optparse" ]
With Python's optparse module, how do you create an option that takes a variable number of arguments?
1,025,214
<p>With Perl's <code>Getopt::Long</code> you can easily define command-line options that take a variable number of arguments:</p> <pre><code>foo.pl --files a.txt --verbose foo.pl --files a.txt b.txt c.txt --verbose </code></pre> <p>Is there a way to do this directly with Python's <code>optparse</code> module? As far as I can tell, the <code>nargs</code> option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.</p>
10
2009-06-22T01:28:04Z
30,767,994
<p>I recently has this issue myself: I was on Python 2.6 and needed an option to take a variable number of arguments. I tried to use Dave's solution but found that it wouldn't work without also explicitly setting nargs to 0.</p> <pre><code>def arg_list(option, opt_str, value, parser): args = set() for arg in parser.rargs: if arg[0] = '-': break args.add(arg) parser.rargs.pop(0) setattr(parser.values, option.dest, args) parser=OptionParser() parser.disable_interspersed_args() parser.add_option("-f", "--filename", action="callback", callback=arg_list, dest="file", nargs=0) (options, args) = parser.parse_args() </code></pre> <p>The problem was that, by default, a new option added by add_options is assumed to have nargs = 1 and when nargs > 0 OptionParser will pop items off rargs and assign them to value before any callbacks are called. Thus, for options that do not specify nargs, rargs will always be off by one by the time your callback is called.</p> <p>This callback is can be used for any number of options, just have callback_args be the function to be called instead of setattr.</p>
0
2015-06-10T21:55:18Z
[ "python", "optparse" ]
How do I build a custom "list-type" entry to request.POST
1,025,216
<p>Basically I have a model with a ManyToMany field, and then a modelform derived from that model where that field is rendered as a "multiple choice" selectbox. In my template I'm having that field omitted, electing instead to prepare the values for that field in the view, then pass those prepared values into request.POST (actually a copy of request.POST because request.POST is immutable), then feeding request.POST to the form and then carry on as normal. I can't figure out how to do this, because request.POST isn't just a simple python dictionary, but instead a QueryDict, which behaves a little differently. </p> <p>The field I need to populate is called <code>"not_bases"</code>. When I create the widget using the form, it works perfectly well internally, but just not to my liking UI-wise. When I inspect the django-form submitted POST value via django's handy debug error window, the working QueryDict looks like this:</p> <pre><code>&lt;QueryDict: {u'not_bases': [u'005', u'00AR', u'00F', u'00FD'], [...] }&gt; </code></pre> <p>It appears the value for <code>"not_bases"</code> is a list, but it's not simply a list. I can't just .append() to it because it won't work. I dug around the documentation and found .update(), which <em>appears</em> to work, but doesn't. Here is my code:</p> <pre><code>newPOST = request.POST.copy() for base in bases: newPOST.update({"not_bases": base.identifier}) </code></pre> <p>and here is the output:</p> <pre><code>&lt;QueryDict: {u'not_bases': [u'KMER', u'KYIP'], u'reference': [u''], [...] }&gt; </code></pre> <p>But when I feed that QueryDict to the form, I get an form validation error that says "not_bases: Enter a list of values.". Its obvious that the list-looking things coming from the str() representation of the QueryDict are not the same in the two cases above, even though they look exactly the same</p> <p>So how do I do this?</p>
0
2009-06-22T01:29:44Z
1,026,038
<p>It's really not clear what you're trying to do here, but I doubt that hacking the QueryDict is the right way to achieve it.</p> <p>If you are trying to customise the display of the not_bases field, you can simply override the definition in your modelform declaration:</p> <pre><code>class MyModelForm(forms.ModelForm): not_bases = forms.ChoiceField(choices=[(base, base) for base in bases]) class Meta: model = MyModel </code></pre> <p>Or, if you simply want to avoid showing it on the form, you can exclude it from the form and set the value after validation.</p> <pre><code>class MyModelForm(forms.ModelForm): class Meta: model = MyModel exclude = ['not_bases'] .... if request.POST: if form.is_valid(): instance = form.save(commit=False) instance.not_bases = bases instance.save() </code></pre> <p>Does either of these do what you want?</p>
2
2009-06-22T08:15:46Z
[ "python", "django" ]
Disable GNOME's automount with Python
1,025,244
<p>I need to stop GNOME/Nautilus from automagically mounting new devices and partitions as they appear to the system. How can I accomplish this in python?</p>
1
2009-06-22T01:54:08Z
1,025,369
<p>Why would do it in Python? You can just use the commandline, as in:</p> <pre><code>gconftool-2 --type bool --set /apps/nautilus/preferences/media_automount false </code></pre> <p>If you really need it to be in Python, then you can use the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess module</a>:</p> <pre><code>import subprocess def setAutomount(value): """ @type value: boolean """ cmd = ['gconftool-2', '--type', 'bool', '--set', '/apps/nautilus/preferences/media_automount'] cmd.append(str(value).lower()) subprocess.check_call(cmd) setAutomount(False) </code></pre> <p>But I'm really not sure that it's necessary here.</p>
3
2009-06-22T03:27:13Z
[ "python", "gnome", "hal", "automount" ]
dual iterator in one python object
1,025,348
<p>In python, I am trying to write a class that support two different kind of iterator. Roughly speaking, this object contains a matrix of data and I want to have two different kind of iterator to support row iteration and column iteration. </p>
2
2009-06-22T03:12:19Z
1,025,362
<p>Okay, so make two separate methods where each is a generator.</p> <pre><code>class Matrix(object): def iter_rows(self): for row in self.rows: yield row def iter_columns(self): for column in self.columns: yield column </code></pre> <p>Your <code>__iter__</code> could iterate over one or the other by default, though I'd recommend having no <code>__iter__</code> at all.</p>
2
2009-06-22T03:21:37Z
[ "python", "iterator" ]
dual iterator in one python object
1,025,348
<p>In python, I am trying to write a class that support two different kind of iterator. Roughly speaking, this object contains a matrix of data and I want to have two different kind of iterator to support row iteration and column iteration. </p>
2
2009-06-22T03:12:19Z
1,025,366
<p>Is this what you're looking for?</p> <pre><code>class Matrix(object): def __init__(self, rows): self._rows = rows def columns(self): return zip(*self._rows) def rows(self): return self._rows # Create a Matrix by providing rows. m = Matrix([[1,2,3], [4,5,6], [7,8,9]]) # Iterate in row-major order. for row in m.rows(): for value in row: print value # Iterate in column-major order. for column in m.columns(): for value in column: print value </code></pre> <p>You can use <code>itertools.izip</code> instead of <code>zip</code> if you want to create each column on demand.</p> <p>You can also move the iteration of the actual values into the class. I wasn't sure if you wanted to iterate over rows/columns (as shown) or the values <em>in</em> the rows/columns.</p>
4
2009-06-22T03:24:35Z
[ "python", "iterator" ]
dual iterator in one python object
1,025,348
<p>In python, I am trying to write a class that support two different kind of iterator. Roughly speaking, this object contains a matrix of data and I want to have two different kind of iterator to support row iteration and column iteration. </p>
2
2009-06-22T03:12:19Z
1,025,384
<p><code>dict</code> has several iterator-producing methods -- <code>iterkeys</code>, <code>itervalues</code>, <code>iteritems</code> -- and so should your class. If there's one "most natural" way of iterating, you should also alias it to <code>__iter__</code> for convenience and readability (that's probably going to be <code>iterrows</code>; of course there is always going to be some doubt, as there was with <code>dict</code> when we designed its iteration behavior, but a reasonable pick is better than none).</p> <p>For example, suppose your matrix is square, held flattened up into a row-major list <code>self.data</code>, with a side of <code>self.n</code>. Then:</p> <pre><code>def iterrows(self): start = 0 n = self.n data = self.data while start &lt; n*n: stop = start + n yield data[start:stop] start = stop def itercols(self): start = 0 n = self.n data = self.data while start &lt; n: yield data[start::n] start += 1 __iter__ = iterrows </code></pre>
5
2009-06-22T03:35:57Z
[ "python", "iterator" ]
Decimal alignment formatting in Python
1,025,379
<p>This <em>should</em> be easy.</p> <p>Here's my array (rather, a method of generating representative test arrays):</p> <pre><code>&gt;&gt;&gt; ri = numpy.random.randint &gt;&gt;&gt; ri2 = lambda x: ''.join(ri(0,9,x).astype('S')) &gt;&gt;&gt; a = array([float(ri2(x)+ '.' + ri2(y)) for x,y in ri(1,10,(10,2))]) &gt;&gt;&gt; a array([ 7.99914000e+01, 2.08000000e+01, 3.94000000e+02, 4.66100000e+03, 5.00000000e+00, 1.72575100e+03, 3.91500000e+02, 1.90610000e+04, 1.16247000e+04, 3.53920000e+02]) </code></pre> <p>I want a list of strings where '\n'.join(list_o_strings) would print:</p> <pre><code> 79.9914 20.8 394.0 4661.0 5.0 1725.751 391.5 19061.0 11624.7 353.92 </code></pre> <p>I want to space pad to the left <em>and</em> the right (but no more than necessary).</p> <p>I want a zero after the decimal if that is all that is after the decimal.</p> <p>I do not want scientific notation.</p> <p>..and I do not want to lose any significant digits. (in 353.98000000000002 the 2 is not significant)</p> <p>Yeah, it's nice to want..</p> <p>Python 2.5's <code>%g, %fx.x</code>, etc. are either befuddling me, or can't do it. I have not tried <code>import decimal</code> yet. I can't see that <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a> does it either (although, the <code>array.__str__</code> and <code>array.__repr__</code> are decimal aligned (but sometimes return scientific).</p> <p>Oh, and speed counts. I'm dealing with big arrays here.</p> <p>My current solution approaches are:</p> <ol> <li>to str(a) and parse off NumPy's brackets</li> <li>to str(e) each element in the array and split('.') then pad and reconstruct</li> <li>to a.astype('S'+str(i)) where i is the max(len(str(a))), then pad</li> </ol> <p>It seems like there should be some off-the-shelf solution out there... (but not required)</p> <p>Top suggestion fails with when <code>dtype</code> is float64:</p> <pre><code>&gt;&gt;&gt; a array([ 5.50056103e+02, 6.77383566e+03, 6.01001513e+05, 3.55425142e+08, 7.07254875e+05, 8.83174744e+02, 8.22320510e+01, 4.25076609e+08, 6.28662635e+07, 1.56503068e+02]) &gt;&gt;&gt; ut0 = re.compile(r'(\d)0+$') &gt;&gt;&gt; thelist = [ut0.sub(r'\1', "%12f" % x) for x in a] &gt;&gt;&gt; print '\n'.join(thelist) 550.056103 6773.835663 601001.513 355425141.8471 707254.875038 883.174744 82.232051 425076608.7676 62866263.55 156.503068 </code></pre>
5
2009-06-22T03:34:16Z
1,025,528
<p>Sorry, but after thorough investigation I can't find any way to perform the task you require without a minimum of post-processing (to strip off the trailing zeros you don't want to see); something like:</p> <pre><code>import re ut0 = re.compile(r'(\d)0+$') thelist = [ut0.sub(r'\1', "%12f" % x) for x in a] print '\n'.join(thelist) </code></pre> <p>is speedy and concise, but breaks your constraint of being "off-the-shelf" -- it is, instead, a modular combination of general formatting (which almost does what you want but leaves trailing zero you want to hide) and a RE to remove undesired trailing zeros. Practically, I think it does exactly what you require, but your conditions as stated are, I believe, over-constrained.</p> <p><strong>Edit</strong>: original question was edited to specify more significant digits, require no extra leading space beyond what's required for the largest number, and provide a new example (where my previous suggestion, above, doesn't match the desired output). The work of removing leading whitespace that's common to a bunch of strings is best performed with <a href="http://docs.python.org/library/textwrap.html">textwrap.dedent</a> -- but that works on a single string (with newlines) while the required output is a list of strings. No problem, we'll just put the lines together, dedent them, and split them up again:</p> <pre><code>import re import textwrap a = [ 5.50056103e+02, 6.77383566e+03, 6.01001513e+05, 3.55425142e+08, 7.07254875e+05, 8.83174744e+02, 8.22320510e+01, 4.25076609e+08, 6.28662635e+07, 1.56503068e+02] thelist = textwrap.dedent( '\n'.join(ut0.sub(r'\1', "%20f" % x) for x in a)).splitlines() print '\n'.join(thelist) </code></pre> <p>emits:</p> <pre><code> 550.056103 6773.83566 601001.513 355425142.0 707254.875 883.174744 82.232051 425076609.0 62866263.5 156.503068 </code></pre>
7
2009-06-22T05:07:44Z
[ "python", "formatting", "numpy", "code-golf" ]
Decimal alignment formatting in Python
1,025,379
<p>This <em>should</em> be easy.</p> <p>Here's my array (rather, a method of generating representative test arrays):</p> <pre><code>&gt;&gt;&gt; ri = numpy.random.randint &gt;&gt;&gt; ri2 = lambda x: ''.join(ri(0,9,x).astype('S')) &gt;&gt;&gt; a = array([float(ri2(x)+ '.' + ri2(y)) for x,y in ri(1,10,(10,2))]) &gt;&gt;&gt; a array([ 7.99914000e+01, 2.08000000e+01, 3.94000000e+02, 4.66100000e+03, 5.00000000e+00, 1.72575100e+03, 3.91500000e+02, 1.90610000e+04, 1.16247000e+04, 3.53920000e+02]) </code></pre> <p>I want a list of strings where '\n'.join(list_o_strings) would print:</p> <pre><code> 79.9914 20.8 394.0 4661.0 5.0 1725.751 391.5 19061.0 11624.7 353.92 </code></pre> <p>I want to space pad to the left <em>and</em> the right (but no more than necessary).</p> <p>I want a zero after the decimal if that is all that is after the decimal.</p> <p>I do not want scientific notation.</p> <p>..and I do not want to lose any significant digits. (in 353.98000000000002 the 2 is not significant)</p> <p>Yeah, it's nice to want..</p> <p>Python 2.5's <code>%g, %fx.x</code>, etc. are either befuddling me, or can't do it. I have not tried <code>import decimal</code> yet. I can't see that <a href="http://en.wikipedia.org/wiki/NumPy" rel="nofollow">NumPy</a> does it either (although, the <code>array.__str__</code> and <code>array.__repr__</code> are decimal aligned (but sometimes return scientific).</p> <p>Oh, and speed counts. I'm dealing with big arrays here.</p> <p>My current solution approaches are:</p> <ol> <li>to str(a) and parse off NumPy's brackets</li> <li>to str(e) each element in the array and split('.') then pad and reconstruct</li> <li>to a.astype('S'+str(i)) where i is the max(len(str(a))), then pad</li> </ol> <p>It seems like there should be some off-the-shelf solution out there... (but not required)</p> <p>Top suggestion fails with when <code>dtype</code> is float64:</p> <pre><code>&gt;&gt;&gt; a array([ 5.50056103e+02, 6.77383566e+03, 6.01001513e+05, 3.55425142e+08, 7.07254875e+05, 8.83174744e+02, 8.22320510e+01, 4.25076609e+08, 6.28662635e+07, 1.56503068e+02]) &gt;&gt;&gt; ut0 = re.compile(r'(\d)0+$') &gt;&gt;&gt; thelist = [ut0.sub(r'\1', "%12f" % x) for x in a] &gt;&gt;&gt; print '\n'.join(thelist) 550.056103 6773.835663 601001.513 355425141.8471 707254.875038 883.174744 82.232051 425076608.7676 62866263.55 156.503068 </code></pre>
5
2009-06-22T03:34:16Z
1,025,729
<p>Pythons string formatting can both print out only the necessary decimals (with %g) or use a fixed set of decimals (with %f). However, you want to print out only the necessary decimals, except if the number is a whole number, then you want one decimal, and that makes it complex.</p> <p>This means you would end up with something like:</p> <pre><code>def printarr(arr): for x in array: if math.floor(x) == x: res = '%.1f' % x else: res = '%.10g' % x print "%*s" % (15-res.find('.')+len(res), res) </code></pre> <p>This will first create a string either with 1 decimal, if the value is a whole number, or it will print with automatic decimals (but only up to 10 numbers) if it is not a fractional number. Lastly it will print it, adjusted so that the decimal point will be aligned.</p> <p>Probably, though, numpy actually does what you want, because you typically do want it to be in exponential mode if it's too long.</p>
1
2009-06-22T06:33:05Z
[ "python", "formatting", "numpy", "code-golf" ]
sqlite version for python26
1,025,493
<p>which versions of sqlite may best suite for python 2.6.2?</p>
2
2009-06-22T04:49:30Z
1,025,591
<p>If your Python distribution already comes with a copy of sqlite (such as the Windows distribution, or Debian), this is the version you should use.</p> <p>If you compile sqlite yourself, you should use the version that is recommended by the <a href="http://www.sqlite.org/" rel="nofollow">sqlite authors</a> (currently 3.6.15).</p>
9
2009-06-22T05:36:23Z
[ "python", "sqlite", "python-2.6" ]
sqlite version for python26
1,025,493
<p>which versions of sqlite may best suite for python 2.6.2?</p>
2
2009-06-22T04:49:30Z
1,028,006
<p>I'm using 3.4.0 out of inertia (it's what came with the Python 2.* versions I'm using) but there's no real reason (save powerful inertia;-) to avoid upgrading to 3.4.2, which fixes a couple of bugs that could lead to DB corruption and introduces no incompatibilities that I know of. (If you stick with 3.4.0 I'm told the key thing is to avoid <code>VACUUM</code> as it might mangle your data).</p> <p>Python 3.1 comes with SQLite 3.6.11 (which is supposed to work with Python 2.* just as well) and I might one day update to that (or probably to the latest, currently 3.6.15, to pick up a slew of minor bug fixes and enhancements) just to make sure I'm using identical releases on either Python 2 or Python 3 -- I've never observed a compatibility problem, but I doubt there has been thorough testing to support reading and writing the same DB from 3.4.0 and 3.6.11 (or any two releases so far apart from each other!-).</p>
0
2009-06-22T16:00:11Z
[ "python", "sqlite", "python-2.6" ]
Call program from within a browser without using a webserver
1,025,817
<p>Is there a way to call a program (Python script) from a local HTML page? I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)</p> <p>Later, this will migrate to a server, but I need a fast and easy solution now.</p> <p>Thanks.</p>
2
2009-06-22T07:03:31Z
1,025,846
<p>If you want an an HTML page to have some sort of server-side programming then you will need a webserver of some sort to do the processing.</p> <p>My suggestion would be to get a web server running on your development box, or try to accomplish what you need to do with a local desktop application or script.</p>
1
2009-06-22T07:16:15Z
[ "python", "html", "browser" ]
Call program from within a browser without using a webserver
1,025,817
<p>Is there a way to call a program (Python script) from a local HTML page? I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)</p> <p>Later, this will migrate to a server, but I need a fast and easy solution now.</p> <p>Thanks.</p>
2
2009-06-22T07:03:31Z
1,025,855
<p>No you need some kind of server. Wh not try out the <a href="http://www.google.co.uk/search?q=usb%2Bweb%2Bserver&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-GB:official&amp;client=firefox-a" rel="nofollow">portable webservers</a>? You can run them from your usb drive.</p>
0
2009-06-22T07:18:56Z
[ "python", "html", "browser" ]
Call program from within a browser without using a webserver
1,025,817
<p>Is there a way to call a program (Python script) from a local HTML page? I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)</p> <p>Later, this will migrate to a server, but I need a fast and easy solution now.</p> <p>Thanks.</p>
2
2009-06-22T07:03:31Z
1,025,873
<p>Python has a small built in Web server. If you already already got Python to run with the RS232 you might need to read <a href="http://fragments.turtlemeat.com/pythonwebserver.php" rel="nofollow">here</a> on how to set up a very simple and basic webserver. An even easier one can look like <a href="http://effbot.org/librarybook/simplehttpserver.htm" rel="nofollow">this</a>:</p> <pre><code>import SimpleHTTPServer import SocketServer port = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", port), Handler) httpd.serve_forever() </code></pre> <p>Try so separate you source as good as possible, to that you won't have too much trouble to move it to a production ready Python capable webserver.</p>
3
2009-06-22T07:24:29Z
[ "python", "html", "browser" ]
Call program from within a browser without using a webserver
1,025,817
<p>Is there a way to call a program (Python script) from a local HTML page? I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)</p> <p>Later, this will migrate to a server, but I need a fast and easy solution now.</p> <p>Thanks.</p>
2
2009-06-22T07:03:31Z
1,025,901
<p>Try also XML-RPC it gives you a simple way to pass remote procedure calls from YUI towards a simple XMLRPC server and from that towards your rs232 device</p>
0
2009-06-22T07:31:11Z
[ "python", "html", "browser" ]
Call program from within a browser without using a webserver
1,025,817
<p>Is there a way to call a program (Python script) from a local HTML page? I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)</p> <p>Later, this will migrate to a server, but I need a fast and easy solution now.</p> <p>Thanks.</p>
2
2009-06-22T07:03:31Z
1,025,904
<p>I see now that Daff mentioned the simple HTTP server, but I made an example on how you'd solve your problem (using <code>BaseHTTPServer</code>):</p> <pre><code>import BaseHTTPServer HOST_NAME = 'localhost' PORT_NUMBER = 1337 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(s): s.send_response(200) s.send_header('Content-Type', 'text/html') s.end_headers() # Get parameters in query. params = {} index = s.path.rfind('?') if index &gt;= 0: parts = s.path[index + 1:].split('&amp;') for p in parts: try: a, b = p.split('=', 2) params[a] = b except: params[p] = '' # !!! # Check if there is a color parameter and send to controller... if 'color' in params: print 'Send something to controller...' # !!! s.wfile.write('&lt;pre&gt;%s&lt;/pre&gt;' % params) if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler) try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() </code></pre> <p>Now, from your JavaScript, you'd call <code>http://localhost:1337/?color=ffaabb</code></p>
6
2009-06-22T07:31:26Z
[ "python", "html", "browser" ]
Call program from within a browser without using a webserver
1,025,817
<p>Is there a way to call a program (Python script) from a local HTML page? I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)</p> <p>Later, this will migrate to a server, but I need a fast and easy solution now.</p> <p>Thanks.</p>
2
2009-06-22T07:03:31Z
1,025,929
<p>another quick solution is https://addons.mozilla.org/en-US/firefox/addon/3002 POW, it's a firefox extension that adds a simple web server with Server Side JS built in. </p> <p>You'd be able to access a command line and call a python script from there.</p>
1
2009-06-22T07:40:43Z
[ "python", "html", "browser" ]
Call program from within a browser without using a webserver
1,025,817
<p>Is there a way to call a program (Python script) from a local HTML page? I have a YUI-colorpicker on that page and need to send its value to a microcontroller via rs232. (There is other stuff than the picker, so I can't code an application instead of an HTML page.)</p> <p>Later, this will migrate to a server, but I need a fast and easy solution now.</p> <p>Thanks.</p>
2
2009-06-22T07:03:31Z
1,026,086
<p>I see no reason why you can't setup a handler for .py/.bat/.vbs files in your browser. This should result in your chosen application running a script when you link to it. This won't work when you migrate to the server but as a testing platform it would work. Just remember to turn it off when you're done or you expose yourself to viruses from other sites.</p>
0
2009-06-22T08:30:08Z
[ "python", "html", "browser" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,026,045
<p>You can try starting with <a href="http://bitbucket.org/ubernostrum/django-registration/wiki/Home" rel="nofollow">django-registration</a>.</p> <p>EDIT: You can probably hack something up on your own faster than learning Django. However, learning a framework will serve you better. You'll be able to easily ask a large community when you have problems, and build on work that's already been done. And of course, if you're doing something new in the future, your knowledge of the framework can be more easily reapplied.</p>
1
2009-06-22T08:18:39Z
[ "python", "dreamhost" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,026,046
<p>django framework</p>
1
2009-06-22T08:18:41Z
[ "python", "dreamhost" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,026,169
<p>Let me share my own experience with django. My prerequisits:</p> <ul> <li><p>average knowledge of python</p></li> <li><p>very weak idea of how web works (no js skills, just a bit of css)</p></li> <li><p>my day job is filled with coding in C and I just wanted to try something different, so there certainly was a passion to learn (I think this is the most important one)</p></li> </ul> <p>Why I've chosen django:</p> <ul> <li><p>I've already knew bits and pieces of python</p></li> <li><p>django has excelent documentation, including tutorial, which explained everything in very clear and simple manner</p></li> </ul> <p>It is worth to read complete <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">manual</a> first (it took me two or three weekends. I remember I could not remember/understand everything at first pass, but it helped me to learn where the information can be found when needed. There is also another source of documentaion called <a href="http://www.djangobook.com/" rel="nofollow" title="djangobook">djangobook</a>. Djangobook contains same information as manual, but things are explained more in detail. It's worth to read it also, it helps to catch up with MVC concept, if you have not tried that before.</p> <p>And finally to answer your question best: there are already also <a href="http://openid.net" rel="nofollow">OpenId</a> modules ready for you. I'm considering to use <a href="http://bitbucket.org/benoitc/django-authopenid/wiki/Home" rel="nofollow">django-authopenid</a> for my new project. It supports OpenId, while providing fallback to locally managed users.</p> <p>There is certain learning curve if you are going learn django. The more you know about the web and python the steeper the curve is. I had to also learn bits and pieces of javascript and it took me also some time. If you are able to spend full time learning django, then you can expect you'll be able to deliver first results within 4-6 weeks. It took me 6 months, since I was doing my django studies in free time.</p>
4
2009-06-22T09:00:26Z
[ "python", "dreamhost" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,026,242
<p>Django is the way to go. You can try it locally on your PC and see do you like it. It is very nice framework and allows you to quickly build your applications.</p> <p>If you want to give Django quick go to see how it feels you can download <a href="http://www.portablepython.com" rel="nofollow">Portable Python</a> where everything is preinstalled and ready to use.</p> <p>You can also do what you are trying to do with apache module mod_python (which is also used to run Django) but it <strong>would require more coding</strong>. Your code snippet would work with mod_python (<a href="http://www.modpython.org/" rel="nofollow">http://www.modpython.org/</a>) right away. I think mod_python comes pre-installed on Dreamhost so you can try it.</p>
1
2009-06-22T09:20:34Z
[ "python", "dreamhost" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,026,260
<p>For a more complete basic setup (with lots of preprogrammed features) I would point you at Pinax which is a web site on top of Django (which I praise of course, see the dedicated page on dreamhost Wiki at <a href="http://wiki.dreamhost.com/Django" rel="nofollow">http://wiki.dreamhost.com/Django</a>)</p> <p>The introduction on the project's web site (pinaxproject.com) : </p> <blockquote> <p>Pinax is an open-source platform built on the Django Web Framework.</p> <p>By integrating numerous reusable Django apps to take care of the things that many sites have in common, it lets you focus on what makes your site different.</p> </blockquote> <p>There you will have a complete web site to customize and add features to.</p>
1
2009-06-22T09:25:21Z
[ "python", "dreamhost" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,027,704
<p>Another voice to the choir.</p> <p>Go for django. It's very good and easy to use.</p>
0
2009-06-22T15:02:30Z
[ "python", "dreamhost" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,027,850
<p>There are several blog entries &amp;c pointing out some problems with Python on Dreamhost and how to work around them to run several web frameworks that could suit you. (Most of the posts are over a year old so it may be that dreamhost has fixed some of the issues since then, of course, but the only way to really find out is to try!-).</p> <p>Start with <a href="http://wiki.dreamhost.com/Python" rel="nofollow">this page</a>, dreamhost's own wikipage about Python -- at least you know it's quite current (was last updated earlier today!-). It gives instructions on using virtual env, building a custom Python &amp;c if you absolutely need that, and running WSGI apps -- WSGI is the common underpinning of all modern Python web frameworks, including Django which everybody's recommending but also Pylons &amp;c.</p> <p>Some notes on running Pylons on Dreamhost are <a href="http://www.heikkitoivonen.net/blog/2008/02/03/pylons-on-dreamhost/" rel="nofollow">here</a> (but it does look like Dreamhost has since fixed some issues, e.g. <code>flup</code> <em>is</em> now the dreamhost-recommended FCGI layer for WSGI as you'll see at the previously mentioned URL) and links therefrom. If you do go with Pylons, <a href="http://wiki.pylonshq.com/display/pylonscookbook/Authentication%2Band%2BAuthorization" rel="nofollow">here</a> is the best place to start considering how best to do auth (authentication and authorization) with it. I'm trying to play devil's advocate since everybody else's recommending django, but for a beginner django may in fact be better than pylons (still, spending a day or so lightly researching each main alternative, before you commit to one, is a good investment of your time!-).</p> <p>For Django, again there's an official dreamhost <a href="http://wiki.dreamhost.com/Django" rel="nofollow">wiki page</a> and it's pretty thorough -- be sure to read through it and briefly to the other URLs it points to. The contributed <code>auth</code> module is no doubt the best way to do authentication and authorization if you do decide to go with Django.</p> <p>And, whichever way you do choose -- best of luck!</p>
2
2009-06-22T15:29:36Z
[ "python", "dreamhost" ]
How do I set up a basic website with registration in Python on Dreamhost?
1,026,030
<p>I need to write a basic website on Dreamhost. It needs to be done in Python. I discovered Dreamhost permits me to write .py files, and read them.</p> <h3>Example:</h3> <pre><code>#!/usr/bin/python print "Content-type: text/html\n\n" print "hello world" </code></pre> <p>So now I am looking for a basic framework, or a set of files that has already programmed the whole registration to be able to kick-off the project in a simple way. By registration I mean the files to register a new account, log in, check the email (sending a mail), and edit the user information. All this possibly using MySQL.</p>
2
2009-06-22T08:13:33Z
1,092,696
<p>I've noticed that a lot of people recommend Django. If you're running on a shared host on Dreamhost, the performance will not be satisfactory. </p> <p>This is a known issue with Dreamhost shared hosting. I have installed web2py on my Dreamhost shared account and it seems to work okay; search the google groups for an install FAQ.</p> <p>Later edit: google Dreamhost Django performance for an idea of what I mean.</p>
1
2009-07-07T14:33:39Z
[ "python", "dreamhost" ]
Django model query with custom select fields
1,026,204
<p>I'm using the row-level permission model known as django-granular-permissions (<a href="http://code.google.com/p/django-granular-permissions/" rel="nofollow">http://code.google.com/p/django-granular-permissions/</a>). The permission model simply has just two more fields which are content-type and object id.</p> <p>I've used the following query:</p> <pre><code> User.objects.filter(Q(row_permission_set__name='staff') | \ Q(row_permission_set__name='student'), \ row_permission_set__object_id=labsite.id) </code></pre> <p>I want to add <code>is_staff</code> and <code>is_student</code> boolean fields to the result set without querying everytime when I fetch the result.</p> <p>Django documentation shows extra() method of querysets, but I can't figure out what I should write for plain SQL selection query with this relation.</p> <p>How to do this?</p>
0
2009-06-22T09:12:19Z
1,026,362
<p>Normally you'd use select_related() for things like this, but unfortunately it doesn't work on reverse relationships. What you could do is turn the query around:</p> <pre><code>users = [permission.user for permission in Permission.objects.select_related('user').filter(...)] </code></pre>
0
2009-06-22T09:56:36Z
[ "python", "django", "django-models" ]
Django model query with custom select fields
1,026,204
<p>I'm using the row-level permission model known as django-granular-permissions (<a href="http://code.google.com/p/django-granular-permissions/" rel="nofollow">http://code.google.com/p/django-granular-permissions/</a>). The permission model simply has just two more fields which are content-type and object id.</p> <p>I've used the following query:</p> <pre><code> User.objects.filter(Q(row_permission_set__name='staff') | \ Q(row_permission_set__name='student'), \ row_permission_set__object_id=labsite.id) </code></pre> <p>I want to add <code>is_staff</code> and <code>is_student</code> boolean fields to the result set without querying everytime when I fetch the result.</p> <p>Django documentation shows extra() method of querysets, but I can't figure out what I should write for plain SQL selection query with this relation.</p> <p>How to do this?</p>
0
2009-06-22T09:12:19Z
1,026,477
<pre><code>.extra(select={'is_staff': "%s.name='staff'" % Permission._meta.db_table, 'is_student': "%s.name='student'" % Permission._meta.db_table, }) </code></pre>
4
2009-06-22T10:36:12Z
[ "python", "django", "django-models" ]
Cross-platform way to check admin rights in a Python script under Windows?
1,026,431
<p>Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, <code>os.getuid()</code> is UNIX-only and is not available under Windows.</p>
11
2009-06-22T10:20:32Z
1,026,442
<p>Try doing whatever you need admin rights for, and check for failure.</p> <p>This will only work for some things though, what are you trying to do?</p>
4
2009-06-22T10:25:50Z
[ "python", "privileges", "admin-rights" ]
Cross-platform way to check admin rights in a Python script under Windows?
1,026,431
<p>Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, <code>os.getuid()</code> is UNIX-only and is not available under Windows.</p>
11
2009-06-22T10:20:32Z
1,026,516
<p>It's better if you check which platform your script is running (using <code>sys.platform</code>) and do a test based on that, e.g. import some hasAdminRights function from another, platform-specific module.</p> <p>On Windows you could check whether <code>Windows\System32</code> is writable using <code>os.access</code>, but remember to try to retrieve system's actual "Windows" folder path, probably using pywin32. Don't hardcode one.</p>
3
2009-06-22T10:47:33Z
[ "python", "privileges", "admin-rights" ]
Cross-platform way to check admin rights in a Python script under Windows?
1,026,431
<p>Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, <code>os.getuid()</code> is UNIX-only and is not available under Windows.</p>
11
2009-06-22T10:20:32Z
1,026,626
<pre><code>import ctypes, os try: is_admin = os.getuid() == 0 except AttributeError: is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0 print is_admin </code></pre>
26
2009-06-22T11:22:56Z
[ "python", "privileges", "admin-rights" ]
Cross-platform way to check admin rights in a Python script under Windows?
1,026,431
<p>Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, <code>os.getuid()</code> is UNIX-only and is not available under Windows.</p>
11
2009-06-22T10:20:32Z
1,038,617
<p>Administrator group membership (Domain/Local/Enterprise) is one thing..</p> <p>tailoring your application to not use blanket privilege and setting fine grained rights is a better option especially if the app is being used iinteractively.</p> <p>testing for particular named privileges (se_shutdown se_restore etc), file rights is abetter bet and easier to diagnose.</p>
1
2009-06-24T14:07:57Z
[ "python", "privileges", "admin-rights" ]
Algorithms for named entity recognition
1,026,925
<p>I would like to use named entity recognition (NER) to find adequate tags for texts in a database.</p> <p>I know there is a Wikipedia article about this and lots of other pages describing NER, I would preferably hear something about this topic from you:</p> <ul> <li>What experiences did you make with the various algorithms?</li> <li>Which algorithm would you recommend?</li> <li>Which algorithm is the easiest to implement (PHP/Python)?</li> <li>How to the algorithms work? Is manual training necessary?</li> </ul> <p>Example:</p> <p>"Last year, I was in London where I saw Barack Obama." => Tags: London, Barack Obama</p> <p>I hope you can help me. Thank you very much in advance!</p>
19
2009-06-22T12:26:33Z
1,026,976
<p>I don't really know about NER, but judging from that example, you could make an algorithm that searched for capital letters in the words or something like that. For that I would recommend regex as the most easy to implement solution if you're thinking small.</p> <p>Another option is to compare the texts with a database, wich yould match string pre-identified as Tags of interest.</p> <p>my 5 cents.</p>
-9
2009-06-22T12:38:28Z
[ "php", "python", "extract", "analysis", "named-entity-recognition" ]
Algorithms for named entity recognition
1,026,925
<p>I would like to use named entity recognition (NER) to find adequate tags for texts in a database.</p> <p>I know there is a Wikipedia article about this and lots of other pages describing NER, I would preferably hear something about this topic from you:</p> <ul> <li>What experiences did you make with the various algorithms?</li> <li>Which algorithm would you recommend?</li> <li>Which algorithm is the easiest to implement (PHP/Python)?</li> <li>How to the algorithms work? Is manual training necessary?</li> </ul> <p>Example:</p> <p>"Last year, I was in London where I saw Barack Obama." => Tags: London, Barack Obama</p> <p>I hope you can help me. Thank you very much in advance!</p>
19
2009-06-22T12:26:33Z
1,027,336
<p>To start with check out <a href="http://www.nltk.org/">http://www.nltk.org/</a> if you plan working with python although as far as I know the code isn't "industrial strength" but it will get you started.</p> <p>Check out section 7.5 from <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html">http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html</a> but to understand the algorithms you probably will have to read through a lot of the book.</p> <p>Also check this out <a href="http://nlp.stanford.edu/software/CRF-NER.shtml">http://nlp.stanford.edu/software/CRF-NER.shtml</a>. It's done with java, </p> <p>NER isn't an easy subject and probably nobody will tell you "this is the best algorithm", most of them have their pro/cons.</p> <p>My 0.05 of a dollar.</p> <p>Cheers,</p>
13
2009-06-22T13:53:39Z
[ "php", "python", "extract", "analysis", "named-entity-recognition" ]
Algorithms for named entity recognition
1,026,925
<p>I would like to use named entity recognition (NER) to find adequate tags for texts in a database.</p> <p>I know there is a Wikipedia article about this and lots of other pages describing NER, I would preferably hear something about this topic from you:</p> <ul> <li>What experiences did you make with the various algorithms?</li> <li>Which algorithm would you recommend?</li> <li>Which algorithm is the easiest to implement (PHP/Python)?</li> <li>How to the algorithms work? Is manual training necessary?</li> </ul> <p>Example:</p> <p>"Last year, I was in London where I saw Barack Obama." => Tags: London, Barack Obama</p> <p>I hope you can help me. Thank you very much in advance!</p>
19
2009-06-22T12:26:33Z
1,027,399
<p>It depends on whether you want:</p> <p><em>To learn about NER</em>: An excellent place to start is with <a href="http://www.nltk.org/" rel="nofollow">NLTK</a>, and the associated <a href="http://www.nltk.org/book" rel="nofollow">book</a>.</p> <p><em>To implement the best solution</em>: Here you're going to need to look for the state of the art. Have a look at publications in <a href="http://trec.nist.gov/" rel="nofollow">TREC</a>. A more specialised meeting is <a href="http://biocreative.sourceforge.net/bc2ws/index.html" rel="nofollow">Biocreative</a> (a good example of NER applied to a narrow field).</p> <p><em>To implement the easiest solution</em>: In this case you basically just want to do simple tagging, and pull out the words tagged as nouns. You could use a tagger from nltk, or even just look up each word in <a href="http://pywordnet.sourceforge.net" rel="nofollow">PyWordnet</a> and tag it with the most common wordsense.</p> <p><hr /></p> <p>Most algorithms required some sort of training, and perform best when they're trained on content that represents what you're going to be asking it to tag. </p>
3
2009-06-22T14:05:15Z
[ "php", "python", "extract", "analysis", "named-entity-recognition" ]
Algorithms for named entity recognition
1,026,925
<p>I would like to use named entity recognition (NER) to find adequate tags for texts in a database.</p> <p>I know there is a Wikipedia article about this and lots of other pages describing NER, I would preferably hear something about this topic from you:</p> <ul> <li>What experiences did you make with the various algorithms?</li> <li>Which algorithm would you recommend?</li> <li>Which algorithm is the easiest to implement (PHP/Python)?</li> <li>How to the algorithms work? Is manual training necessary?</li> </ul> <p>Example:</p> <p>"Last year, I was in London where I saw Barack Obama." => Tags: London, Barack Obama</p> <p>I hope you can help me. Thank you very much in advance!</p>
19
2009-06-22T12:26:33Z
24,789,590
<p>There's a few tools and API's out there.</p> <p>There's a tool built on top of DBPedia called DBPedia Spotlight (<a href="https://github.com/dbpedia-spotlight/dbpedia-spotlight/wiki" rel="nofollow">https://github.com/dbpedia-spotlight/dbpedia-spotlight/wiki</a>). You can use their REST interface or download and install your own server. The great thing is it maps entities to their DBPedia presence, which means you can extract interesting linked data.</p> <p>AlchemyAPI (www.alchemyapi.com) have an API that will do this via REST as well, and they use a freemium model.</p> <p>I think most techniques rely on a bit of NLP to find entities, then use an underlying database like Wikipedia, DBPedia, Freebase, etc to do disambiguation and relevance (so for instance, trying to decide whether an article that mentions Apple is about the fruit or the company... we would choose the company if the article includes other entities that are linked to Apple the company).</p>
1
2014-07-16T20:01:14Z
[ "php", "python", "extract", "analysis", "named-entity-recognition" ]
How can I make sure all my Python code "compiles"?
1,026,966
<p>My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages.</p> <p>When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-specific errors remain. For me that means that I can't rely solely on my runtime defense (rigorous testing of input, asserts etc.) to avoid crashes, because in 6 months when some otherwise nice code finally gets run, it might crack due to some stupid typo.</p> <p>Clearly a system should be tested enough to make sure all code has been run, but most of the time I use Python for in-house scripts and small tools, which ofcourse never gets the QA attention they need. Also, some code is so simple that (if your background is C/C++) you know it will work fine as long as it compiles (e.g. getter-methods inside classes, usually a simple return of a member variable).</p> <p>So, my question is the obvious - is there any way (with a special tool or something) I can make sure all the code in my Python script will "compile" and run?</p>
14
2009-06-22T12:36:18Z
1,026,984
<p>I think what you are looking for is code test line coverage. You want to add tests to your script that will make sure all of your lines of code, or as many as you have time to, get tested. Testing is a great deal of work, but if you want the kind of assurance you are asking for, there is no free lunch, sorry :( .</p>
1
2009-06-22T12:39:25Z
[ "python", "parsing", "code-analysis" ]
How can I make sure all my Python code "compiles"?
1,026,966
<p>My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages.</p> <p>When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-specific errors remain. For me that means that I can't rely solely on my runtime defense (rigorous testing of input, asserts etc.) to avoid crashes, because in 6 months when some otherwise nice code finally gets run, it might crack due to some stupid typo.</p> <p>Clearly a system should be tested enough to make sure all code has been run, but most of the time I use Python for in-house scripts and small tools, which ofcourse never gets the QA attention they need. Also, some code is so simple that (if your background is C/C++) you know it will work fine as long as it compiles (e.g. getter-methods inside classes, usually a simple return of a member variable).</p> <p>So, my question is the obvious - is there any way (with a special tool or something) I can make sure all the code in my Python script will "compile" and run?</p>
14
2009-06-22T12:36:18Z
1,026,985
<p>Look at <a href="http://pychecker.sourceforge.net/">PyChecker</a> and <a href="http://www.logilab.org/857">PyLint</a>.</p> <p>Here's example output from pylint, resulting from the trivial program:</p> <pre><code>print a </code></pre> <p>As you can see, it detects the undefined variable, which py_compile won't (deliberately).</p> <pre><code>in foo.py: ************* Module foo C: 1: Black listed name "foo" C: 1: Missing docstring E: 1: Undefined variable 'a' ... |error |1 |1 |= | </code></pre> <p>Trivial example of why tests aren't good enough, even if they cover "every line":</p> <pre><code>bar = "Foo" foo = "Bar" def baz(X): return bar if X else fo0 print baz(input("True or False: ")) </code></pre> <p>EDIT: PyChecker handles the ternary for me:</p> <pre><code>Processing ternary... True or False: True Foo Warnings... ternary.py:6: No global (fo0) found ternary.py:8: Using input() is a security problem, consider using raw_input() </code></pre>
21
2009-06-22T12:39:34Z
[ "python", "parsing", "code-analysis" ]
How can I make sure all my Python code "compiles"?
1,026,966
<p>My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages.</p> <p>When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-specific errors remain. For me that means that I can't rely solely on my runtime defense (rigorous testing of input, asserts etc.) to avoid crashes, because in 6 months when some otherwise nice code finally gets run, it might crack due to some stupid typo.</p> <p>Clearly a system should be tested enough to make sure all code has been run, but most of the time I use Python for in-house scripts and small tools, which ofcourse never gets the QA attention they need. Also, some code is so simple that (if your background is C/C++) you know it will work fine as long as it compiles (e.g. getter-methods inside classes, usually a simple return of a member variable).</p> <p>So, my question is the obvious - is there any way (with a special tool or something) I can make sure all the code in my Python script will "compile" and run?</p>
14
2009-06-22T12:36:18Z
1,027,032
<p>Your code actually gets compiled when you run it, the Python runtime will complain if there is a syntax error in the code. Compared to statically compiled languages like C/C++ or Java, it does not check whether variable names and types are correct – for that you need to actually run the code (e.g. with automated tests).</p>
0
2009-06-22T12:49:04Z
[ "python", "parsing", "code-analysis" ]
How can I make sure all my Python code "compiles"?
1,026,966
<p>My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages.</p> <p>When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-specific errors remain. For me that means that I can't rely solely on my runtime defense (rigorous testing of input, asserts etc.) to avoid crashes, because in 6 months when some otherwise nice code finally gets run, it might crack due to some stupid typo.</p> <p>Clearly a system should be tested enough to make sure all code has been run, but most of the time I use Python for in-house scripts and small tools, which ofcourse never gets the QA attention they need. Also, some code is so simple that (if your background is C/C++) you know it will work fine as long as it compiles (e.g. getter-methods inside classes, usually a simple return of a member variable).</p> <p>So, my question is the obvious - is there any way (with a special tool or something) I can make sure all the code in my Python script will "compile" and run?</p>
14
2009-06-22T12:36:18Z
1,027,127
<p>If you are using Eclipse with <a href="http://pydev.sourceforge.net/" rel="nofollow">Pydev</a> as an IDE, it can flag many typos for you with red squigglies immediately, and has Pylint integration too. For example:</p> <pre><code>foo = 5 print food </code></pre> <p>will be flagged as "Undefined variable: food". Of course this is not always accurate (perhaps food was defined earlier using setattr or other exotic techniques), but it works well most of the time.</p> <p>In general, you can only statically analyze your code to the extent that your code is actually static; the more dynamic your code is, the more you really do need automated testing.</p>
1
2009-06-22T13:09:00Z
[ "python", "parsing", "code-analysis" ]
How can I make sure all my Python code "compiles"?
1,026,966
<p>My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages.</p> <p>When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-specific errors remain. For me that means that I can't rely solely on my runtime defense (rigorous testing of input, asserts etc.) to avoid crashes, because in 6 months when some otherwise nice code finally gets run, it might crack due to some stupid typo.</p> <p>Clearly a system should be tested enough to make sure all code has been run, but most of the time I use Python for in-house scripts and small tools, which ofcourse never gets the QA attention they need. Also, some code is so simple that (if your background is C/C++) you know it will work fine as long as it compiles (e.g. getter-methods inside classes, usually a simple return of a member variable).</p> <p>So, my question is the obvious - is there any way (with a special tool or something) I can make sure all the code in my Python script will "compile" and run?</p>
14
2009-06-22T12:36:18Z
1,061,573
<p>Others have mentioned tools like PyLint which are pretty good, but the long and the short of it is that it's simply not possible to do 100%. In fact, you might not even want to do it. Part of the benefit to Python's dynamicity is that you can do crazy things like insert names into the local scope through a dictionary access.</p> <p>What it comes down to is that if you want a way to catch type errors at compile time, you shouldn't use Python. A language choice always involves a set of trade-offs. If you choose Python over C, just be aware that you're trading a strong type system for faster development, better string manipulation, etc.</p>
2
2009-06-30T03:26:18Z
[ "python", "parsing", "code-analysis" ]
Python - when is 'import' required?
1,027,557
<p>mod1.py</p> <pre><code>import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) </code></pre> <p>mod2.py</p> <pre><code>#import mod1 -- not necessary def show_answer(thing): print thing.answer() </code></pre> <p>Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used.</p> <p>Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?</p> <p>In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?</p> <p>I realise Python is <em>so</em> much more dynamic than C++, it's taken me a while to see how little code you actually need to write! </p> <p>I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.</p> <p>UPDATE: Thanks for all the answers, I think I should clarify my question now:</p> <p>Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?</p>
3
2009-06-22T14:35:30Z
1,027,596
<p>Think of import being more like the linker.<br /> With "import mod2" you are simply telling python that it can find the function in the file mod2.py </p>
1
2009-06-22T14:43:13Z
[ "python", "import", "module" ]
Python - when is 'import' required?
1,027,557
<p>mod1.py</p> <pre><code>import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) </code></pre> <p>mod2.py</p> <pre><code>#import mod1 -- not necessary def show_answer(thing): print thing.answer() </code></pre> <p>Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used.</p> <p>Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?</p> <p>In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?</p> <p>I realise Python is <em>so</em> much more dynamic than C++, it's taken me a while to see how little code you actually need to write! </p> <p>I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.</p> <p>UPDATE: Thanks for all the answers, I think I should clarify my question now:</p> <p>Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?</p>
3
2009-06-22T14:35:30Z
1,027,604
<p>In this case you're right: show_answer() is given an object, of which it calls the method "answer". As long as the object given to show_answer() has such a method, it doesn't matter where the object comes from.</p> <p>If, however, you wanted to create an instance of Universe inside mod2, you'd have to import mod1, because Universe is not in the mod2 namespace, even after mod2 has been imported by mod1.</p>
6
2009-06-22T14:44:40Z
[ "python", "import", "module" ]
Python - when is 'import' required?
1,027,557
<p>mod1.py</p> <pre><code>import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) </code></pre> <p>mod2.py</p> <pre><code>#import mod1 -- not necessary def show_answer(thing): print thing.answer() </code></pre> <p>Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used.</p> <p>Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?</p> <p>In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?</p> <p>I realise Python is <em>so</em> much more dynamic than C++, it's taken me a while to see how little code you actually need to write! </p> <p>I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.</p> <p>UPDATE: Thanks for all the answers, I think I should clarify my question now:</p> <p>Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?</p>
3
2009-06-22T14:35:30Z
1,027,637
<p>import in Python loads the module into the given namespace. As such, is it as if the def show_answer actually existed in the mod1.py module. Because of this, mod2.py does not need to know of the Universe class and thus you do not need to import mod1 from mod2.py.</p>
1
2009-06-22T14:48:38Z
[ "python", "import", "module" ]
Python - when is 'import' required?
1,027,557
<p>mod1.py</p> <pre><code>import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) </code></pre> <p>mod2.py</p> <pre><code>#import mod1 -- not necessary def show_answer(thing): print thing.answer() </code></pre> <p>Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used.</p> <p>Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?</p> <p>In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?</p> <p>I realise Python is <em>so</em> much more dynamic than C++, it's taken me a while to see how little code you actually need to write! </p> <p>I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.</p> <p>UPDATE: Thanks for all the answers, I think I should clarify my question now:</p> <p>Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?</p>
3
2009-06-22T14:35:30Z
1,027,706
<p>Actually, in this case, importing <code>mod1</code> in <code>mod2.py</code> should <b>not</b> work.<br /> Would it not create a circular reference? </p>
1
2009-06-22T15:03:07Z
[ "python", "import", "module" ]
Python - when is 'import' required?
1,027,557
<p>mod1.py</p> <pre><code>import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) </code></pre> <p>mod2.py</p> <pre><code>#import mod1 -- not necessary def show_answer(thing): print thing.answer() </code></pre> <p>Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used.</p> <p>Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?</p> <p>In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?</p> <p>I realise Python is <em>so</em> much more dynamic than C++, it's taken me a while to see how little code you actually need to write! </p> <p>I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.</p> <p>UPDATE: Thanks for all the answers, I think I should clarify my question now:</p> <p>Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?</p>
3
2009-06-22T14:35:30Z
1,027,708
<p>In fact, according to <a href="http://effbot.org/zone/import-confusion.htm" rel="nofollow">this explanation</a> , the circular <code>import</code> will not work the way you want it to work: if you uncomment <code>import mod1</code>, the second module will still not know about the <code>Universe</code>. </p> <p>I think this is quite reasonable. If both of your files need access to the type of some specific object, like <code>Universe</code>, you have several choices: </p> <ul> <li>if your program is small, just use one file</li> <li>if it's big, you need to decide if your files both need to know how <code>Universe</code> is implemented, perhaps passing an object of not-yet-known type to <code>show_answer</code> is fine</li> <li>if that doesn't work for you, by all means put <code>Universe</code> in a separate module and load it first.</li> </ul>
1
2009-06-22T15:03:16Z
[ "python", "import", "module" ]
Python - when is 'import' required?
1,027,557
<p>mod1.py</p> <pre><code>import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) </code></pre> <p>mod2.py</p> <pre><code>#import mod1 -- not necessary def show_answer(thing): print thing.answer() </code></pre> <p>Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used.</p> <p>Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?</p> <p>In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?</p> <p>I realise Python is <em>so</em> much more dynamic than C++, it's taken me a while to see how little code you actually need to write! </p> <p>I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.</p> <p>UPDATE: Thanks for all the answers, I think I should clarify my question now:</p> <p>Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?</p>
3
2009-06-22T14:35:30Z
1,027,729
<p><code>import</code> is all about names -- mostly "bare names" that are bound at top level (AKA global level, AKA module-level names) in a certain module, say <code>mod2</code>. When you've done <code>import mod2</code>, you get the <code>mod2</code> namespace as an available name (top-level in your own module, if you're doing the <code>import</code> itself as top level, as is most common; but a local <code>import</code> within a function would make <code>mod2</code> a local variable of that function, etc); and therefore you can use <code>mod2.foobar</code> to access the name <code>foobar</code> that's bound at top level in <code>mod2</code>. If you have no need to access such names, then you have no need to <code>import mod2</code> in your own module.</p>
4
2009-06-22T15:06:58Z
[ "python", "import", "module" ]
Python - when is 'import' required?
1,027,557
<p>mod1.py</p> <pre><code>import mod2 class Universe: def __init__(self): pass def answer(self): return 42 u = Universe() mod2.show_answer(u) </code></pre> <p>mod2.py</p> <pre><code>#import mod1 -- not necessary def show_answer(thing): print thing.answer() </code></pre> <p>Coming from a C++ background I had the feeling it was necessary to import the module containing the Universe class definition before the show_answer function would work. I.e. everything had to be declared before it could be used.</p> <p>Am I right in thinking this isn't necessary? This is duck typing, right? So if an import isn't required to see the methods of a class, I'd at least need it for the class definition itself and the top level functions of a module?</p> <p>In one script I've written, I even went as far as writing a base class to declare an interface with a set of methods, and then deriving concrete classes to inherit that interface, but I think I get it now - that's just wrong in Python, and whether an object has a particular method is checked at runtime at the point where the call is made?</p> <p>I realise Python is <em>so</em> much more dynamic than C++, it's taken me a while to see how little code you actually need to write! </p> <p>I think I know the answer to this question, but I just wanted to get clarification and make sure I was on the right track.</p> <p>UPDATE: Thanks for all the answers, I think I should clarify my question now:</p> <p>Does mod2.show_answer() need an import (of any description) to know that thing has a method called answer(), or is that determined dynamically at runtime?</p>
3
2009-06-22T14:35:30Z
1,028,100
<p>I don't know much about C++, so can't directly compare it, but..</p> <p><code>import</code> basically loads the other Python script (<code>mod2.py</code>) into the current script (the top level of <code>mod1.py</code>). It's not so much a link, it's closer to an <code>eval</code></p> <p>For example, in Python'ish psuedo-code:</p> <pre><code>eval("mod2.py") </code></pre> <p>is the same as..</p> <pre><code>from mod2 import * </code></pre> <p>..it executes mod2.py, and makes the functions/classes defined accessible in the current script.</p> <p>Both above snippets would allow you to call <code>show_answer()</code> (well, eval doesn't quite work like that, thus I called it pseudo code!)</p> <pre><code>import mod2 </code></pre> <p>..is basically the same, but instead of bringing in all the functions into the "top level", it brings them into the mod2 module, so you call <code>show_answer</code> by doing..</p> <pre><code>mod2.show_answer </code></pre> <blockquote> <p>Am I right in thinking [the import in mod2.py] isn't necessary?</p> </blockquote> <p>Absolutely. In fact if you try and import <code>mod1</code> from <code>mod2</code> you get a circular dependancy error (since <code>mod2</code> then tries to import <code>mod1</code> and so on..)</p>
1
2009-06-22T16:19:12Z
[ "python", "import", "module" ]
How to execute a file within the python interpreter?
1,027,714
<p>I'm trying to execute a file with python commands from within the interpreter. </p> <p>EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.</p>
132
2009-06-22T15:05:00Z
1,027,730
<pre><code>&gt;&gt;&gt; execfile('filename.py') </code></pre> <p>See <a href="http://docs.python.org/library/functions.html#execfile">the documentation</a>. If you are using Python 3.0, see <a href="http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0">this question</a>.</p> <p>See answer by @S.Lott for an example of how you access globals from filename.py after executing it.</p>
101
2009-06-22T15:07:10Z
[ "python" ]
How to execute a file within the python interpreter?
1,027,714
<p>I'm trying to execute a file with python commands from within the interpreter. </p> <p>EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.</p>
132
2009-06-22T15:05:00Z
1,027,739
<p>Several ways.</p> <p>From the shell</p> <pre><code>python someFile.py </code></pre> <p>From inside IDLE, hit <strong>F5</strong>.</p> <p>If you're typing interactively, try this.</p> <pre><code>&gt;&gt;&gt; variables= {} &gt;&gt;&gt; execfile( "someFile.py", variables ) &gt;&gt;&gt; print variables # globals from the someFile module </code></pre>
144
2009-06-22T15:08:38Z
[ "python" ]
How to execute a file within the python interpreter?
1,027,714
<p>I'm trying to execute a file with python commands from within the interpreter. </p> <p>EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.</p>
132
2009-06-22T15:05:00Z
1,028,096
<blockquote> <p>I'm trying to use variables and settings from that file, not to invoke a separate process.</p> </blockquote> <p>Well, simply importing the file with <code>import filename</code> (minus .py, needs to be in the same directory or on your <code>PYTHONPATH</code>) will run the file, making its variables, functions, classes, etc. available in the <code>filename.variable</code> namespace.</p> <p>So if you have <code>cheddar.py</code> with the variable spam and the function eggs – you can import them with <code>import cheddar</code>, access the variable with <code>cheddar.spam</code> and run the function by calling <code>cheddar.eggs()</code></p> <p>If you have code in <code>cheddar.py</code> that is outside a function, it will be run immediately, but building applications that runs stuff on import is going to make it hard to reuse your code. If a all possible, put everything inside functions or classes.</p>
20
2009-06-22T16:18:11Z
[ "python" ]
How to execute a file within the python interpreter?
1,027,714
<p>I'm trying to execute a file with python commands from within the interpreter. </p> <p>EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.</p>
132
2009-06-22T15:05:00Z
20,010,963
<p>I am not an expert but this is what I noticed:</p> <p>if your code is mycode.py for instance, and you type just 'import mycode', Python will execute it but it will not make all your variables available to the interpreter. I found that you should type actually 'from mycode import *' if you want to make all variables available to the interpreter. </p>
7
2013-11-15T21:31:19Z
[ "python" ]
How to execute a file within the python interpreter?
1,027,714
<p>I'm trying to execute a file with python commands from within the interpreter. </p> <p>EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.</p>
132
2009-06-22T15:05:00Z
31,566,843
<h2>Python 2 + Python 3</h2> <pre><code>exec(open("./path/to/script.py").read(), globals()) </code></pre> <p>This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most other languages).</p> <p><a href="https://docs.python.org/3/library/functions.html#exec">Python 3 <code>exec</code> Documentation</a></p>
21
2015-07-22T14:58:25Z
[ "python" ]
How to execute a file within the python interpreter?
1,027,714
<p>I'm trying to execute a file with python commands from within the interpreter. </p> <p>EDIT: I'm trying to use variables and settings from that file, not to invoke a separate process.</p>
132
2009-06-22T15:05:00Z
36,311,203
<p>For python3 use either with <code>xxxx = name</code> of <code>yourfile</code>. </p> <pre><code>exec(open('./xxxx.py').read()) </code></pre>
-1
2016-03-30T14:03:39Z
[ "python" ]
MySQLdb through proxy
1,027,751
<p>I'm using the above mentioned Python lib to connect to a MySQL server. So far I've worked locally and all worked fine, until i realized I'll have to use my program in a network where all access goes through a proxy.</p> <p>Does anyone now how I can set the connections managed by that lib to use a proxy? Alternatively: do you know of another Python lib for MySQL that can handle this?</p> <p>I also have no idea if the if the proxy server will allow access to the standard MySQL port or how I can trick it to allow it. Help on this is also welcomed.</p>
2
2009-06-22T15:11:05Z
1,027,780
<p>Do you have to do anything special to connect through a proxy?</p> <p>I would guess you just supply the correct parameters to the <code>connect</code> function. From <a href="http://mysql-python.sourceforge.net/MySQLdb.html#id8" rel="nofollow">the documentation</a>, it looks as if you can specify the host name and port number with an arguments to <code>connect</code>.</p> <p>Like this:</p> <pre><code>connection = connect(host="dbserver.somewhere.com", port=nnnn) # etc.. </code></pre>
0
2009-06-22T15:16:54Z
[ "python", "mysql", "proxy" ]
MySQLdb through proxy
1,027,751
<p>I'm using the above mentioned Python lib to connect to a MySQL server. So far I've worked locally and all worked fine, until i realized I'll have to use my program in a network where all access goes through a proxy.</p> <p>Does anyone now how I can set the connections managed by that lib to use a proxy? Alternatively: do you know of another Python lib for MySQL that can handle this?</p> <p>I also have no idea if the if the proxy server will allow access to the standard MySQL port or how I can trick it to allow it. Help on this is also welcomed.</p>
2
2009-06-22T15:11:05Z
1,027,784
<p>I use <a href="http://www.ssh.com/support/documentation/online/ssh/winhelp/32/Tunneling%5FExplained.html" rel="nofollow">ssh tunneling</a> for that kind of issues. For example I am developing an application that connects to an oracle db.</p> <p>In my code I write to connect to localhost and then from a shell I do:</p> <pre><code>ssh -L1521:localhost:1521 user@server.com </code></pre> <p>If you are in windows you can use <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/" rel="nofollow">PuTTY</a></p>
2
2009-06-22T15:17:01Z
[ "python", "mysql", "proxy" ]
MySQLdb through proxy
1,027,751
<p>I'm using the above mentioned Python lib to connect to a MySQL server. So far I've worked locally and all worked fine, until i realized I'll have to use my program in a network where all access goes through a proxy.</p> <p>Does anyone now how I can set the connections managed by that lib to use a proxy? Alternatively: do you know of another Python lib for MySQL that can handle this?</p> <p>I also have no idea if the if the proxy server will allow access to the standard MySQL port or how I can trick it to allow it. Help on this is also welcomed.</p>
2
2009-06-22T15:11:05Z
1,027,817
<p>there are a lot of different possibilities here. the only way you're going to get a definitive answer is to talk to the person that runs the proxy.</p> <p>if this is a web app and the web server and the database serve are both on the other side of a proxy, then you won't need to connect to the mysql server at all since the web app will do it for you.</p>
1
2009-06-22T15:23:29Z
[ "python", "mysql", "proxy" ]
Detect if X11 is available (python)
1,027,894
<p>Firstly, what is the best/simplest way to detect if X11 is running and available for a python script.</p> <p>parent process?<br /> session leader?<br /> X environment variables?<br /> other? </p> <p>Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command line backed tool.</p> <p>Off the top of my head I thought of this</p> <p>-main python script (detects if gui is available and launches appropriate script)<br /> -gui or command line python script starts<br /> -both use a generic module to do actual work </p> <p>I am very open to suggestions to simplify this. </p>
4
2009-06-22T15:38:45Z
1,027,907
<p>I'd check to see if DISPLAY is set ( this is what C API X11 applications do after all ). </p>
8
2009-06-22T15:41:25Z
[ "python", "user-interface" ]
Detect if X11 is available (python)
1,027,894
<p>Firstly, what is the best/simplest way to detect if X11 is running and available for a python script.</p> <p>parent process?<br /> session leader?<br /> X environment variables?<br /> other? </p> <p>Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command line backed tool.</p> <p>Off the top of my head I thought of this</p> <p>-main python script (detects if gui is available and launches appropriate script)<br /> -gui or command line python script starts<br /> -both use a generic module to do actual work </p> <p>I am very open to suggestions to simplify this. </p>
4
2009-06-22T15:38:45Z
1,027,918
<p>You could simply launch the gui part, and catch the exception it raises when X (or any other platform dependent graphics system is not available.</p> <p>Make sure you really have an interactive terminal before running the text based part. Your process might have been started without a visible terminal, as is common in graphical user environments like KDE, gnome or windows.</p>
4
2009-06-22T15:42:38Z
[ "python", "user-interface" ]
Detect if X11 is available (python)
1,027,894
<p>Firstly, what is the best/simplest way to detect if X11 is running and available for a python script.</p> <p>parent process?<br /> session leader?<br /> X environment variables?<br /> other? </p> <p>Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command line backed tool.</p> <p>Off the top of my head I thought of this</p> <p>-main python script (detects if gui is available and launches appropriate script)<br /> -gui or command line python script starts<br /> -both use a generic module to do actual work </p> <p>I am very open to suggestions to simplify this. </p>
4
2009-06-22T15:38:45Z
1,027,942
<p>Check the return code of <code>xset -q</code>:</p> <pre><code>def X_is_running(): from subprocess import Popen, PIPE p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE) p.communicate() return p.returncode == 0 </code></pre> <p>As for the second part of your question, I suggest the following <code>main.py</code> structure:</p> <pre><code>import common_lib def gui_main(): ... def cli_main(): ... def X_is_running(): ... if __name__ == '__main__': if X_is_running(): gui_main() else: cli_main() </code></pre>
5
2009-06-22T15:48:28Z
[ "python", "user-interface" ]
Is python a stable platform for facebook development?
1,027,990
<p>I'm trying to build my first facebook app, and it seems that the python facebook (<a href="http://code.google.com/p/pyfacebook/" rel="nofollow">pyfacebook</a>) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.</p> <p>Are there any mature python frontends for facebook? If not, what's the best language for facebook development?</p>
7
2009-06-22T15:57:26Z
1,028,027
<p>The updated location of pyfacebook is <a href="http://github.com/sciyoshi/pyfacebook/tree/master" rel="nofollow">on github</a>. Plus, as <a href="http://arstechnica.com/open-source/news/2009/04/how-to-using-the-new-facebook-stream-api-in-a-desktop-app.ars" rel="nofollow">arstechnica</a> well explains:</p> <blockquote> <p>PyFacebook is also very easy to extend when new Facebook API methods are introduced. Each Facebook API method is described in the PyFacebook library using a simple data structure that specifies the method's name and parameter types.</p> </blockquote> <p>so, even should you be using a pyfacebook version that doesn't yet implement some brand-new thing you need, it's easy to add said thing, as Ryan Paul shows <a href="http://bazaar.launchpad.net/~segphault/gwibber/template-facebook-stream/revision/289#gwibber/microblog/support/facelib.py" rel="nofollow">here</a> regarding some of the stream functions (back in April right after they were launched).</p>
13
2009-06-22T16:04:39Z
[ "python", "api", "facebook" ]
Is python a stable platform for facebook development?
1,027,990
<p>I'm trying to build my first facebook app, and it seems that the python facebook (<a href="http://code.google.com/p/pyfacebook/" rel="nofollow">pyfacebook</a>) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.</p> <p>Are there any mature python frontends for facebook? If not, what's the best language for facebook development?</p>
7
2009-06-22T15:57:26Z
1,028,032
<p>Try <a href="http://github.com/sciyoshi/pyfacebook/tree/master" rel="nofollow">this site</a> instead.</p> <p>It's pyfacebooks site on GitHub. The one you have is outdated.</p>
4
2009-06-22T16:05:01Z
[ "python", "api", "facebook" ]
Is python a stable platform for facebook development?
1,027,990
<p>I'm trying to build my first facebook app, and it seems that the python facebook (<a href="http://code.google.com/p/pyfacebook/" rel="nofollow">pyfacebook</a>) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.</p> <p>Are there any mature python frontends for facebook? If not, what's the best language for facebook development?</p>
7
2009-06-22T15:57:26Z
1,028,325
<p>If you're a facebook newbie, I'd suggest doing your first couple of apps in PHP. Facebook is written in PHP, the APIs are really designed around PHP (although they are language-neutral, theoretically.) The latest API support and most of the sample code is always in PHP.</p> <p>Once you get the hang of it, you can definitely write FB apps in other languages, including Python, Actionscript, etc. But my experience with other platforms is that they never work "out of the box" with Facebook the way PHP does.</p> <p>This is nothing against python! I like the language alot.</p>
3
2009-06-22T16:57:17Z
[ "python", "api", "facebook" ]
Is python a stable platform for facebook development?
1,027,990
<p>I'm trying to build my first facebook app, and it seems that the python facebook (<a href="http://code.google.com/p/pyfacebook/" rel="nofollow">pyfacebook</a>) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented.</p> <p>Are there any mature python frontends for facebook? If not, what's the best language for facebook development?</p>
7
2009-06-22T15:57:26Z
4,034,156
<p>Facebook's own Python-SDK covers the newer Graph API now:</p> <p><a href="http://github.com/facebook/python-sdk/" rel="nofollow">http://github.com/facebook/python-sdk/</a></p>
11
2010-10-27T14:08:22Z
[ "python", "api", "facebook" ]
Conditional Django Middleware (or how to exclude the Admin System)
1,028,019
<p>I want to use some middleware I wrote across the whole of my site (large # of pages, so I chose not to use decorators as I wanted to use the code for all pages). Only issue is that I don't want to use the middleware for the admin code, and it seems to be active on them.</p> <p>Is there any way I can configure the settings.py or urls.py perhaps, or maybe something in the code to prevent it from executing on pages in the admin system?</p> <p>Any help much appreciated,</p> <p>Cheers</p> <p>Paul</p>
13
2009-06-22T16:03:21Z
1,028,350
<p>You could check the path in process_request (and any other process_*-methods in your middleware)</p> <pre><code>def process_request(self, request): if request.path.startswith('/admin/'): return None # rest of method def process_response(self, request, response): if request.path.startswith('/admin/'): return response # rest of method </code></pre>
6
2009-06-22T17:04:37Z
[ "python", "django", "django-admin", "django-middleware" ]
Conditional Django Middleware (or how to exclude the Admin System)
1,028,019
<p>I want to use some middleware I wrote across the whole of my site (large # of pages, so I chose not to use decorators as I wanted to use the code for all pages). Only issue is that I don't want to use the middleware for the admin code, and it seems to be active on them.</p> <p>Is there any way I can configure the settings.py or urls.py perhaps, or maybe something in the code to prevent it from executing on pages in the admin system?</p> <p>Any help much appreciated,</p> <p>Cheers</p> <p>Paul</p>
13
2009-06-22T16:03:21Z
1,031,698
<p>The main reason I wanted to do this was down to using an XML parser in the middleware which was messing up non-XML downloads. I have put some additional code for detecting if the code is XML and not trying to parse anything that it shouldn't.</p> <p>For other middleware where this wouldn't be convenient, I'll probably use the method piquadrat outlines above, or maybe just use a view decorator - Cheers piquadrat!</p>
0
2009-06-23T10:13:38Z
[ "python", "django", "django-admin", "django-middleware" ]
Conditional Django Middleware (or how to exclude the Admin System)
1,028,019
<p>I want to use some middleware I wrote across the whole of my site (large # of pages, so I chose not to use decorators as I wanted to use the code for all pages). Only issue is that I don't want to use the middleware for the admin code, and it seems to be active on them.</p> <p>Is there any way I can configure the settings.py or urls.py perhaps, or maybe something in the code to prevent it from executing on pages in the admin system?</p> <p>Any help much appreciated,</p> <p>Cheers</p> <p>Paul</p>
13
2009-06-22T16:03:21Z
3,204,374
<p>A general way would be (based on piquadrat's answer)</p> <pre><code>def process_request(self, request): if request.path.startswith(reverse('admin:index')): return None # rest of method </code></pre> <p>This way if someone changes <code>/admin/</code> to <code>/django_admin/</code> you are still covered. </p>
24
2010-07-08T14:04:44Z
[ "python", "django", "django-admin", "django-middleware" ]
Can I avoid handling a file twice if I need the number of lines and I need to append to the file?
1,028,122
<p>I am writing a file to disk in stages. As I write it I need to know the line numbers that I am writing to use to build an index. The file now has 12 million lines so I need to build the index on the fly. I am doing this in four steps, with four groupings of the value that I am indexing on. Based on some examples I found elsewhere on SO I decided that to keep my functions as clean as possible I would get the linesize of the file before I start writing so I can use that count to continue to build my index.</p> <p>So I have run across this problem, theoretically I don't know if I am adding the first chunk or the last chunk to my file so I thought to get the current size I would</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>When I do this the result is always 0-even if myFile exists and has a num_lines >0</p> <p>If I do this instead:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>I get the correct value iff myFile exists. byt if myFile does not exist, if I am on the first cycle, I get an error message. </p> <p>As I was writing out this question it occurred to me that the reason for the value num_lines=0 on every case the file exists is because the file is being opened for appending to so the file is opened at the last line and is now awaiting for lines to be delivered. So this fixes the problem</p> <pre><code>try: myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>My question is whether or not this can be done another way. The reason I ask is because I have to now close myFile and reopen it for appending:</p> <p>That is to do the work I need to do now that I have the ending index number for the data that is already in the file I have to </p> <pre><code>myFile.close() myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') </code></pre> <p>Now, here is where maybe I am learning something- given that I have to open the file twice then maybe getting the starting index (num_lines) should be moved to a function</p> <pre><code>def getNumbLines(myFileRef): try: myFile=open(myFileRef) num_lines=sum(1 for line in myFile) myFile.close() except IOError: num_lines=0 return num_lines </code></pre> <p>It would be cleaner if I did not have to open/handle the file twice.</p> <p>Based on Eric Wendelin's answer I can just do:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a+') num_lines=sum(1 for line in myFile) </code></pre> <p>Thanks</p>
2
2009-06-22T16:22:32Z
1,028,173
<p>Open the file for updates ('u' or 'rw', I forget). Now you can read it until EOF and then start writing to append.</p>
0
2009-06-22T16:27:51Z
[ "python", "file" ]
Can I avoid handling a file twice if I need the number of lines and I need to append to the file?
1,028,122
<p>I am writing a file to disk in stages. As I write it I need to know the line numbers that I am writing to use to build an index. The file now has 12 million lines so I need to build the index on the fly. I am doing this in four steps, with four groupings of the value that I am indexing on. Based on some examples I found elsewhere on SO I decided that to keep my functions as clean as possible I would get the linesize of the file before I start writing so I can use that count to continue to build my index.</p> <p>So I have run across this problem, theoretically I don't know if I am adding the first chunk or the last chunk to my file so I thought to get the current size I would</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>When I do this the result is always 0-even if myFile exists and has a num_lines >0</p> <p>If I do this instead:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>I get the correct value iff myFile exists. byt if myFile does not exist, if I am on the first cycle, I get an error message. </p> <p>As I was writing out this question it occurred to me that the reason for the value num_lines=0 on every case the file exists is because the file is being opened for appending to so the file is opened at the last line and is now awaiting for lines to be delivered. So this fixes the problem</p> <pre><code>try: myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>My question is whether or not this can be done another way. The reason I ask is because I have to now close myFile and reopen it for appending:</p> <p>That is to do the work I need to do now that I have the ending index number for the data that is already in the file I have to </p> <pre><code>myFile.close() myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') </code></pre> <p>Now, here is where maybe I am learning something- given that I have to open the file twice then maybe getting the starting index (num_lines) should be moved to a function</p> <pre><code>def getNumbLines(myFileRef): try: myFile=open(myFileRef) num_lines=sum(1 for line in myFile) myFile.close() except IOError: num_lines=0 return num_lines </code></pre> <p>It would be cleaner if I did not have to open/handle the file twice.</p> <p>Based on Eric Wendelin's answer I can just do:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a+') num_lines=sum(1 for line in myFile) </code></pre> <p>Thanks</p>
2
2009-06-22T16:22:32Z
1,028,189
<p>You can open a file for reading AND writing:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','r+') </code></pre> <p>Try that.</p> <p><strong>UPDATE: Ah, my mistake since the file might not exist. Use 'a+' instead of 'r+'.</strong></p>
4
2009-06-22T16:30:35Z
[ "python", "file" ]
Can I avoid handling a file twice if I need the number of lines and I need to append to the file?
1,028,122
<p>I am writing a file to disk in stages. As I write it I need to know the line numbers that I am writing to use to build an index. The file now has 12 million lines so I need to build the index on the fly. I am doing this in four steps, with four groupings of the value that I am indexing on. Based on some examples I found elsewhere on SO I decided that to keep my functions as clean as possible I would get the linesize of the file before I start writing so I can use that count to continue to build my index.</p> <p>So I have run across this problem, theoretically I don't know if I am adding the first chunk or the last chunk to my file so I thought to get the current size I would</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>When I do this the result is always 0-even if myFile exists and has a num_lines >0</p> <p>If I do this instead:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>I get the correct value iff myFile exists. byt if myFile does not exist, if I am on the first cycle, I get an error message. </p> <p>As I was writing out this question it occurred to me that the reason for the value num_lines=0 on every case the file exists is because the file is being opened for appending to so the file is opened at the last line and is now awaiting for lines to be delivered. So this fixes the problem</p> <pre><code>try: myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>My question is whether or not this can be done another way. The reason I ask is because I have to now close myFile and reopen it for appending:</p> <p>That is to do the work I need to do now that I have the ending index number for the data that is already in the file I have to </p> <pre><code>myFile.close() myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') </code></pre> <p>Now, here is where maybe I am learning something- given that I have to open the file twice then maybe getting the starting index (num_lines) should be moved to a function</p> <pre><code>def getNumbLines(myFileRef): try: myFile=open(myFileRef) num_lines=sum(1 for line in myFile) myFile.close() except IOError: num_lines=0 return num_lines </code></pre> <p>It would be cleaner if I did not have to open/handle the file twice.</p> <p>Based on Eric Wendelin's answer I can just do:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a+') num_lines=sum(1 for line in myFile) </code></pre> <p>Thanks</p>
2
2009-06-22T16:22:32Z
1,028,339
<p>I assume you are writing the file, in that case why don't you maintain a separate track of how many lines you have already written? to me it looks very wasteful that you have to read whole file line by line just to get line number.</p>
0
2009-06-22T17:00:37Z
[ "python", "file" ]
Can I avoid handling a file twice if I need the number of lines and I need to append to the file?
1,028,122
<p>I am writing a file to disk in stages. As I write it I need to know the line numbers that I am writing to use to build an index. The file now has 12 million lines so I need to build the index on the fly. I am doing this in four steps, with four groupings of the value that I am indexing on. Based on some examples I found elsewhere on SO I decided that to keep my functions as clean as possible I would get the linesize of the file before I start writing so I can use that count to continue to build my index.</p> <p>So I have run across this problem, theoretically I don't know if I am adding the first chunk or the last chunk to my file so I thought to get the current size I would</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>When I do this the result is always 0-even if myFile exists and has a num_lines >0</p> <p>If I do this instead:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') try: num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>I get the correct value iff myFile exists. byt if myFile does not exist, if I am on the first cycle, I get an error message. </p> <p>As I was writing out this question it occurred to me that the reason for the value num_lines=0 on every case the file exists is because the file is being opened for appending to so the file is opened at the last line and is now awaiting for lines to be delivered. So this fixes the problem</p> <pre><code>try: myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt') num_lines=sum(1 for line in myFile) except IOError: num_lines=0 </code></pre> <p>My question is whether or not this can be done another way. The reason I ask is because I have to now close myFile and reopen it for appending:</p> <p>That is to do the work I need to do now that I have the ending index number for the data that is already in the file I have to </p> <pre><code>myFile.close() myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a') </code></pre> <p>Now, here is where maybe I am learning something- given that I have to open the file twice then maybe getting the starting index (num_lines) should be moved to a function</p> <pre><code>def getNumbLines(myFileRef): try: myFile=open(myFileRef) num_lines=sum(1 for line in myFile) myFile.close() except IOError: num_lines=0 return num_lines </code></pre> <p>It would be cleaner if I did not have to open/handle the file twice.</p> <p>Based on Eric Wendelin's answer I can just do:</p> <pre><code>myFile=open(r'C:\NEWMASTERLIST\FULLLIST.txt','a+') num_lines=sum(1 for line in myFile) </code></pre> <p>Thanks</p>
2
2009-06-22T16:22:32Z
1,029,764
<p>A bit late to the party but for the file existing problem why not use (Psuedocode):</p> <pre><code>If FileExists(C:\NEWMASTERLIST\FULLLIST.txt') then begin Open file etc Calc numlines etc end else Create new file etc NumLines := 0; end; </code></pre>
0
2009-06-22T22:42:49Z
[ "python", "file" ]