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
listlengths
1
5
Python classes -- mutability
1,355,555
<p>Im having a problem with python.. I have a binary tree node type:</p> <pre><code>class NODE: element = 0 leftchild = None rightchild = None </code></pre> <p>And I had to implement a function deletemin:</p> <pre><code>def DELETEMIN( A ): if A.leftchild == None: retval = A.element A = A.rightchild return retval else: return DELETEMIN( A.leftchild ) </code></pre> <p>Yet, when I try to test this on the binary tree:</p> <pre><code> 1 / \ 0 2 </code></pre> <p>It should delete 0, by just setting it to null but instead, i get this:</p> <pre><code> 0 / \ 0 2 </code></pre> <p>Why can I not nullify a node within a function in python? Is their a way to do this? </p>
1
2009-08-31T02:26:42Z
1,355,636
<pre><code>class Node: element = 0; left_child = None right_child = None def delete_min( A ): if A.left_child is None: return A.right_child else: A.left_child = delete_min(A.left_child) return A tree = delete_min(tree) </code></pre>
0
2009-08-31T03:05:34Z
[ "python", "class" ]
How does this Python code work?
1,355,710
<p>I don't know if it is feasable to paste all of the code here but I am looking at the code in <a href="http://github.com/cloudkick/libcloud/tree/master" rel="nofollow">this git repo</a>.</p> <p>If you look at the example they do: </p> <pre><code>ec2 = EC2('access key id', 'secret key') </code></pre> <p>...but there is no EC2 class. However, it looks like in libcloud\providers.py there is a dict that maps the EC2 to the EC2NodeDriver found in libcloud\drivers\ec2.py. The correct mapping is calculated by get_driver(provider), but that method doesn't appear to be called anywhere.</p> <p>I am new to python, obviously, but not to programming. I'm not even sure what I should be looking up in the docs to figure this out. Thanks.</p>
0
2009-08-31T03:51:50Z
1,355,735
<p>Checking out the libcloud\examples.py might be helpful. I saw this:</p> <pre><code>from libcloud.drivers import EC2, Slicehost, Rackspace </code></pre> <p>The python 'import' statement brings in the class from other python module, in this case from the libcloud.drivers module.</p>
0
2009-08-31T04:04:27Z
[ "python", "code-review" ]
How does this Python code work?
1,355,710
<p>I don't know if it is feasable to paste all of the code here but I am looking at the code in <a href="http://github.com/cloudkick/libcloud/tree/master" rel="nofollow">this git repo</a>.</p> <p>If you look at the example they do: </p> <pre><code>ec2 = EC2('access key id', 'secret key') </code></pre> <p>...but there is no EC2 class. However, it looks like in libcloud\providers.py there is a dict that maps the EC2 to the EC2NodeDriver found in libcloud\drivers\ec2.py. The correct mapping is calculated by get_driver(provider), but that method doesn't appear to be called anywhere.</p> <p>I am new to python, obviously, but not to programming. I'm not even sure what I should be looking up in the docs to figure this out. Thanks.</p>
0
2009-08-31T03:51:50Z
1,355,744
<p><code>example.py</code> includes an <code>import</code> statement that reads:</p> <pre><code>from libcloud.drivers import EC2, Slicehost, Rackspace </code></pre> <p>This means that the <code>EC2</code> class is imported from the <code>libcloud.drivers</code> module. However, in this case, <code>libcloud.drivers</code> is actually a <em>package</em> (a Python <em>package</em> contains <em>modules</em>), which means that <code>EC2</code> should be defined in a file <code>__init__.py</code> in <code>libcloud/drivers/</code>, but it's not. Which means that in this specific case, their example code is actually wrong. (I downloaded the code and got an import error when running <code>example.py</code>, and as you can see, the file <code>libcloud/drivers/__init__.py</code> does not contain any definitions at all, least of all an <code>EC2</code> definition.)</p>
5
2009-08-31T04:09:56Z
[ "python", "code-review" ]
Is there a stable integration procedure/pluggin for Django 1.1 and Google app engine?
1,355,813
<p>What is the best procedure/plugging to use to integrate django and google app engine? I have read many articles in the internet and seen videos on how to go round this. Am still left wondering which is the best procedure to use. </p> <p>Is there an official procedure documented in django or google app engine. Examples and site references will really help.</p> <p>Am using Python 2.6, Django 1.1</p> <p>Gath</p>
1
2009-08-31T04:41:00Z
1,355,859
<p>There is NO way you can run Python 2.6 on App Engine: it's 2.5 only.</p> <p>If you're rarin' to have Django 1.1 (with Python 2.5), I suggest <a href="http://code.google.com/p/app-engine-patch/" rel="nofollow">app-engine patch</a> which now supports it (it's a release candidate, not a final release, but close). I find their docs good and thorough, and their code well written and solid.</p>
3
2009-08-31T05:01:49Z
[ "python", "django", "google-app-engine" ]
Creating GUI with Python in Linux
1,355,918
<p>Quick question.</p> <p>I'm using Linux and I want to try making a GUI with Python. I've heard about something like Qt, GTK+ and PyGTK but I don't know what they are exactly and what the difference between them is.</p> <p>Is there any difference on how they work with different DEs like GNOME, KDE, XFCE etc.? Is there any IDE that allows you to create GUI like Microsoft Visual Studio does (for C#, C, Visual Basic etc.)?</p> <p>Or should I maybe use another language other than Python to make GUI applications?</p>
11
2009-08-31T05:25:00Z
1,355,923
<p>Your first step should be <a href="http://wiki.python.org/moin/GuiProgramming" rel="nofollow">http://wiki.python.org/moin/GuiProgramming</a></p> <p>Some tool-kits integrate better in one environment over the other. For example PyQt, PyKDE (and the brand new <a href="http://www.pyside.org/" rel="nofollow">PySide</a> will play nicer in a KDE environment, while the GTK versions (including the WX-widgets) will blend better into a GNOME/XFCE desktops.</p> <p>You should look at the environment you want to target. You can go for basic portable GUI kit, or you can to a deeper integration with tour DE, like use of integrated password manager, and configuration file parsers, that are integrated in a specific DE like KDE or GNOME.</p> <p>You should also consider the dependency that your selection dictates, and what is come by default with a basic DE. For example, PyKDE in the KDE 3.X branch had a non trivial set of dependencies, while at the 4.X branch the plasma binding made the Python GUI programming dependency less of an issue.</p> <p>There are several IDE tools, in different levels of completeness and maturity. The best thing is to try one ore more, and see what best fit your needs.</p>
12
2009-08-31T05:27:14Z
[ "python", "linux", "user-interface", "gtk", "pygtk" ]
Creating GUI with Python in Linux
1,355,918
<p>Quick question.</p> <p>I'm using Linux and I want to try making a GUI with Python. I've heard about something like Qt, GTK+ and PyGTK but I don't know what they are exactly and what the difference between them is.</p> <p>Is there any difference on how they work with different DEs like GNOME, KDE, XFCE etc.? Is there any IDE that allows you to create GUI like Microsoft Visual Studio does (for C#, C, Visual Basic etc.)?</p> <p>Or should I maybe use another language other than Python to make GUI applications?</p>
11
2009-08-31T05:25:00Z
1,355,948
<p>Each desktop environment uses a specific toolkit to build it's components. For example, KDE uses Qt and GNOME uses Gtk. </p> <p>Your use of a toolkit will be dependent upon what type of desktop environment you're targeting at, and if you want to target a wide range of desktops then use a toolkit which will work on many desktop environments, like Wx widgets which will work on Linux, Mac OS and Windows. For building simple GUI applications, Tkinter will do.</p>
2
2009-08-31T05:36:38Z
[ "python", "linux", "user-interface", "gtk", "pygtk" ]
Creating GUI with Python in Linux
1,355,918
<p>Quick question.</p> <p>I'm using Linux and I want to try making a GUI with Python. I've heard about something like Qt, GTK+ and PyGTK but I don't know what they are exactly and what the difference between them is.</p> <p>Is there any difference on how they work with different DEs like GNOME, KDE, XFCE etc.? Is there any IDE that allows you to create GUI like Microsoft Visual Studio does (for C#, C, Visual Basic etc.)?</p> <p>Or should I maybe use another language other than Python to make GUI applications?</p>
11
2009-08-31T05:25:00Z
1,355,988
<p>I would avoid using another language to make a GUI for Python. </p> <p>I've had every good luck with wxwidgets, which is the python binding for WX, a cross-platform development system. It's pretty easy to learn and quite powerful. The problem with wxwidgets is that it is not installed by default, so your users will need to install it on every platform that they wish to run your application. Find more information about it at <a href="http://wxwidgets.org/" rel="nofollow">http://wxwidgets.org/</a>.</p> <p>If you want people to be able to use your program without installing anything else, use Tkinter, the GUI system that comes with Python.</p> <p>I would avoid the Python bindings for GTK or KDE unless you already know those systems. They also need to be downloaded, and they do not seem to have as much adoption as wxwidgets.</p>
4
2009-08-31T05:52:54Z
[ "python", "linux", "user-interface", "gtk", "pygtk" ]
Creating GUI with Python in Linux
1,355,918
<p>Quick question.</p> <p>I'm using Linux and I want to try making a GUI with Python. I've heard about something like Qt, GTK+ and PyGTK but I don't know what they are exactly and what the difference between them is.</p> <p>Is there any difference on how they work with different DEs like GNOME, KDE, XFCE etc.? Is there any IDE that allows you to create GUI like Microsoft Visual Studio does (for C#, C, Visual Basic etc.)?</p> <p>Or should I maybe use another language other than Python to make GUI applications?</p>
11
2009-08-31T05:25:00Z
1,358,089
<p>Use the <a href="http://glade.gnome.org/" rel="nofollow">glade UI designer</a> and pyGtk bindings... that was my first ever experience with python and there are <a href="http://www.google.com/search?q=python+glade+pygtk&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=com.ubuntu%3Aen-US%3Aunofficial&amp;client=firefox-a" rel="nofollow">lots of blog posts and tutorials to help you get started</a></p>
1
2009-08-31T15:49:40Z
[ "python", "linux", "user-interface", "gtk", "pygtk" ]
Creating GUI with Python in Linux
1,355,918
<p>Quick question.</p> <p>I'm using Linux and I want to try making a GUI with Python. I've heard about something like Qt, GTK+ and PyGTK but I don't know what they are exactly and what the difference between them is.</p> <p>Is there any difference on how they work with different DEs like GNOME, KDE, XFCE etc.? Is there any IDE that allows you to create GUI like Microsoft Visual Studio does (for C#, C, Visual Basic etc.)?</p> <p>Or should I maybe use another language other than Python to make GUI applications?</p>
11
2009-08-31T05:25:00Z
1,378,336
<p>Use PyGTK. As important as the toolkit is its underpinnings, with PyGTK you use GLib as well, with its filesystem abstractions (python module gio) that are very important for the Linux desktop, its high-level cross-desktop functions such as <a href="http://library.gnome.org/devel/pygobject/stable/glib-functions.html#function-glib--get-user-data-dir" rel="nofollow"><code>glib.get_user_data_dir()</code></a> and its other application framework tools, and GObject and its property and signals model.</p>
0
2009-09-04T10:06:26Z
[ "python", "linux", "user-interface", "gtk", "pygtk" ]
How to call super() in Python 3.0?
1,355,931
<p>I have the strangest error I have seen for a while in Python (version 3.0).</p> <p>Changing the signature of the function affects whether <code>super()</code> works, despite the fact that it takes no arguments. Can you explain why this occurs?</p> <p>Thanks,</p> <p>Chris</p> <pre><code>&gt;&gt;&gt; class tmp: ... def __new__(*args): ... super() ... &gt;&gt;&gt; tmp() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in __new__ SystemError: super(): no arguments &gt;&gt;&gt; class tmp: ... def __new__(mcl,*args): ... super() ... &gt;&gt;&gt; tmp() &gt;&gt;&gt; </code></pre>
0
2009-08-31T05:30:09Z
1,355,947
<p>python 3.0 new super is trying to dynamically make a choice for you here, read this PEP <a href="http://www.python.org/dev/peps/pep-3135/" rel="nofollow">here</a> that should explain everything.</p>
1
2009-08-31T05:36:25Z
[ "python", "python-3.x" ]
How to call super() in Python 3.0?
1,355,931
<p>I have the strangest error I have seen for a while in Python (version 3.0).</p> <p>Changing the signature of the function affects whether <code>super()</code> works, despite the fact that it takes no arguments. Can you explain why this occurs?</p> <p>Thanks,</p> <p>Chris</p> <pre><code>&gt;&gt;&gt; class tmp: ... def __new__(*args): ... super() ... &gt;&gt;&gt; tmp() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in __new__ SystemError: super(): no arguments &gt;&gt;&gt; class tmp: ... def __new__(mcl,*args): ... super() ... &gt;&gt;&gt; tmp() &gt;&gt;&gt; </code></pre>
0
2009-08-31T05:30:09Z
1,355,951
<p>As <a href="http://docs.python.org/3.1/library/functions.html?#super" rel="nofollow">the docs</a> say, "The zero argument form automatically searches the stack frame for the class (<code>__class__</code>) and the first argument." Your first example of <code>__new__</code> doesn't HAVE a first argument - it claims it can be called with zero or more arguments, so argumentless <code>super</code> is stumped. Your second example DOES have an explicit first argument, so the search in the stack frame succeeds.</p>
6
2009-08-31T05:39:08Z
[ "python", "python-3.x" ]
How do I line up text from python into columns in my terminal?
1,356,029
<p>I'm printing out some values from a script in my terminal window like this:</p> <pre><code>for i in items: print "Name: %s Price: %d" % (i.name, i.price) </code></pre> <p>How do I make these line up into columns?</p>
7
2009-08-31T06:08:43Z
1,356,065
<p>If you know the maximum lengths of data in the two columns, then you can use format qualifiers. For example if the name is at most 20 chars long and the price will fit into 10 chars, you could do</p> <pre><code>print "Name: %-20s Price: %10d" % (i.name, i.price) </code></pre> <p>This is better than using tabs as tabs won't line up in some circumstances (e.g. if one name is quite a bit longer than another).</p> <p>If some names won't fit into usable space, then you can use the <code>.</code> format qualifier to truncate the data. For example, using "%-20.20s" for the name format will truncate any longer names to fit in the 20-character column.</p>
16
2009-08-31T06:26:10Z
[ "python" ]
How do I line up text from python into columns in my terminal?
1,356,029
<p>I'm printing out some values from a script in my terminal window like this:</p> <pre><code>for i in items: print "Name: %s Price: %d" % (i.name, i.price) </code></pre> <p>How do I make these line up into columns?</p>
7
2009-08-31T06:08:43Z
1,356,087
<p>As Vinay said, use string format specifiers.</p> <p>If you don't know the maximum lengths, you can find them by making an extra pass through the list:</p> <pre><code>maxn, maxp = 0, 0 for item in items: maxn = max(maxn, len(item.name)) maxp = max(maxp, len(str(item.price))) </code></pre> <p>then use <code>'*'</code> instead of the number and provide the calculated width as an argument.</p> <pre><code>for item in items: print "Name: %-*s Price: %*d" % (maxn, item.name, maxp, item.price) </code></pre>
8
2009-08-31T06:34:58Z
[ "python" ]
How do I line up text from python into columns in my terminal?
1,356,029
<p>I'm printing out some values from a script in my terminal window like this:</p> <pre><code>for i in items: print "Name: %s Price: %d" % (i.name, i.price) </code></pre> <p>How do I make these line up into columns?</p>
7
2009-08-31T06:08:43Z
1,357,409
<p>You can also use the rjust() / ljust() methods for str objects.</p>
0
2009-08-31T13:13:08Z
[ "python" ]
file system performance testing
1,356,240
<p>I am writing a python script that will perform performance test in linux file system. so besides deadlocks, race conditions and time takes to perform an action (delete, read, write and create) what other variables/parameters should the test contain?</p>
1
2009-08-31T07:29:21Z
1,356,704
<p>Can you be a little more clear?</p> <p>I tried doing such once before using Python itself. I need time to try it out myself. I tried using time.time() to get the time since epoch. I think the time difference can suffice for file operations.</p> <p><strong>Update:</strong> Check this GSOC Idea, PSF had pledged to sponsor it <a href="http://allmydata.org/trac/tahoe/wiki/GSoCIdeas" rel="nofollow">http://allmydata.org/trac/tahoe/wiki/GSoCIdeas</a></p> <p>I am trying to read up that page to get more information.</p>
0
2009-08-31T09:46:19Z
[ "python", "filesystems", "performance-testing" ]
file system performance testing
1,356,240
<p>I am writing a python script that will perform performance test in linux file system. so besides deadlocks, race conditions and time takes to perform an action (delete, read, write and create) what other variables/parameters should the test contain?</p>
1
2009-08-31T07:29:21Z
1,356,966
<p>You might be inetersting in looking at tools like caollectd and iotop. Then again, yopu mightalso by interested in just using them instead of reinventing the wheel - as far as I see, such performance analysis is not learned in a day, and these guys invested significant amounts of time and knowledge in building these tools.</p>
0
2009-08-31T11:15:39Z
[ "python", "filesystems", "performance-testing" ]
file system performance testing
1,356,240
<p>I am writing a python script that will perform performance test in linux file system. so besides deadlocks, race conditions and time takes to perform an action (delete, read, write and create) what other variables/parameters should the test contain?</p>
1
2009-08-31T07:29:21Z
1,356,981
<p>You should try to use the softwares already present. You can use iozone for the same. For tutorial, you should refer to <a href="http://www.cyberciti.biz/tips/linux-filesystem-benchmarking-with-iozone.html" rel="nofollow">this blog post on nixcraft</a></p>
0
2009-08-31T11:19:22Z
[ "python", "filesystems", "performance-testing" ]
file system performance testing
1,356,240
<p>I am writing a python script that will perform performance test in linux file system. so besides deadlocks, race conditions and time takes to perform an action (delete, read, write and create) what other variables/parameters should the test contain?</p>
1
2009-08-31T07:29:21Z
1,356,986
<p>File system performance testing is a very complex topic. You can easily make a lots of mistakes that basically make your whole tests worthless.</p> <p>Stony Brook University and IBM Watson Labs have published an highly recommended journal paper in the "Transaction of Storage" about file system benchmarking, in which they present different benchmarks and their strong and weak points: <a href="http://portal.acm.org/citation.cfm?id=1367829.1367831" rel="nofollow">A nine year study of file system and storage benchmarking</a>.</p> <p>They give lots of advise how to design and implement a good filesystem benchmark. As I said: It is not an easy task.</p>
3
2009-08-31T11:20:46Z
[ "python", "filesystems", "performance-testing" ]
Display jpg images in python
1,356,255
<p>I am creating a simple tool to add album cover images to mp3 files in python. So far I am just working on sending a request to amazon with artist and album title, and get the resulting list, as well as finding the actual images for each result. What I want to do is to display a simple frame with a button/link for each image, and a skip/cancel button.</p> <p>I have done some googling, but I can't find examples that I can use as a base.</p> <ol> <li>I want to display the images directly from the web. Ie. using urllib to open and read the bytes into memory, rather than go via a file on disk</li> <li>I want to display the images as buttons preferably</li> </ol> <p>All examples seems to focus on working on files on disk, rather with just a buffer. The TK documentation in the python standard library doesn't seem to cover the basic Button widget. This seems like an easy task, I have just not had any luck in finding the proper documentation yet.</p>
5
2009-08-31T07:32:00Z
1,356,598
<p>you can modify <a href="http://www.daniweb.com/code/snippet622.html" rel="nofollow">this</a> using <code>urllib.urlopen()</code>. But I don't know (as I haven't tested it) if you can make this step without saving the (image) file locally. But IMHO <code>urlopen</code> returns a file handle that is usable in <code>tk.PhotoImage()</code>.</p> <p>For jpg files in PhotoImage you need <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>:</p> <pre><code>from PIL import Image, ImageTk image = Image.open("test.jpg") photo = ImageTk.PhotoImage(image) </code></pre>
3
2009-08-31T09:16:07Z
[ "python", "tkinter" ]
Display jpg images in python
1,356,255
<p>I am creating a simple tool to add album cover images to mp3 files in python. So far I am just working on sending a request to amazon with artist and album title, and get the resulting list, as well as finding the actual images for each result. What I want to do is to display a simple frame with a button/link for each image, and a skip/cancel button.</p> <p>I have done some googling, but I can't find examples that I can use as a base.</p> <ol> <li>I want to display the images directly from the web. Ie. using urllib to open and read the bytes into memory, rather than go via a file on disk</li> <li>I want to display the images as buttons preferably</li> </ol> <p>All examples seems to focus on working on files on disk, rather with just a buffer. The TK documentation in the python standard library doesn't seem to cover the basic Button widget. This seems like an easy task, I have just not had any luck in finding the proper documentation yet.</p>
5
2009-08-31T07:32:00Z
1,356,882
<p>For displaying jpgs in Python check out PIL </p>
0
2009-08-31T10:49:02Z
[ "python", "tkinter" ]
sum of two numbers coming from the command line
1,356,348
<p>I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):</p> <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print " sum is", sum </code></pre>
2
2009-08-31T08:03:31Z
1,356,353
<pre><code>su = int(a) + int(b) print("sum is %d" % su) </code></pre> <p>And you should be careful with your variable naming. <code>sum</code> shadows the built-in, it's not a good practice to do that (that is, don't name variables as built-in functions or any globally defined name).</p>
0
2009-08-31T08:06:53Z
[ "python" ]
sum of two numbers coming from the command line
1,356,348
<p>I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):</p> <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print " sum is", sum </code></pre>
2
2009-08-31T08:03:31Z
1,356,354
<p>You should do this:</p> <pre><code>import sys a, b = sys.argv[1:2] summ = int(a) + int(b) print "sum is", summ </code></pre> <p>There is no need for str() when printing an integer. But you should use int() if you want to add a and b as integers.</p>
5
2009-08-31T08:07:03Z
[ "python" ]
sum of two numbers coming from the command line
1,356,348
<p>I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):</p> <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print " sum is", sum </code></pre>
2
2009-08-31T08:03:31Z
1,356,373
<p>The error <code>list index out of range</code> means that you are trying to access a list item that is outside the bounds of the list.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; mylist = ['hello', 'world'] &gt;&gt;&gt; print mylist[2] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: list index out of range </code></pre> <p>In your case, the error comes from either <code>sys.argv[1]</code> or <code>sys.argv[2]</code>.</p> <p>Make sure you actually pass something to the program from the command line.</p>
3
2009-08-31T08:12:03Z
[ "python" ]
sum of two numbers coming from the command line
1,356,348
<p>I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):</p> <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print " sum is", sum </code></pre>
2
2009-08-31T08:03:31Z
1,356,380
<p>If your error is <em>"list index out of range"</em>, then the problem is that your <em>list</em> doesn't have enough items. Which list? The only list you're using is <strong><code>sys.argv</code></strong>, so to populate it, you need to pass more items on the command line.</p> <p>Alternatively, check for the length of the argument list with <code>len(sys.argv)</code> and prompt interactively (e.g. using <code>raw_input()</code>) to get the values if they're not in <code>sys.argv</code>.</p>
0
2009-08-31T08:12:26Z
[ "python" ]
sum of two numbers coming from the command line
1,356,348
<p>I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):</p> <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print " sum is", sum </code></pre>
2
2009-08-31T08:03:31Z
1,356,388
<p>Assuming your inputs are integers:</p> <pre><code>import sys summ = sum(map(int,sys.argv[1:]) print "sum is ", summ </code></pre> <p>or</p> <pre><code>import sys summ = sum(int(i) for i in sys.argv[1:]) print "sum is ", summ </code></pre> <p>If not, change int to float.</p> <p>The second method is probably more pythonic, but the first is a little faster in this instance.</p> <pre><code>&gt;&gt;&gt;import timeit &gt;&gt;&gt;t1 = timeit.Timer("sum(map(int,['3','5','7','9']))") &gt;&gt;&gt;t2 = timeit.Timer("sum(int(i) for i in ['3','5','7','9'])") &gt;&gt;&gt;print t1.timeit() 3.0187220573425293 &gt;&gt;&gt;print t2.timeit() 3.4699549674987793 </code></pre>
3
2009-08-31T08:15:30Z
[ "python" ]
sum of two numbers coming from the command line
1,356,348
<p>I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):</p> <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print " sum is", sum </code></pre>
2
2009-08-31T08:03:31Z
1,356,835
<p>If you wish to sum the numbers as floating points number use "float" instead of "int", like in the following snippet.</p> <pre><code>import sys try: a, b = sys.argv[1:3] print "sum is ", float(a) + float(b) except ValueError: print "please give me two numbers to sum" </code></pre> <p>Beware that floating points are different from real numbers, so that you could obtain seemingly "strange" results about which there is a wealth of documentation on the web.</p>
0
2009-08-31T10:31:14Z
[ "python" ]
sum of two numbers coming from the command line
1,356,348
<p>I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):</p> <pre><code>import sys a= sys.argv[1] b= sys.argv[2] sum=str( a+b) print " sum is", sum </code></pre>
2
2009-08-31T08:03:31Z
1,761,045
<p>Thanks to every one. I got the answer</p> <p>for i in range (1,51): if i%5==0: print i,"\n" else: print i,</p>
0
2009-11-19T05:19:32Z
[ "python" ]
Detecting case mismatch on filename in Windows (preferably using python)?
1,356,386
<p>I have some xml-configuration files that we create in a Windows environment but is deployed on Linux. These configuration files reference each other with filepaths. We've had problems with case-sensitivity and trailing spaces before, and I'd like to write a script that checks for these problems. We have Cygwin if that helps.</p> <p>Example:</p> <p>Let's say I have a reference to the file foo/bar/baz.xml, I'd do this</p> <pre><code>&lt;someTag fileref="foo/bar/baz.xml" /&gt; </code></pre> <p>Now if we by mistake do this:</p> <pre><code>&lt;someTag fileref="fOo/baR/baz.Xml " /&gt; </code></pre> <p>It will still work on Windows, but it will fail on Linux.</p> <p>What I want to do is detect these cases where the file reference in these files don't match the real file with respect to case sensitivity.</p>
4
2009-08-31T08:13:44Z
1,356,777
<p>it's hard to judge what exactly your problem is, but if you apply <a href="http://docs.python.org/library/os.path.html#os.path.normcase" rel="nofollow"><code>os.path.normcase</code></a> along with <a href="http://docs.python.org/library/stdtypes.html#str.strip" rel="nofollow"><code>str.stript</code></a> before saving your file name, it should solve all your problems.</p> <p>as I said in comment, it's not clear how are you ending up with such a mistake. However, it would be trivial to check for existing file, as long as you have some sensible convention (all file names are lower case, for example):</p> <pre><code>try: open(fname) except IOError: open(fname.lower()) </code></pre>
0
2009-08-31T10:12:25Z
[ "python", "windows", "case-sensitive" ]
Detecting case mismatch on filename in Windows (preferably using python)?
1,356,386
<p>I have some xml-configuration files that we create in a Windows environment but is deployed on Linux. These configuration files reference each other with filepaths. We've had problems with case-sensitivity and trailing spaces before, and I'd like to write a script that checks for these problems. We have Cygwin if that helps.</p> <p>Example:</p> <p>Let's say I have a reference to the file foo/bar/baz.xml, I'd do this</p> <pre><code>&lt;someTag fileref="foo/bar/baz.xml" /&gt; </code></pre> <p>Now if we by mistake do this:</p> <pre><code>&lt;someTag fileref="fOo/baR/baz.Xml " /&gt; </code></pre> <p>It will still work on Windows, but it will fail on Linux.</p> <p>What I want to do is detect these cases where the file reference in these files don't match the real file with respect to case sensitivity.</p>
4
2009-08-31T08:13:44Z
1,357,817
<p><a href="http://docs.python.org/library/os.html#os.listdir" rel="nofollow">os.listdir</a> on a directory, in all case-preserving filesystems (including those on Windows), returns the actual case for the filenames in the directory you're listing.</p> <p>So you need to do this check at each level of the path:</p> <pre><code>def onelevelok(parent, thislevel): for fn in os.listdir(parent): if fn.lower() == thislevel.lower(): return fn == thislevel raise ValueError('No %r in dir %r!' % ( thislevel, parent)) </code></pre> <p>where I'm assuming that the complete absence of any case variation of a name is a different kind of error, and using an exception for that; and, for the whole path (assuming no drive letters or UNC that wouldn't translate to Windows anyway):</p> <pre><code>def allpathok(path): levels = os.path.split(path) if os.path.isabs(path): top = ['/'] else: top = ['.'] return all(onelevelok(p, t) for p, t in zip(top+levels, levels)) </code></pre> <p>You may need to adapt this if , e.g., <code>foo/bar</code> is not to be taken to mean that <code>foo</code> is in the current directory, but somewhere else; or, of course, if UNC or drive letters are in fact needed (but as I mentioned translating them to Linux is not trivial anyway;-).</p> <p>Implementation notes: I'm taking advantage of the fact that <code>zip</code> just drop "extra entries" beyond the length of the shortest of the sequences it's zipping; so I don't need to explicitly slice off the "leaf" (last entry) from <code>levels</code> in the first argument, <code>zip</code> does it for me. <code>all</code> will short circuit where it can, returning <code>False</code> as soon as it detects a false value, so it's just as good as an explicit loop but faster and more concise.</p>
3
2009-08-31T14:45:10Z
[ "python", "windows", "case-sensitive" ]
How to Extract the key from unnecessary Html Wrapping in python
1,356,705
<p>The HTML page containing the key and some \n character .I need to use only key block i.e from -----BEGIN PGP PUBLIC KEY BLOCK----- to -----END PGP PUBLIC KEY BLOCK----- and after putting extracting key in a file can i pass it in any function.... </p>
1
2009-08-31T09:46:29Z
1,356,737
<p>in it's simpliest form</p> <pre><code>import re clean = re.sub("&lt;/?[^\W].{0,10}?&gt;|\n|\r\n", "", your_html) #remove tags and newlines key = re.search(r'BEGIN PGP PUBLIC KEY BLOCK.+?END PGP PUBLIC KEY BLOCK', clean) </code></pre> <p>or if you don't need <code>BEGIN PGP ... BLOCK</code> and <code>END PGP ... BLOCK</code>:</p> <pre><code>key = re.search(r'BEGIN PGP PUBLIC KEY BLOCK----(.+?)----END PGP PUBLIC KEY BLOCK',clean) </code></pre> <p>is this what you're after? (I don't have python right here to check it, but I hope it's OK)</p>
0
2009-08-31T09:57:49Z
[ "python" ]
Django : save a new value in a ManyToManyField
1,356,761
<p>I gave details on my code : I don't know why my table is empty (it seems that it was empty out after calling <code>save_model</code>, but I'm not sure).</p> <pre><code>class PostAdmin(admin.ModelAdmin): def save_model(self, request, post, form, change): post.save() # Authors must be saved after saving post print form.cleaned_data['authors'] # [] print request.user # pg authors = form.cleaned_data['authors'] or request.user print authors # pg post.authors.add(authors) print post.authors.all() # [&lt;User: pg&gt;] # But on a shell, table is empty. WTF ?! : # select * from journal_post_authors; # Empty set (0.00 sec) </code></pre>
0
2009-08-31T10:06:54Z
1,356,863
<p>You need to save the post again, after the post.authors.add(authors). </p>
2
2009-08-31T10:43:53Z
[ "python", "django", "save", "add", "manytomanyfield" ]
Django : save a new value in a ManyToManyField
1,356,761
<p>I gave details on my code : I don't know why my table is empty (it seems that it was empty out after calling <code>save_model</code>, but I'm not sure).</p> <pre><code>class PostAdmin(admin.ModelAdmin): def save_model(self, request, post, form, change): post.save() # Authors must be saved after saving post print form.cleaned_data['authors'] # [] print request.user # pg authors = form.cleaned_data['authors'] or request.user print authors # pg post.authors.add(authors) print post.authors.all() # [&lt;User: pg&gt;] # But on a shell, table is empty. WTF ?! : # select * from journal_post_authors; # Empty set (0.00 sec) </code></pre>
0
2009-08-31T10:06:54Z
1,357,836
<p>I don't know what kind of field you're using, but shouldn't there be one of these in there somewhere? (or something similar)</p> <pre><code>author = form.cleaned_data['authors'] User.objects.get(id=author) </code></pre>
0
2009-08-31T14:48:46Z
[ "python", "django", "save", "add", "manytomanyfield" ]
Django : save a new value in a ManyToManyField
1,356,761
<p>I gave details on my code : I don't know why my table is empty (it seems that it was empty out after calling <code>save_model</code>, but I'm not sure).</p> <pre><code>class PostAdmin(admin.ModelAdmin): def save_model(self, request, post, form, change): post.save() # Authors must be saved after saving post print form.cleaned_data['authors'] # [] print request.user # pg authors = form.cleaned_data['authors'] or request.user print authors # pg post.authors.add(authors) print post.authors.all() # [&lt;User: pg&gt;] # But on a shell, table is empty. WTF ?! : # select * from journal_post_authors; # Empty set (0.00 sec) </code></pre>
0
2009-08-31T10:06:54Z
1,362,907
<p>I found the solution. I've just changed the value in cleaned_data and it works :</p> <pre><code>if not form.cleaned_data['authors']: form.cleaned_data['authors'] = [request.user] </code></pre> <p>Thank for helping me. :)</p>
1
2009-09-01T14:51:30Z
[ "python", "django", "save", "add", "manytomanyfield" ]
Can I write a screencapture in Python
1,357,564
<ul> <li>Are there any libraries to that can be used to write a screen capture in Python.</li> <li>Can it be made to be cross-platform?</li> <li>Is it possible to capture to video? And if could that be in real-time?</li> <li>Or would it be possible to directly generate flash movies?</li> </ul>
15
2009-08-31T13:51:29Z
1,357,573
<p>I don't know of any general purpose libraries. I did this for windows and used some <a href="http://www.google.com/search?rlz=1C1CHMB%5FenUS325US325&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=codeproject.com+screen+capture" rel="nofollow">codeproject.com</a> code in a DLL, called from ctypes.</p> <p>Video capture is probably harder; I took screenshots really fast using the trivial codeproject way and got maybe 8fps. If that's not sufficient you are probably going to need a library that is optimized to your use case; e.g. <a href="http://www.tightvnc.com/" rel="nofollow">tightVNC</a> or <a href="http://camstudio.org/" rel="nofollow">CamStudio</a> or something. CamStudio can export flash and is OSS.</p>
2
2009-08-31T13:53:13Z
[ "python", "flash" ]
Can I write a screencapture in Python
1,357,564
<ul> <li>Are there any libraries to that can be used to write a screen capture in Python.</li> <li>Can it be made to be cross-platform?</li> <li>Is it possible to capture to video? And if could that be in real-time?</li> <li>Or would it be possible to directly generate flash movies?</li> </ul>
15
2009-08-31T13:51:29Z
1,357,898
<p>screen capture can be done with <a href="http://www.pythonware.com/library/pil/handbook/imagegrab.htm" rel="nofollow">PIL thanks to the ImageGrab module</a></p> <p>For generating Flash movies, you can have a look at <a href="http://www.libming.net/FrontPage" rel="nofollow">ming</a>. I am not sure that it has this capability but it worths a look.</p>
3
2009-08-31T15:02:06Z
[ "python", "flash" ]
Can I write a screencapture in Python
1,357,564
<ul> <li>Are there any libraries to that can be used to write a screen capture in Python.</li> <li>Can it be made to be cross-platform?</li> <li>Is it possible to capture to video? And if could that be in real-time?</li> <li>Or would it be possible to directly generate flash movies?</li> </ul>
15
2009-08-31T13:51:29Z
1,358,093
<p>One way to capture a video of the user's screen (certainly for X11, not sure about Windows) is to use gstreamer with the <a href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-good-plugins/html/gst-plugins-good-plugins-ximagesrc.html" rel="nofollow">ximagesrc plugin</a>. There are Python bindings available <a href="http://pygstdocs.berlios.de/" rel="nofollow">here</a>, though I haven't used gst-python before. I know <a href="http://live.gnome.org/Istanbul" rel="nofollow">Istanbul</a>, an open source screencasting app, uses it - viewing its source might help you. </p> <p>To capture static images, I've used PyGTK before on Linux to capture the user's screen. This should also work on Windows and Mac, though I haven't tried it. Here's a small snippet:</p> <pre><code>import gtk win = gtk.gdk.get_root_window() width, height = win.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height) pb = pb.get_from_drawable(window, window.get_colormap(), 0, 0, 0, 0, width, height) pb.save('path to file', 'png') </code></pre> <p><a href="http://www.pygtk.org/docs/pygtk/class-gtkwindow.html" rel="nofollow">See the GTK docs</a> for more info. </p> <p>Hope that helps!</p>
1
2009-08-31T15:51:17Z
[ "python", "flash" ]
Can I write a screencapture in Python
1,357,564
<ul> <li>Are there any libraries to that can be used to write a screen capture in Python.</li> <li>Can it be made to be cross-platform?</li> <li>Is it possible to capture to video? And if could that be in real-time?</li> <li>Or would it be possible to directly generate flash movies?</li> </ul>
15
2009-08-31T13:51:29Z
1,523,752
<p>you can try this also may be this <a href="http://pypi.python.org/pypi/castro/1.0.4" rel="nofollow">URL</a> can help you out.</p> <p>its castro !!! see the sample code below may be useful....</p> <pre><code>&gt;&gt;&gt; from castro import Castro &gt;&gt;&gt; c = Castro() &gt;&gt;&gt; c.start() &gt;&gt;&gt; # Do something awesome! &gt;&gt;&gt; c.stop() </code></pre>
3
2009-10-06T05:29:27Z
[ "python", "flash" ]
Can I write a screencapture in Python
1,357,564
<ul> <li>Are there any libraries to that can be used to write a screen capture in Python.</li> <li>Can it be made to be cross-platform?</li> <li>Is it possible to capture to video? And if could that be in real-time?</li> <li>Or would it be possible to directly generate flash movies?</li> </ul>
15
2009-08-31T13:51:29Z
6,247,532
<p>I've written a cross-platform screen capture tool in wxPython. See download "GeneralScreenShotWX.py" in subtopic "A Flexible Screen Capture App" under topic "WorkingWithImages" @ <a href="http://wiki.wxpython.org/WorkingWithImages#A_Flexible_Screen_Capture_App" rel="nofollow">http://wiki.wxpython.org/WorkingWithImages#A_Flexible_Screen_Capture_App</a>.</p> <p>It's working on MSW, OS X and one Linux distro and requires no extra wxPython packages.</p>
2
2011-06-06T03:28:44Z
[ "python", "flash" ]
Can I write a screencapture in Python
1,357,564
<ul> <li>Are there any libraries to that can be used to write a screen capture in Python.</li> <li>Can it be made to be cross-platform?</li> <li>Is it possible to capture to video? And if could that be in real-time?</li> <li>Or would it be possible to directly generate flash movies?</li> </ul>
15
2009-08-31T13:51:29Z
10,727,134
<p>I guess all possible ways to take Python controlled screenshots are covered at <a href="https://github.com/ponty/pyscreenshot" rel="nofollow">https://github.com/ponty/pyscreenshot</a></p>
0
2012-05-23T20:12:21Z
[ "python", "flash" ]
pytz utc conversion
1,357,711
<p>What is the right way to convert a naive time and a <code>tzinfo</code> into an utc time? Say I have:</p> <pre><code>d = datetime(2009, 8, 31, 22, 30, 30) tz = timezone('US/Pacific') </code></pre> <p>First way, pytz inspired:</p> <pre><code>d_tz = tz.normalize(tz.localize(d)) utc = pytz.timezone('UTC') d_utc = d_tz.astimezone(utc) </code></pre> <p>Second way, from <a href="http://www.djangosnippets.org/snippets/388/">UTCDateTimeField</a></p> <pre><code>def utc_from_localtime(dt, tz): dt = dt.replace(tzinfo=tz) _dt = tz.normalize(dt) if dt.tzinfo != _dt.tzinfo: # Houston, we have a problem... # find out which one has a dst offset if _dt.tzinfo.dst(_dt): _dt -= _dt.tzinfo.dst(_dt) else: _dt += dt.tzinfo.dst(dt) return _dt.astimezone(pytz.utc) </code></pre> <p>Needles to say those two methods produce different results for quite a few timezones.</p> <p>Question is - what's the right way?</p>
20
2009-08-31T14:22:55Z
1,357,965
<p>Use the first method. There's no reason to reinvent the wheel of timezone conversion </p>
0
2009-08-31T15:18:22Z
[ "python", "datetime", "utc", "pytz" ]
pytz utc conversion
1,357,711
<p>What is the right way to convert a naive time and a <code>tzinfo</code> into an utc time? Say I have:</p> <pre><code>d = datetime(2009, 8, 31, 22, 30, 30) tz = timezone('US/Pacific') </code></pre> <p>First way, pytz inspired:</p> <pre><code>d_tz = tz.normalize(tz.localize(d)) utc = pytz.timezone('UTC') d_utc = d_tz.astimezone(utc) </code></pre> <p>Second way, from <a href="http://www.djangosnippets.org/snippets/388/">UTCDateTimeField</a></p> <pre><code>def utc_from_localtime(dt, tz): dt = dt.replace(tzinfo=tz) _dt = tz.normalize(dt) if dt.tzinfo != _dt.tzinfo: # Houston, we have a problem... # find out which one has a dst offset if _dt.tzinfo.dst(_dt): _dt -= _dt.tzinfo.dst(_dt) else: _dt += dt.tzinfo.dst(dt) return _dt.astimezone(pytz.utc) </code></pre> <p>Needles to say those two methods produce different results for quite a few timezones.</p> <p>Question is - what's the right way?</p>
20
2009-08-31T14:22:55Z
1,358,161
<p>Your first method seems to be the approved one, and should be DST-aware.</p> <p>You could shorten it a tiny bit, since <em>pytz.utc = pytz.timezone('UTC')</em>, but you knew that already :)</p> <pre><code>tz = timezone('US/Pacific') def toUTC(d): return tz.normalize(tz.localize(d)).astimezone(pytz.utc) print "Test: ", datetime.datetime.utcnow(), " = ", toUTC(datetime.datetime.now()) </code></pre>
18
2009-08-31T16:07:40Z
[ "python", "datetime", "utc", "pytz" ]
pytz utc conversion
1,357,711
<p>What is the right way to convert a naive time and a <code>tzinfo</code> into an utc time? Say I have:</p> <pre><code>d = datetime(2009, 8, 31, 22, 30, 30) tz = timezone('US/Pacific') </code></pre> <p>First way, pytz inspired:</p> <pre><code>d_tz = tz.normalize(tz.localize(d)) utc = pytz.timezone('UTC') d_utc = d_tz.astimezone(utc) </code></pre> <p>Second way, from <a href="http://www.djangosnippets.org/snippets/388/">UTCDateTimeField</a></p> <pre><code>def utc_from_localtime(dt, tz): dt = dt.replace(tzinfo=tz) _dt = tz.normalize(dt) if dt.tzinfo != _dt.tzinfo: # Houston, we have a problem... # find out which one has a dst offset if _dt.tzinfo.dst(_dt): _dt -= _dt.tzinfo.dst(_dt) else: _dt += dt.tzinfo.dst(dt) return _dt.astimezone(pytz.utc) </code></pre> <p>Needles to say those two methods produce different results for quite a few timezones.</p> <p>Question is - what's the right way?</p>
20
2009-08-31T14:22:55Z
26,190,657
<blockquote> <p>What is the right way to convert a naive time and a tzinfo into an utc time? </p> </blockquote> <p><a href="http://stackoverflow.com/a/26163706/4279">This answer enumerates some issues with converting a local time to UTC</a>:</p> <pre><code>from datetime import datetime import pytz # $ pip install pytz d = datetime(2009, 8, 31, 22, 30, 30) tz = pytz.timezone('US/Pacific') # a) raise exception for non-existent or ambiguous times aware_d = tz.localize(d, is_dst=None) ## b) assume standard time, adjust non-existent times #aware_d = tz.normalize(tz.localize(d, is_dst=False)) ## c) assume DST is in effect, adjust non-existent times #aware_d = tz.normalize(tz.localize(naive_d, is_dst=True)) # convert to UTC utc_d = aware_d.astimezone(pytz.utc) </code></pre>
2
2014-10-04T07:25:02Z
[ "python", "datetime", "utc", "pytz" ]
pytz utc conversion
1,357,711
<p>What is the right way to convert a naive time and a <code>tzinfo</code> into an utc time? Say I have:</p> <pre><code>d = datetime(2009, 8, 31, 22, 30, 30) tz = timezone('US/Pacific') </code></pre> <p>First way, pytz inspired:</p> <pre><code>d_tz = tz.normalize(tz.localize(d)) utc = pytz.timezone('UTC') d_utc = d_tz.astimezone(utc) </code></pre> <p>Second way, from <a href="http://www.djangosnippets.org/snippets/388/">UTCDateTimeField</a></p> <pre><code>def utc_from_localtime(dt, tz): dt = dt.replace(tzinfo=tz) _dt = tz.normalize(dt) if dt.tzinfo != _dt.tzinfo: # Houston, we have a problem... # find out which one has a dst offset if _dt.tzinfo.dst(_dt): _dt -= _dt.tzinfo.dst(_dt) else: _dt += dt.tzinfo.dst(dt) return _dt.astimezone(pytz.utc) </code></pre> <p>Needles to say those two methods produce different results for quite a few timezones.</p> <p>Question is - what's the right way?</p>
20
2009-08-31T14:22:55Z
31,574,271
<pre><code> import pytz from django.utils import timezone tz = pytz.timezone('America/Los_Angeles') time = tz.normalize(timezone.now()) </code></pre>
-2
2015-07-22T21:25:59Z
[ "python", "datetime", "utc", "pytz" ]
Finding set difference between two complex dictionaries
1,358,101
<p>I have two dictionaries of the following structure: </p> <pre><code>a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]} b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]} </code></pre> <p>I need to find the set difference between each key in the dictionary i.e., dict1['a'] - dict2['a'] should return [3,4]. Any thought is appreciated.</p>
2
2009-08-31T15:53:23Z
1,358,150
<p>The use of mutable items (such as lists) makes the problem MUCH harder, as it precludes the simple use of Python's <code>set</code> data structure. It may be worth making temporary copies/versions which actually use tuples in lieu of those pesky lists:</p> <pre><code>def tempaux(d): return dict((k, set(tuple(x) for x in v)) for k, v in d.iteritems()) </code></pre> <p>Now:</p> <pre><code>def thedifs(dd1, dd2) d1 = tempaux(dd1) d2 = tempaux(dd2) allkeys = set(d1).update(d2) empty = set() difs = [] for k in allkeys: s1 = d1.get(k, empty) s2 = d2.get(k, empty) adif = s1 - s2 if adif: difs.append(adif) return difs </code></pre> <p>This assumes actual set difference rather than symmetric difference etc. You can of course turn back the tuples into lists before returns, &amp;c, depending on your exact requirements.</p>
6
2009-08-31T16:04:57Z
[ "python-3.x", "python" ]
Finding set difference between two complex dictionaries
1,358,101
<p>I have two dictionaries of the following structure: </p> <pre><code>a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]} b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]} </code></pre> <p>I need to find the set difference between each key in the dictionary i.e., dict1['a'] - dict2['a'] should return [3,4]. Any thought is appreciated.</p>
2
2009-08-31T15:53:23Z
1,358,156
<pre><code>&gt;&gt;&gt; s1 = set([(1,2), (3,4)]) &gt;&gt;&gt; s2 = set([(1,2), (5,6)]) &gt;&gt;&gt; s1 - s2 {(3, 4)} </code></pre>
3
2009-08-31T16:06:56Z
[ "python-3.x", "python" ]
Finding set difference between two complex dictionaries
1,358,101
<p>I have two dictionaries of the following structure: </p> <pre><code>a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]} b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]} </code></pre> <p>I need to find the set difference between each key in the dictionary i.e., dict1['a'] - dict2['a'] should return [3,4]. Any thought is appreciated.</p>
2
2009-08-31T15:53:23Z
1,358,787
<p>You've got the wrong data structure for what you're trying to do.</p> <p>Use this instead.</p> <pre><code>dict1 = {'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]} dict2 = {'a': [(1, 2), (5, 6)], 'b': [(1, 2), (7, 8)]} </code></pre> <p>Life is simpler when you try to do set operations on immutable objects like tuples.</p> <p>This will transform your list-of-lists into a list-of-tuples.</p> <pre><code>&gt;&gt;&gt; dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 ) {'a': [(1, 2), (3, 4)], 'b': [(1, 2), (5, 6)]} </code></pre> <p>Here's the complete solution.</p> <pre><code>&gt;&gt;&gt; dict1t= dict( (key,[tuple(v) for v in dict1[key]]) for key in dict1 ) &gt;&gt;&gt; dict2t= dict( (key,[tuple(v) for v in dict2[key]]) for key in dict2 ) &gt;&gt;&gt; set(dict1t['a'])-set(dict2t['a']) set([(3, 4)]) </code></pre>
2
2009-08-31T18:36:32Z
[ "python-3.x", "python" ]
Finding set difference between two complex dictionaries
1,358,101
<p>I have two dictionaries of the following structure: </p> <pre><code>a) dict1 = {'a':[ [1,2], [3,4] ], 'b':[ [1,2],[5,6] ]} b) dict2 = {'a':[ [1,2], [5,6] ], 'b':[ [1,2],[7,8] ]} </code></pre> <p>I need to find the set difference between each key in the dictionary i.e., dict1['a'] - dict2['a'] should return [3,4]. Any thought is appreciated.</p>
2
2009-08-31T15:53:23Z
12,791,351
<h1>applicable to list or dict or number when a and b share the same structure</h1> <pre><code>c={'a':'1','b':'2'} d={'a':'10','b':'20'} e={'x':c,'t':15} f={'x':d,'t':19} def diff(a,b): if isinstance(a, int) and isinstance(b, int): b = b - a return b if isinstance(a, str) and isinstance(b, str): if a.isdigit() and b.isdigit(): b = str(int(b) - int(a)) return b else: b = a return b if type(a) is list and type(b) is list: for i in range(len(a)): b[i] = diff(a[i],b[i]) return b if type(a) is dict and type(b) is dict: for k,v in b.iteritems(): b[k] = diff(a[k],b[k]) return b print diff(e,f) </code></pre>
2
2012-10-09T00:37:11Z
[ "python-3.x", "python" ]
Creating database schema for parsed feed
1,358,501
<p>Additional questions regarding <a href="http://stackoverflow.com/questions/1354415/split-twitter-rss-string-using-python">SilentGhost's initial answer</a> to a problem I'm having parsing Twitter RSS feeds. See also partial code below.</p> <p>First, could I insert <code>tags[0]</code>, <code>tags[1]</code>, etc., into the database, or is there a different/better way to do it? </p> <p>Second, almost all of the entries have a url, but a few don't; likewise, many entries don't have the hashtags. So, would the thing to do be to create default values for url and tags? And if so, do you have any hints on how to do that? :)</p> <p>Third, when you say the single-table db design is not optimal, do you mean I should create a separate table for tags? Right now, I have one table for the RSS feed urls and another table with all the rss entry data (summar.y, date, etc.).</p> <p>I've pasted in a modified version of the code you posted. I had some success in getting a "tinyurl" variable to get into the sqlite database, but now it isn't working. Not sure why.</p> <p>Lastly, assuming I can get the whole thing up and running (smile), is there a central site where people might appreciate seeing my solution? Or should I just post something on my own blog? </p> <p>Best,</p> <p>Greg</p>
0
2009-08-31T17:37:18Z
1,358,551
<p>I would suggest reading up on <a href="http://en.wikipedia.org/wiki/Database%5Fnormalization" rel="nofollow">database normalisation</a>, especially on 1st and 2nd normal forms. Once you're done with it, I hope there won't be need for default values, and your db schema evolves into something more appropriate.</p> <p>There are plenty of options for sharing your source code on the web, depending on what versioning system you're most comfortable with you might have a look at such well know sites as <a href="http://code.google.com/" rel="nofollow">google code</a>, <a href="http://bitbucket.org/" rel="nofollow">bitbucket</a>, <a href="http://github.com/" rel="nofollow">github</a> and many other.</p>
2
2009-08-31T17:44:24Z
[ "python", "rss", "database-schema" ]
Raising an exception on updating a 'constant' attribute in python
1,358,711
<p>As python does not have concept of constants, would it be possible to raise an exception if an 'constant' attribute is updated? How? </p> <pre><code>class MyClass(): CLASS_CONSTANT = 'This is a constant' var = 'This is a not a constant, can be updated' #this should raise an exception MyClass.CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass.var = 'updating this is fine' #this also should raise an exception MyClass().CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass().var = 'updating this is fine' </code></pre> <p>Any attempt to change CLASS_CONSTANT as a class attribute or as an instance attribute should raise an exception.</p> <p>Changing var as a class attribute or as an instance attribute should not raise an exception. </p>
2
2009-08-31T18:21:13Z
1,358,752
<p>If you really want to have constant that can't be changed then look at this: <a href="http://code.activestate.com/recipes/65207/" rel="nofollow">http://code.activestate.com/recipes/65207/</a></p>
0
2009-08-31T18:28:10Z
[ "python", "exception", "attributes", "constants" ]
Raising an exception on updating a 'constant' attribute in python
1,358,711
<p>As python does not have concept of constants, would it be possible to raise an exception if an 'constant' attribute is updated? How? </p> <pre><code>class MyClass(): CLASS_CONSTANT = 'This is a constant' var = 'This is a not a constant, can be updated' #this should raise an exception MyClass.CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass.var = 'updating this is fine' #this also should raise an exception MyClass().CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass().var = 'updating this is fine' </code></pre> <p>Any attempt to change CLASS_CONSTANT as a class attribute or as an instance attribute should raise an exception.</p> <p>Changing var as a class attribute or as an instance attribute should not raise an exception. </p>
2
2009-08-31T18:21:13Z
1,358,753
<p>Start reading this:</p> <p><a href="http://docs.python.org/reference/datamodel.html#customizing-attribute-access" rel="nofollow">http://docs.python.org/reference/datamodel.html#customizing-attribute-access</a></p> <p>You basically write your own version of <code>__setattr__</code> that throws exceptions for some attributes, but not others.</p>
1
2009-08-31T18:28:18Z
[ "python", "exception", "attributes", "constants" ]
Raising an exception on updating a 'constant' attribute in python
1,358,711
<p>As python does not have concept of constants, would it be possible to raise an exception if an 'constant' attribute is updated? How? </p> <pre><code>class MyClass(): CLASS_CONSTANT = 'This is a constant' var = 'This is a not a constant, can be updated' #this should raise an exception MyClass.CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass.var = 'updating this is fine' #this also should raise an exception MyClass().CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass().var = 'updating this is fine' </code></pre> <p>Any attempt to change CLASS_CONSTANT as a class attribute or as an instance attribute should raise an exception.</p> <p>Changing var as a class attribute or as an instance attribute should not raise an exception. </p>
2
2009-08-31T18:21:13Z
1,358,755
<p>You could do something like this: (from <a href="http://www.siafoo.net/snippet/108" rel="nofollow">http://www.siafoo.net/snippet/108</a>)</p> <pre><code>class Constants: # A constant variable foo = 1337 def __setattr__(self, attr, value): if hasattr(self, attr): raise ValueError, 'Attribute %s already has a value and so cannot be written to' % attr self.__dict__[attr] = value </code></pre> <p>Then use it like this:</p> <pre><code>&gt;&gt;&gt; const = Constants() &gt;&gt;&gt; const.test1 = 42 &gt;&gt;&gt; const.test1 42 &gt;&gt;&gt; const.test1 = 43 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 4, in __setattr__ ValueError: Attribute test1 already has a value and so cannot be written to &gt;&gt;&gt; const.test1 42 </code></pre>
2
2009-08-31T18:28:40Z
[ "python", "exception", "attributes", "constants" ]
Raising an exception on updating a 'constant' attribute in python
1,358,711
<p>As python does not have concept of constants, would it be possible to raise an exception if an 'constant' attribute is updated? How? </p> <pre><code>class MyClass(): CLASS_CONSTANT = 'This is a constant' var = 'This is a not a constant, can be updated' #this should raise an exception MyClass.CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass.var = 'updating this is fine' #this also should raise an exception MyClass().CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass().var = 'updating this is fine' </code></pre> <p>Any attempt to change CLASS_CONSTANT as a class attribute or as an instance attribute should raise an exception.</p> <p>Changing var as a class attribute or as an instance attribute should not raise an exception. </p>
2
2009-08-31T18:21:13Z
1,358,832
<p>Customizing <code>__setattr__</code> in every class (e.g. as exemplified in my old recipe that @ainab's answer is pointing to, and other answers), only works to stop assignment to INSTANCE attributes and not to CLASS attributes. So, none of the existing answers would actually satisfy your requirement as stated.</p> <p>If what you asked for IS actually exactly what you want, you could resort to some mix of custom metaclasses and descriptors, such as:</p> <pre><code>class const(object): def __init__(self, val): self.val = val def __get__(self, *_): return self.val def __set__(self, *_): raise TypeError("Can't reset const!") class mcl(type): def __init__(cls, *a, **k): mkl = cls.__class__ class spec(mkl): pass for n, v in vars(cls).items(): if isinstance(v, const): setattr(spec, n, v) spec.__name__ = mkl.__name__ cls.__class__ = spec class with_const: __metaclass__ = mcl class foo(with_const): CLASS_CONSTANT = const('this is a constant') print foo().CLASS_CONSTANT print foo.CLASS_CONSTANT foo.CLASS_CONSTANT = 'Oops!' print foo.CLASS_CONSTANT </code></pre> <p>This is pretty advanced stuff, so you might prefer the simpler <code>__setattr__</code> approach suggested in other answers, despite it NOT meeting your requirements as stated (i.e., you might reasonably choose to weaken your requirements in order to gain simplicity;-). But the techniques here might still be interesting: the custom descriptor type <code>const</code> is another way (IMHO far nicer than overriding <code>__setattr__</code> in each and every class that needs some constants AND making all attributes constants rather than picking and choosing...) to block assignment to an instance attribute; the rest of the code is about a custom metaclass creating unique per-class sub-metaclasses of itself, in order to exploit said custom descriptor to the fullest and achieving the exact functionality you specifically asked for.</p>
3
2009-08-31T18:46:22Z
[ "python", "exception", "attributes", "constants" ]
Raising an exception on updating a 'constant' attribute in python
1,358,711
<p>As python does not have concept of constants, would it be possible to raise an exception if an 'constant' attribute is updated? How? </p> <pre><code>class MyClass(): CLASS_CONSTANT = 'This is a constant' var = 'This is a not a constant, can be updated' #this should raise an exception MyClass.CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass.var = 'updating this is fine' #this also should raise an exception MyClass().CLASS_CONSTANT = 'No, this cannot be updated, will raise an exception' #this should not raise an exception MyClass().var = 'updating this is fine' </code></pre> <p>Any attempt to change CLASS_CONSTANT as a class attribute or as an instance attribute should raise an exception.</p> <p>Changing var as a class attribute or as an instance attribute should not raise an exception. </p>
2
2009-08-31T18:21:13Z
1,358,863
<p>You can use a metaclass to achieve this:</p> <pre><code>class ImmutableConstants(type): def __init__(cls, name, bases, dct): type.__init__(cls, name, bases, dct) old_setattr = cls.__setattr__ def __setattr__(self, key, value): cls.assert_attribute_mutable(key) old_setattr(self, key, value) cls.__setattr__ = __setattr__ def __setattr__(self, key, value): self.assert_attribute_mutable(key) type.__setattr__(self, key, value) def assert_attribute_mutable(self, name): if name.isupper(): raise AttributeError('Attribute %s is constant' % name) class Foo(object): __metaclass__ = ImmutableConstants CONST = 5 class_var = 'foobar' Foo.class_var = 'new value' Foo.CONST = 42 # raises </code></pre> <p>But are you sure this is a real issue? Are you really accidentally setting constants all over the place? You can find most of these pretty easily with a <code>grep -r '\.[A-Z][A-Z0-9_]*\s*=' src/</code>.</p>
2
2009-08-31T18:53:43Z
[ "python", "exception", "attributes", "constants" ]
How to make several plots on a single page using matplotlib?
1,358,977
<p>I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to use the subplot command? I don't understand why I would have to but can't figure out what else I would do? </p> <pre><code>import csv import scipy.stats import numpy import matplotlib.pyplot as plt for i in range(16): plt.figure(i) filename= easygui.fileopenbox(msg='Pdf distance 90m contour', title='select file', filetypes=['*.csv'], default='X:\\herring_schools\\') alt_file=open(filename) a=[] for row in csv.DictReader(alt_file): a.append(row['Dist_90m(nmi)']) y= numpy.array(a, float) relpdf=scipy.stats.relfreq(y, numbins=7, defaultreallimits=(-10,60)) bins = numpy.arange(-10,60,10) print numpy.sum(relpdf[0]) print bins patches=plt.bar(bins,relpdf[0], width=10, facecolor='black') titlename= easygui.enterbox(msg='write graph title', title='', default='', strip=True, image=None, root=None) plt.title(titlename) plt.ylabel('Probability Density Function') plt.xlabel('Distance from 90m Contour Line(nm)') plt.ylim([0,1]) plt.show() </code></pre>
48
2009-08-31T19:17:03Z
1,358,983
<p>To answer your main question, you want to use the <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.subplot">subplot</a> command. I think changing <code>plt.figure(i)</code> to <code>plt.subplot(4,4,i+1)</code> should work.</p>
10
2009-08-31T19:19:17Z
[ "python", "numpy", "matplotlib" ]
How to make several plots on a single page using matplotlib?
1,358,977
<p>I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to use the subplot command? I don't understand why I would have to but can't figure out what else I would do? </p> <pre><code>import csv import scipy.stats import numpy import matplotlib.pyplot as plt for i in range(16): plt.figure(i) filename= easygui.fileopenbox(msg='Pdf distance 90m contour', title='select file', filetypes=['*.csv'], default='X:\\herring_schools\\') alt_file=open(filename) a=[] for row in csv.DictReader(alt_file): a.append(row['Dist_90m(nmi)']) y= numpy.array(a, float) relpdf=scipy.stats.relfreq(y, numbins=7, defaultreallimits=(-10,60)) bins = numpy.arange(-10,60,10) print numpy.sum(relpdf[0]) print bins patches=plt.bar(bins,relpdf[0], width=10, facecolor='black') titlename= easygui.enterbox(msg='write graph title', title='', default='', strip=True, image=None, root=None) plt.title(titlename) plt.ylabel('Probability Density Function') plt.xlabel('Distance from 90m Contour Line(nm)') plt.ylim([0,1]) plt.show() </code></pre>
48
2009-08-31T19:17:03Z
2,060,170
<p>The answer from <em>las3rjock</em>, which somehow is the answer accepted by the OP, is incorrect--the code doesn't run, nor is it valid matplotlib syntax; that answer provides no runnable code and lacks any information or suggestion that the OP might find useful in writing their own code to solve the problem in the OP.</p> <p>Given that it's the accepted answer and has already received several up-votes, I suppose a little deconstruction is in order. </p> <p>First, calling <em>subplot</em> does <strong>not</strong> give you multiple plots; <strong><em>subplot</em></strong> is called to create a single plot, as well as to create multiple plots. In addition, "changing plt.figure(i)" is not correct.</p> <p><em>plt.figure()</em> (in which plt or PLT is usually matplotlib's <em>pyplot library</em> imported and rebound as a global variable, plt or sometimes PLT, like so:</p> <pre><code>from matplotlib import pyplot as PLT fig = PLT.figure() </code></pre> <p>the line just above creates a matplotlib figure instance; this object's <em>add_subplot</em> method is then called for every plotting window (informally think of an x &amp; y axis comprising a single subplot). You create (whether just one or for several on a page), like so</p> <pre><code>fig.add_subplot(111) </code></pre> <p>this syntax is equivalent to</p> <pre><code>fig.add_subplot(1,1,1) </code></pre> <p>choose the one that makes sense to you.</p> <p>Below I've listed the code to plot two plots on a page, one above the other. The formatting is done via the argument passed to <strong>add_subplot</strong>. Notice the argument is (<strong><em>211</em></strong>) for the first plot and (<strong><em>212</em></strong>) for the second. </p> <pre><code>from matplotlib import pyplot as PLT fig = PLT.figure() ax1 = fig.add_subplot(211) ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)]) ax2 = fig.add_subplot(212) ax2.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)]) PLT.show() </code></pre> <p>Each of these two arguments is a complete specification for correctly placing the respective plot windows on the page.</p> <p><strong><em>211</em></strong> (which again, could also be written in 3-tuple form as (2,1,1) means <em>two rows</em> and <em>one column</em> of plot windows; the third digit specifies the ordering of that particular subplot window relative to the other subplot windows--in this case, this is the first plot (which places it on row 1) hence plot number 1, row 1 col 1.</p> <p>The argument passed to the second call to <strong>add_subplot</strong>, differs from the first only by the trailing digit (a 2 instead of a 1, because this plot is the second plot (row 2, col 1).</p> <p>An example with more plots: if instead you wanted <em>four</em> plots on a page, in a 2x2 matrix configuration, you would call the add_subplot method four times, passing in these four arguments (221), (222), (223), and (224), to create four plots on a page at 10, 2, 8, and 4 o'clock, respectively and in this order.</p> <p>Notice that each of the four arguments contains two leadings 2's--that encodes the 2 x 2 configuration, ie, two rows and two columns.</p> <p>The third (right-most) digit in each of the four arguments encodes the ordering of that particular plot window in the 2 x 2 matrix--ie, row 1 col 1 (1), row 1 col 2 (2), row 2 col 1 (3), row 2 col 2 (4).</p>
109
2010-01-13T20:52:22Z
[ "python", "numpy", "matplotlib" ]
How to make several plots on a single page using matplotlib?
1,358,977
<p>I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to use the subplot command? I don't understand why I would have to but can't figure out what else I would do? </p> <pre><code>import csv import scipy.stats import numpy import matplotlib.pyplot as plt for i in range(16): plt.figure(i) filename= easygui.fileopenbox(msg='Pdf distance 90m contour', title='select file', filetypes=['*.csv'], default='X:\\herring_schools\\') alt_file=open(filename) a=[] for row in csv.DictReader(alt_file): a.append(row['Dist_90m(nmi)']) y= numpy.array(a, float) relpdf=scipy.stats.relfreq(y, numbins=7, defaultreallimits=(-10,60)) bins = numpy.arange(-10,60,10) print numpy.sum(relpdf[0]) print bins patches=plt.bar(bins,relpdf[0], width=10, facecolor='black') titlename= easygui.enterbox(msg='write graph title', title='', default='', strip=True, image=None, root=None) plt.title(titlename) plt.ylabel('Probability Density Function') plt.xlabel('Distance from 90m Contour Line(nm)') plt.ylim([0,1]) plt.show() </code></pre>
48
2009-08-31T19:17:03Z
2,064,911
<p>This works also:</p> <pre><code>for i in range(19): plt.subplot(5,4,i+1) </code></pre> <p>It plots 19 total graphs on one page. The format is 5 down and 4 across..</p>
6
2010-01-14T14:51:37Z
[ "python", "numpy", "matplotlib" ]
How to make several plots on a single page using matplotlib?
1,358,977
<p>I have written code that opens 16 figures at once. Currently they all open as separate graphs. I'd like them to open all on the same page. Not the same graph. I want 16 separate graphs on a single page/window. Also for some reason the format of the numbins and defaultreallimits doesn't hold past figure 1. Do I need to use the subplot command? I don't understand why I would have to but can't figure out what else I would do? </p> <pre><code>import csv import scipy.stats import numpy import matplotlib.pyplot as plt for i in range(16): plt.figure(i) filename= easygui.fileopenbox(msg='Pdf distance 90m contour', title='select file', filetypes=['*.csv'], default='X:\\herring_schools\\') alt_file=open(filename) a=[] for row in csv.DictReader(alt_file): a.append(row['Dist_90m(nmi)']) y= numpy.array(a, float) relpdf=scipy.stats.relfreq(y, numbins=7, defaultreallimits=(-10,60)) bins = numpy.arange(-10,60,10) print numpy.sum(relpdf[0]) print bins patches=plt.bar(bins,relpdf[0], width=10, facecolor='black') titlename= easygui.enterbox(msg='write graph title', title='', default='', strip=True, image=None, root=None) plt.title(titlename) plt.ylabel('Probability Density Function') plt.xlabel('Distance from 90m Contour Line(nm)') plt.ylim([0,1]) plt.show() </code></pre>
48
2009-08-31T19:17:03Z
18,673,184
<p>Since this question is from 4 years ago new things have been implemented and among them there is a <a href="http://matplotlib.org/api/pyplot_api.html">new function <code>plt.subplots</code> which is very convenient</a>:</p> <pre><code>fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True) </code></pre> <p>where <code>axes</code> is a <code>numpy.ndarray</code> of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices <code>[i,j]</code>.</p>
43
2013-09-07T12:14:45Z
[ "python", "numpy", "matplotlib" ]
Wildcard Downloads with Python
1,359,090
<p>How can I download files from a website using wildacrds in Python? I have a site that I need to download file from periodically. The problem is the filenames change each time. A portion of the file stays the same though. How can I use a wildcard to specify the unknown portion of the file in a URL?</p>
1
2009-08-31T19:46:12Z
1,359,101
<p>If the filename changes, there must still be a <em>link</em> to the file somewhere (otherwise nobody would ever guess the filename). A typical approach is to get the HTML page that contains a link to the file, search through that looking for the link target, and then send a second request to get the actual file you're after.</p> <p>Web servers do not generally implement such a "wildcard" facility as you describe, so you must use other techniques.</p>
7
2009-08-31T19:48:53Z
[ "python" ]
Wildcard Downloads with Python
1,359,090
<p>How can I download files from a website using wildacrds in Python? I have a site that I need to download file from periodically. The problem is the filenames change each time. A portion of the file stays the same though. How can I use a wildcard to specify the unknown portion of the file in a URL?</p>
1
2009-08-31T19:46:12Z
1,359,226
<p>You could try logging into the ftp server using <a href="http://python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a>. From the python docs:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port ftp.login() # user anonymous, passwd anonymous@ </code></pre> <p>The ftp object has a <code>dir</code> method that lists the contents of a directory. You could use this listing to find the name of the file you want.</p>
1
2009-08-31T20:18:42Z
[ "python" ]
PyObjc and Cocoa on Snow Leopard
1,359,227
<p>I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.</p> <p>I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.</p> <p>I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.</p> <p>Thanks in advance for the help!</p> <p><strong>Update:</strong> I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.</p> <p>Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science. </p> <p>This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.</p> <p>Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!</p>
13
2009-08-31T20:19:29Z
1,359,402
<p>You mean like <a href="http://checkoutapp.com/" rel="nofollow">Checkout</a>? :-) I only mention it because Checkout is gorgeous and written with PyObjC...</p> <p>Your concerns are valid, although probably not as much of a potential showstopper as you'd think. Using PyObjC still requires you to learn some Objective-C, and definitely requires you to understand at least some of the Cocoa frameworks, since you need to call into the Cocoa frameworks whenever you need to do some sort of Cocoa-specific task.</p> <p>I recommend you read and consider the SO question <a href="http://stackoverflow.com/questions/14422">"Why is the PyObjC documentation so bad?"</a> and <a href="http://stackoverflow.com/questions/426607/">"PyObjc vs RubyCocoa for Mac development: Which is more mature?"</a> before you completely convince yourself that "just PyObjC" will make things much easier. I refuse to disparage PyObjC because it is quite powerful and incredibly useful, but realize that nothing is a silver bullet, and no language or technology is best for all problems.</p> <p>The Objective-C language is simple and pretty straightforward. The Cocoa frameworks generally dominate the learning curve for new Cocoa programmers. Plus, you have StackOverflow and lots of other resources to help answer your questions. (Judging by the activity of the <a href="http://stackoverflow.com/questions/tagged/pyobjc">"pyobjc" tag</a>, you also stand a better chance of getting good <a href="http://stackoverflow.com/questions/tagged/objective-c">Objective-C help</a> on SO.)</p>
7
2009-08-31T21:00:03Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
PyObjc and Cocoa on Snow Leopard
1,359,227
<p>I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.</p> <p>I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.</p> <p>I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.</p> <p>Thanks in advance for the help!</p> <p><strong>Update:</strong> I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.</p> <p>Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science. </p> <p>This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.</p> <p>Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!</p>
13
2009-08-31T20:19:29Z
1,359,428
<p>I hardly use PyObjC myself, but I believe you need to run the Xcode installer on the Snow Leopard DVD in order to use PyObjC.</p> <p>Also, as Quinn said, you will need to understand at least some Objective-C in order to use a Cocoa bridge like PyObjC without tearing your hair out. It just doesn't insulate you that completely.</p>
3
2009-08-31T21:06:29Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
PyObjc and Cocoa on Snow Leopard
1,359,227
<p>I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.</p> <p>I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.</p> <p>I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.</p> <p>Thanks in advance for the help!</p> <p><strong>Update:</strong> I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.</p> <p>Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science. </p> <p>This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.</p> <p>Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!</p>
13
2009-08-31T20:19:29Z
1,359,557
<p>I'm going to agree with Quinn here. Even if you're already proficient in Python, learning how to interface Python and Cocoa is not going to be any easier than learning Cocoa with Objective-C.</p> <p>Objective-C is a simple, clean language that is quite easy to grok. Building the GUI and hooking it up to the back-end will be harder than learning the Objective-C to write the back-end, and building the GUI and hooking it up isn't that hard.</p> <p>Follow <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjCTutorial/01Introduction/01Introduction.html" rel="nofollow">the Cocoa app tutorial</a> (you should be able to get through it in a day, or maybe a weekend if you go slow) and you'll be well on your way.</p>
3
2009-08-31T21:41:34Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
PyObjc and Cocoa on Snow Leopard
1,359,227
<p>I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.</p> <p>I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.</p> <p>I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.</p> <p>Thanks in advance for the help!</p> <p><strong>Update:</strong> I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.</p> <p>Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science. </p> <p>This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.</p> <p>Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!</p>
13
2009-08-31T20:19:29Z
1,359,575
<p>And as one of the Checkout developers I'll weigh in too (hi Quinn!). From what we've seen PyObjC runs fairly well on Snow Leopard. We've built one of the latest SVN revisions 2.2b with some customizations on Leopard and just moved over the site-packages folder.</p> <p>Theoretically you should be able to use the built in Python/PyObjC (just do import objc, Foundation, AppKit) but as we ship/work with custom versions of both Python and PyObjC I'm not sure what the status exactly is. The mailing list doesn't mention a lot of people having issues (just a few) so that could be a good sign.</p> <p>Good luck with the project, and if you have specific POS questions shoot me an email ;-)</p>
4
2009-08-31T21:48:38Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
PyObjc and Cocoa on Snow Leopard
1,359,227
<p>I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.</p> <p>I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.</p> <p>I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.</p> <p>Thanks in advance for the help!</p> <p><strong>Update:</strong> I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.</p> <p>Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science. </p> <p>This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.</p> <p>Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!</p>
13
2009-08-31T20:19:29Z
1,359,605
<p>Allow me to echo what has already been said. I too am a student who just started a Cocoa development project, and at the beginning I thought "Well, I already know Python, I'll just use PyObjC and save myself from having to learn Objective-C, which looks beyond my grasp." I learned quickly that it can't be done. You can develop for OS X without learning Objective-C, but not without learning the Cocoa libraries, which constitute 99% of what you need to learn to write a Cocoa app in Objective-C. Objective-C itself isn't that hard; it's the Cocoa libraries that you need to invest in learning.</p> <p>PyObjC basically uses Cocoa libraries and Python syntax. I gave up with it quickly and decided that if I was going to have to learn Cocoa, I may as well use Objective-C.</p> <p>If you're looking to learn, Aaron Hillegass's book is a good place to start. Good luck!</p>
19
2009-08-31T22:00:20Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
PyObjc and Cocoa on Snow Leopard
1,359,227
<p>I am about to start my A-Level Computing project (High School Level) which will hopefully be a point-of-sale application for Mac OS. Unfortunately, Objective-C is a little out of my league at the moment and should I get stuck with it in the project I have no one to help out so I would fail the section of the course and not get into University. So this is quite important to me.</p> <p>I want to use Python to develop a Cocoa app. I know that I need PyObjc, however all details on the net seem to assume it is pre-installed. Apparently this is the case with Leopard and Snow Leopard but I don't seem to have it on Snow Leopard and never noticed it on Leopard. Also, I have tried installing the latest beta of PyObjc by following the instructions on the Sourceforge page, but with no luck.</p> <p>I would really appreciate it if anyone could shed some light on what needs to be installed, how, and links to any resources or tutorials that could help me.</p> <p>Thanks in advance for the help!</p> <p><strong>Update:</strong> I see that this is a popular question, I just got the 'Notable Question' badge for it so I thought I would update anyone coming to this page on what I did after getting the answers.</p> <p>Unfortunately, I wasn't able to use Python to create a Mac application. This was rather disappointing at the time, but probably a good thing. I made a Windows app in C# for my project, it was a tool for creating and running Assembly apps in a simulated environment. My course teacher has now started to use my tool to teach the course instead of his own! I got a very high score on the computing project (over 90%) and this contributed to me getting an A* in my computing A-Level (the highest grade available) and I consequently got in to Southampton University to study Computer Science. </p> <p>This summer, I decided to make an iPad app (soon to be released) and I am glad to say that I know think I could make a Mac OS application in Objective-C as I feel I have learnt enough. I am glad that I took the time to learn it, it is a great language and really useful with iOS becoming so popular.</p> <p>Sorry for all the boasting, but I am really happy about it. What I really want to say is, if you are coming to this page hoping to use PyObjc to create Mac apps easily, don't bother. It takes some time and some effort, but once you have learnt Objective-C, it is really satisfying to create apps with it. Good Luck!</p>
13
2009-08-31T20:19:29Z
1,905,283
<p>I'm a long time python developer who's been doing iPhone apps for awhile now (and only using my python knowledge to package up build files for the apps in run scripts), then who started making some PyObjC apps.</p> <p>I'd have to say, PyObjC is pretty much STILL having to learn objective C (which I already know via iPhone dev), however you get several pretty cool benefits if you use it instead</p> <ul> <li>Easy use of python libraries you know (faster for you)</li> <li>Option to drop it and go to wxPython if styimied by Cocoa</li> <li>Somewhat faster development time (you're writing less code, and the translation between the two languages is pretty darn easy to get used to).</li> </ul> <p>Additionally, interface builder is a little tricky to get used to comparatively speaking, but if you're a python dev, it's not like you're exactly used to a functional gui builder anyhow :oP</p>
3
2009-12-15T05:06:45Z
[ "python", "cocoa", "xcode", "osx-snow-leopard", "pyobjc" ]
Generate two lists at once
1,359,232
<p><strong>Background</strong></p> <p>The algorithm manipulates financial analytics. There are multiple lists of the same size and they are filtered into other lists for analysis. I am doing the same filtering on different by parallel lists. I could set it up so that a1,b1,c2 occur as a tuple in a list but then the analytics have to stripe the tuples the other way to do analysis (regression of one list against the other, beta, etc.).</p> <p><strong>What I want to do</strong></p> <p>I want to generate two different lists based on a third list:</p> <pre><code>&gt;&gt;&gt; a = list(range(10)) &gt;&gt;&gt; b = list(range(10,20)) &gt;&gt;&gt; c = list(i &amp; 1 for i in range(10)) &gt;&gt;&gt; &gt;&gt;&gt; aprime = [a1 for a1, c1 in zip(a,c) if c1 == 0] &gt;&gt;&gt; bprime = [b1 for b1, c1 in zip(b,c) if c1 == 0] &gt;&gt;&gt; aprime [0, 2, 4, 6, 8] &gt;&gt;&gt; bprime [10, 12, 14, 16, 18] </code></pre> <p>It seems there should be a pythonic/functional programming/itertools way to create the two lists and iterate over the three lists only once. Something like:</p> <pre><code>aprime, bprime = [a1, b1 for a1, b1, c1 in zip(a,b,c) if c1 == 0] </code></pre> <p>But of course this generates a syntax error.</p> <p><strong>The question</strong></p> <p>Is there a pythonic way?</p> <p><strong>Micro-optimization shootout</strong></p> <p>The ugly but pythonic-to-the-max one-liner edges out the "just use a for-loop" solution and my original code in the ever popular <em>timeit</em> cage match:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn zip(*[(a1,b1) for a1,b1,c1 in zip(a,b,c) if c1==0])\n") 26.977873025761482 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\taprime, bprime = [], [];\n\tfor a1, b1, c1 in zip(a, b, c):\n\t\tif c1 == 0:\n\t\t\taprime.append(a1); bprime.append(b1);\n\treturn aprime, bprime\n") 32.232914169258947 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn [a1 for a1, c1 in zip(a,c) if c1 == 0], [b1 for b1, c1 in zip(b,c) if c1 == 0]\n") 32.37302275847901 </code></pre>
2
2009-08-31T20:21:02Z
1,359,256
<p>There's no way to create multiple lists at a time with list comprehensions--if you only want to iterate once you're going to need to do it some other way--possible with a loop.</p> <p>You <em>could</em> use a list comprehension to create a list of tuples, with the first element belonging to one list, the second to the other. But if you do want them as separate lists, you're going to have to use another operation to split it, anyway.</p>
0
2009-08-31T20:28:32Z
[ "python" ]
Generate two lists at once
1,359,232
<p><strong>Background</strong></p> <p>The algorithm manipulates financial analytics. There are multiple lists of the same size and they are filtered into other lists for analysis. I am doing the same filtering on different by parallel lists. I could set it up so that a1,b1,c2 occur as a tuple in a list but then the analytics have to stripe the tuples the other way to do analysis (regression of one list against the other, beta, etc.).</p> <p><strong>What I want to do</strong></p> <p>I want to generate two different lists based on a third list:</p> <pre><code>&gt;&gt;&gt; a = list(range(10)) &gt;&gt;&gt; b = list(range(10,20)) &gt;&gt;&gt; c = list(i &amp; 1 for i in range(10)) &gt;&gt;&gt; &gt;&gt;&gt; aprime = [a1 for a1, c1 in zip(a,c) if c1 == 0] &gt;&gt;&gt; bprime = [b1 for b1, c1 in zip(b,c) if c1 == 0] &gt;&gt;&gt; aprime [0, 2, 4, 6, 8] &gt;&gt;&gt; bprime [10, 12, 14, 16, 18] </code></pre> <p>It seems there should be a pythonic/functional programming/itertools way to create the two lists and iterate over the three lists only once. Something like:</p> <pre><code>aprime, bprime = [a1, b1 for a1, b1, c1 in zip(a,b,c) if c1 == 0] </code></pre> <p>But of course this generates a syntax error.</p> <p><strong>The question</strong></p> <p>Is there a pythonic way?</p> <p><strong>Micro-optimization shootout</strong></p> <p>The ugly but pythonic-to-the-max one-liner edges out the "just use a for-loop" solution and my original code in the ever popular <em>timeit</em> cage match:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn zip(*[(a1,b1) for a1,b1,c1 in zip(a,b,c) if c1==0])\n") 26.977873025761482 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\taprime, bprime = [], [];\n\tfor a1, b1, c1 in zip(a, b, c):\n\t\tif c1 == 0:\n\t\t\taprime.append(a1); bprime.append(b1);\n\treturn aprime, bprime\n") 32.232914169258947 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn [a1 for a1, c1 in zip(a,c) if c1 == 0], [b1 for b1, c1 in zip(b,c) if c1 == 0]\n") 32.37302275847901 </code></pre>
2
2009-08-31T20:21:02Z
1,359,274
<p>Just use a <code>for</code> loop:</p> <pre><code>aprime = [] bprime = [] for a1, b1, c1 in zip(a, b, c): if c1 == 0: aprime.append(a1) bprime.append(b1) </code></pre>
4
2009-08-31T20:32:00Z
[ "python" ]
Generate two lists at once
1,359,232
<p><strong>Background</strong></p> <p>The algorithm manipulates financial analytics. There are multiple lists of the same size and they are filtered into other lists for analysis. I am doing the same filtering on different by parallel lists. I could set it up so that a1,b1,c2 occur as a tuple in a list but then the analytics have to stripe the tuples the other way to do analysis (regression of one list against the other, beta, etc.).</p> <p><strong>What I want to do</strong></p> <p>I want to generate two different lists based on a third list:</p> <pre><code>&gt;&gt;&gt; a = list(range(10)) &gt;&gt;&gt; b = list(range(10,20)) &gt;&gt;&gt; c = list(i &amp; 1 for i in range(10)) &gt;&gt;&gt; &gt;&gt;&gt; aprime = [a1 for a1, c1 in zip(a,c) if c1 == 0] &gt;&gt;&gt; bprime = [b1 for b1, c1 in zip(b,c) if c1 == 0] &gt;&gt;&gt; aprime [0, 2, 4, 6, 8] &gt;&gt;&gt; bprime [10, 12, 14, 16, 18] </code></pre> <p>It seems there should be a pythonic/functional programming/itertools way to create the two lists and iterate over the three lists only once. Something like:</p> <pre><code>aprime, bprime = [a1, b1 for a1, b1, c1 in zip(a,b,c) if c1 == 0] </code></pre> <p>But of course this generates a syntax error.</p> <p><strong>The question</strong></p> <p>Is there a pythonic way?</p> <p><strong>Micro-optimization shootout</strong></p> <p>The ugly but pythonic-to-the-max one-liner edges out the "just use a for-loop" solution and my original code in the ever popular <em>timeit</em> cage match:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn zip(*[(a1,b1) for a1,b1,c1 in zip(a,b,c) if c1==0])\n") 26.977873025761482 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\taprime, bprime = [], [];\n\tfor a1, b1, c1 in zip(a, b, c):\n\t\tif c1 == 0:\n\t\t\taprime.append(a1); bprime.append(b1);\n\treturn aprime, bprime\n") 32.232914169258947 &gt;&gt;&gt; timeit.timeit("z2(a,b,c)", "n=100;a = list(range(n)); b = list(range(10,10+n)); c = list(i &amp; 1 for i in range(n));\ndef z2(a,b,c):\n\treturn [a1 for a1, c1 in zip(a,c) if c1 == 0], [b1 for b1, c1 in zip(b,c) if c1 == 0]\n") 32.37302275847901 </code></pre>
2
2009-08-31T20:21:02Z
1,359,279
<p>This might win the ugliest code award, but it works in one line:</p> <pre><code>aprime, bprime = zip(*[(a1,b1) for a1,b1,c1 in zip(a,b,c) if c1==0]) </code></pre>
3
2009-08-31T20:33:29Z
[ "python" ]
Python: Run a process and kill it if it doesn't end within one hour
1,359,383
<p>I need to do the following in Python. I want to spawn a process (subprocess module?), and:</p> <ul> <li>if the process ends normally, to continue exactly from the moment it terminates;</li> <li>if, otherwise, the process "gets stuck" and doesn't terminate within (say) one hour, to kill it and continue (possibly giving it another try, in a loop).</li> </ul> <p>What is the most elegant way to accomplish this?</p>
10
2009-08-31T20:55:29Z
1,359,467
<p>The <code>subprocess</code> module will be your friend. Start the process to get a <code>Popen</code> object, then pass it to a function like this. Note that this only raises exception on timeout. If desired you can catch the exception and call the <code>kill()</code> method on the <code>Popen</code> process. (kill is new in Python 2.6, btw)</p> <pre><code>import time def wait_timeout(proc, seconds): """Wait for a process to finish, or raise exception after timeout""" start = time.time() end = start + seconds interval = min(seconds / 1000.0, .25) while True: result = proc.poll() if result is not None: return result if time.time() &gt;= end: raise RuntimeError("Process timed out") time.sleep(interval) </code></pre>
16
2009-08-31T21:17:10Z
[ "python", "process", "kill" ]
Python: Run a process and kill it if it doesn't end within one hour
1,359,383
<p>I need to do the following in Python. I want to spawn a process (subprocess module?), and:</p> <ul> <li>if the process ends normally, to continue exactly from the moment it terminates;</li> <li>if, otherwise, the process "gets stuck" and doesn't terminate within (say) one hour, to kill it and continue (possibly giving it another try, in a loop).</li> </ul> <p>What is the most elegant way to accomplish this?</p>
10
2009-08-31T20:55:29Z
10,539,952
<p>There are at least 2 ways to do this by using <a href="http://code.google.com/p/psutil/" rel="nofollow">psutil</a> as long as you know the process PID. Assuming the process is created as such:</p> <pre><code>import subprocess subp = subprocess.Popen(['progname']) </code></pre> <p>...you can get its creation time in a busy loop like this:</p> <pre><code>import psutil, time TIMEOUT = 60 * 60 # 1 hour p = psutil.Process(subp.pid) while 1: if (time.time() - p.create_time) &gt; TIMEOUT: p.kill() raise RuntimeError('timeout') time.sleep(5) </code></pre> <p>...or simply, you can do this:</p> <pre><code>import psutil p = psutil.Process(subp.pid) try p.wait(timeout=60*60) except psutil.TimeoutExpired: p.kill() raise </code></pre> <p>Also, while you're at it, you might be interested in the following extra APIs:</p> <pre><code>&gt;&gt;&gt; p.status() 'running' &gt;&gt;&gt; p.is_running() True &gt;&gt;&gt; </code></pre>
5
2012-05-10T18:19:37Z
[ "python", "process", "kill" ]
django : ImportError No module named myapp.views.hometest
1,359,449
<p>I have fecora 11, set django with mod_wsgi2.5 and apache2.2. And I can run "python manage.py runserver" at local. It works fine. I got error when i test from remote browser. </p> <p>Thanks for any suggestion and help!</p>
3
2009-08-31T21:10:12Z
1,359,482
<p>Is the application containing your Django project in your <code>$PYTHONPATH</code> (when Python is invoked in a server context)? For example, if your Django project is at <code>/home/wwwuser/web/myproj</code>, then <code>/home/wwwuser/web</code> should be in your <code>$PYTHONPATH</code>. You should set this in the script that loads the project when invoked from the web server.</p>
2
2009-08-31T21:21:35Z
[ "python", "django", "mod-wsgi" ]
django : ImportError No module named myapp.views.hometest
1,359,449
<p>I have fecora 11, set django with mod_wsgi2.5 and apache2.2. And I can run "python manage.py runserver" at local. It works fine. I got error when i test from remote browser. </p> <p>Thanks for any suggestion and help!</p>
3
2009-08-31T21:10:12Z
1,359,494
<p>Just a guess, but unless you've explicitly made sure that your app is on PYTHONPATH, you should be specifying views in urls.py as myproject.myapp.views.functionname.</p> <p>Otherwise:</p> <ul> <li>check if you're setting PYTHONPATH, or what to. Your project directory should be in there.</li> <li>if you enable the django admin (by uncommenting the lines that are there by default in urls.py), does that work?</li> </ul>
1
2009-08-31T21:23:51Z
[ "python", "django", "mod-wsgi" ]
django : ImportError No module named myapp.views.hometest
1,359,449
<p>I have fecora 11, set django with mod_wsgi2.5 and apache2.2. And I can run "python manage.py runserver" at local. It works fine. I got error when i test from remote browser. </p> <p>Thanks for any suggestion and help!</p>
3
2009-08-31T21:10:12Z
1,360,370
<ul> <li>All required env variables should be set in django.wsgi. You could compare the env declared in django.wsgi and the env of executing <code>./manage runserver</code> and make sure they are same.</li> <li>Furthermore, if there is another myapp package which could be found through PYTHONPATH before <code>/usr/local/django/myapp</code>, <code>ImportError</code> may be raised.</li> </ul>
1
2009-09-01T03:21:18Z
[ "python", "django", "mod-wsgi" ]
django : ImportError No module named myapp.views.hometest
1,359,449
<p>I have fecora 11, set django with mod_wsgi2.5 and apache2.2. And I can run "python manage.py runserver" at local. It works fine. I got error when i test from remote browser. </p> <p>Thanks for any suggestion and help!</p>
3
2009-08-31T21:10:12Z
2,978,457
<p>I just had this problem. It went away when I added <code>sys.path.append('/path/to/project')</code> to my .wsgi file.</p>
4
2010-06-04T23:47:42Z
[ "python", "django", "mod-wsgi" ]
Error while using multiprocessing module in a python daemon
1,359,795
<p>I'm getting the following error when using the <strong>multiprocessing</strong> module within a python daemon process (using <strong>python-daemon</strong>):</p> <pre> Traceback (most recent call last): File "/usr/local/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/local/lib/python2.6/multiprocessing/util.py", line 262, in _exit_function for p in active_children(): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 43, in active_children _cleanup() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 53, in _cleanup if p._popen.poll() is not None: File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 10] No child processes </pre> <p>The daemon process (parent) spawns a number of processes (children) and then periodically polls the processes to see if they have completed. If the parent detects that one of the processes has completed, it then attempts to restart that process. It is at this point that the above exception is raised. It seems that once one of the processes completes, any operation involving the multiprocessing module will generate this exception. If I run the identical code in a non-daemon python script, it executes with no errors whatsoever.</p> <p><strong>EDIT:</strong></p> <p>Sample script</p> <pre><code>from daemon import runner class DaemonApp(object): def __init__(self, pidfile_path, run): self.pidfile_path = pidfile_path self.run = run self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' def run(): import multiprocessing as processing import time import os import sys import signal def func(): print 'pid: ', os.getpid() for i in range(5): print i time.sleep(1) process = processing.Process(target=func) process.start() while True: print 'checking process' if not process.is_alive(): print 'process dead' process = processing.Process(target=func) process.start() time.sleep(1) # uncomment to run as daemon app = DaemonApp('/root/bugtest.pid', run) daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() #uncomment to run as regular script #run() </code></pre>
5
2009-08-31T23:02:05Z
1,360,108
<p>I think there was a fix put into trunk and 2.6 maint a little while ago which should help with this can you try running your script in python-trunk or the latest 2.6-maint svn? I'm failing to pull up the bug information</p>
0
2009-09-01T01:01:06Z
[ "python", "daemon", "multiprocessing" ]
Error while using multiprocessing module in a python daemon
1,359,795
<p>I'm getting the following error when using the <strong>multiprocessing</strong> module within a python daemon process (using <strong>python-daemon</strong>):</p> <pre> Traceback (most recent call last): File "/usr/local/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/local/lib/python2.6/multiprocessing/util.py", line 262, in _exit_function for p in active_children(): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 43, in active_children _cleanup() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 53, in _cleanup if p._popen.poll() is not None: File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 10] No child processes </pre> <p>The daemon process (parent) spawns a number of processes (children) and then periodically polls the processes to see if they have completed. If the parent detects that one of the processes has completed, it then attempts to restart that process. It is at this point that the above exception is raised. It seems that once one of the processes completes, any operation involving the multiprocessing module will generate this exception. If I run the identical code in a non-daemon python script, it executes with no errors whatsoever.</p> <p><strong>EDIT:</strong></p> <p>Sample script</p> <pre><code>from daemon import runner class DaemonApp(object): def __init__(self, pidfile_path, run): self.pidfile_path = pidfile_path self.run = run self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' def run(): import multiprocessing as processing import time import os import sys import signal def func(): print 'pid: ', os.getpid() for i in range(5): print i time.sleep(1) process = processing.Process(target=func) process.start() while True: print 'checking process' if not process.is_alive(): print 'process dead' process = processing.Process(target=func) process.start() time.sleep(1) # uncomment to run as daemon app = DaemonApp('/root/bugtest.pid', run) daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() #uncomment to run as regular script #run() </code></pre>
5
2009-08-31T23:02:05Z
1,360,375
<p>Looks like your error is coming at the very end of your process -- your clue's at the very start of your traceback, and I quote...:</p> <pre><code>File "/usr/local/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) </code></pre> <p>if <code>atexit._run_exitfuncs</code> is running, this clearly shows that your own process is terminating. So, the error itself is a minor issue in a sense -- just from some function that the <code>multiprocessing</code> module registered to run "at-exit" from your process. The really interesting issue is, WHY is your main process exiting? I think this may be due to some uncaught exception: try setting the exception hook and showing rich diagnostic info before it gets lost by the OTHER exception caused by whatever it is that multiprocessing's registered for at-exit running...</p>
0
2009-09-01T03:24:06Z
[ "python", "daemon", "multiprocessing" ]
Error while using multiprocessing module in a python daemon
1,359,795
<p>I'm getting the following error when using the <strong>multiprocessing</strong> module within a python daemon process (using <strong>python-daemon</strong>):</p> <pre> Traceback (most recent call last): File "/usr/local/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/local/lib/python2.6/multiprocessing/util.py", line 262, in _exit_function for p in active_children(): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 43, in active_children _cleanup() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 53, in _cleanup if p._popen.poll() is not None: File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 10] No child processes </pre> <p>The daemon process (parent) spawns a number of processes (children) and then periodically polls the processes to see if they have completed. If the parent detects that one of the processes has completed, it then attempts to restart that process. It is at this point that the above exception is raised. It seems that once one of the processes completes, any operation involving the multiprocessing module will generate this exception. If I run the identical code in a non-daemon python script, it executes with no errors whatsoever.</p> <p><strong>EDIT:</strong></p> <p>Sample script</p> <pre><code>from daemon import runner class DaemonApp(object): def __init__(self, pidfile_path, run): self.pidfile_path = pidfile_path self.run = run self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' def run(): import multiprocessing as processing import time import os import sys import signal def func(): print 'pid: ', os.getpid() for i in range(5): print i time.sleep(1) process = processing.Process(target=func) process.start() while True: print 'checking process' if not process.is_alive(): print 'process dead' process = processing.Process(target=func) process.start() time.sleep(1) # uncomment to run as daemon app = DaemonApp('/root/bugtest.pid', run) daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() #uncomment to run as regular script #run() </code></pre>
5
2009-08-31T23:02:05Z
1,419,952
<p>I'm running into this also using the celery distributed task manager under RHEL 5.3 with Python 2.6. My traceback looks a little different but the error the same:</p> <pre><code> File "/usr/local/lib/python2.6/multiprocessing/pool.py", line 334, in terminate self._terminate() File "/usr/local/lib/python2.6/multiprocessing/util.py", line 174, in __call__ res = self._callback(*self._args, **self._kwargs) File "/usr/local/lib/python2.6/multiprocessing/pool.py", line 373, in _terminate_pool p.terminate() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 111, in terminate self._popen.terminate() File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 136, in terminate if self.wait(timeout=0.1) is None: File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 121, in wait res = self.poll() File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 10] No child processes </code></pre> <p>Quite frustrating.. I'm running the code through pdb now, but haven't spotted anything yet.</p>
0
2009-09-14T06:25:02Z
[ "python", "daemon", "multiprocessing" ]
Error while using multiprocessing module in a python daemon
1,359,795
<p>I'm getting the following error when using the <strong>multiprocessing</strong> module within a python daemon process (using <strong>python-daemon</strong>):</p> <pre> Traceback (most recent call last): File "/usr/local/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/local/lib/python2.6/multiprocessing/util.py", line 262, in _exit_function for p in active_children(): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 43, in active_children _cleanup() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 53, in _cleanup if p._popen.poll() is not None: File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 10] No child processes </pre> <p>The daemon process (parent) spawns a number of processes (children) and then periodically polls the processes to see if they have completed. If the parent detects that one of the processes has completed, it then attempts to restart that process. It is at this point that the above exception is raised. It seems that once one of the processes completes, any operation involving the multiprocessing module will generate this exception. If I run the identical code in a non-daemon python script, it executes with no errors whatsoever.</p> <p><strong>EDIT:</strong></p> <p>Sample script</p> <pre><code>from daemon import runner class DaemonApp(object): def __init__(self, pidfile_path, run): self.pidfile_path = pidfile_path self.run = run self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' def run(): import multiprocessing as processing import time import os import sys import signal def func(): print 'pid: ', os.getpid() for i in range(5): print i time.sleep(1) process = processing.Process(target=func) process.start() while True: print 'checking process' if not process.is_alive(): print 'process dead' process = processing.Process(target=func) process.start() time.sleep(1) # uncomment to run as daemon app = DaemonApp('/root/bugtest.pid', run) daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() #uncomment to run as regular script #run() </code></pre>
5
2009-08-31T23:02:05Z
1,423,690
<p>The original sample script has "import signal" but no use of signals. However, I had a script causing this error message and it was due to my signal handling, so I'll explain here in case its what is happening for others. Within a signal handler, I was doing stuff with processes (e.g. creating a new process). Apparently this doesn't work, so I stopped doing that within the handler and fixed the error. (Note: sleep() functions wake up after signal handling so that can be an alternative approach to acting upon signals if you need to do things with processes)</p>
0
2009-09-14T20:20:25Z
[ "python", "daemon", "multiprocessing" ]
Error while using multiprocessing module in a python daemon
1,359,795
<p>I'm getting the following error when using the <strong>multiprocessing</strong> module within a python daemon process (using <strong>python-daemon</strong>):</p> <pre> Traceback (most recent call last): File "/usr/local/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/local/lib/python2.6/multiprocessing/util.py", line 262, in _exit_function for p in active_children(): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 43, in active_children _cleanup() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 53, in _cleanup if p._popen.poll() is not None: File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 10] No child processes </pre> <p>The daemon process (parent) spawns a number of processes (children) and then periodically polls the processes to see if they have completed. If the parent detects that one of the processes has completed, it then attempts to restart that process. It is at this point that the above exception is raised. It seems that once one of the processes completes, any operation involving the multiprocessing module will generate this exception. If I run the identical code in a non-daemon python script, it executes with no errors whatsoever.</p> <p><strong>EDIT:</strong></p> <p>Sample script</p> <pre><code>from daemon import runner class DaemonApp(object): def __init__(self, pidfile_path, run): self.pidfile_path = pidfile_path self.run = run self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' def run(): import multiprocessing as processing import time import os import sys import signal def func(): print 'pid: ', os.getpid() for i in range(5): print i time.sleep(1) process = processing.Process(target=func) process.start() while True: print 'checking process' if not process.is_alive(): print 'process dead' process = processing.Process(target=func) process.start() time.sleep(1) # uncomment to run as daemon app = DaemonApp('/root/bugtest.pid', run) daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() #uncomment to run as regular script #run() </code></pre>
5
2009-08-31T23:02:05Z
1,431,666
<p>Your problem is a conflict between the daemon and multiprocessing modules, in particular in its handling of the SIGCLD (child process terminated) signal. daemon sets SIGCLD to SIG_IGN when launching, which, at least on Linux, causes terminated children to immediately be reaped (rather than becoming a zombie until the parent invokes wait()). But multiprocessing's is_alive test invokes wait() to see if the process is alive, which fails if the process has already been reaped.</p> <p>Simplest solution is just to set SIGCLD back to SIG_DFL (default behaviour -- ignore the signal and let the parent wait() for the terminated child process):</p> <pre><code>def run(): # ... signal.signal(signal.SIGCLD, signal.SIG_DFL) process = processing.Process(target=func) process.start() while True: # ... </code></pre>
5
2009-09-16T08:24:54Z
[ "python", "daemon", "multiprocessing" ]
Error while using multiprocessing module in a python daemon
1,359,795
<p>I'm getting the following error when using the <strong>multiprocessing</strong> module within a python daemon process (using <strong>python-daemon</strong>):</p> <pre> Traceback (most recent call last): File "/usr/local/lib/python2.6/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/usr/local/lib/python2.6/multiprocessing/util.py", line 262, in _exit_function for p in active_children(): File "/usr/local/lib/python2.6/multiprocessing/process.py", line 43, in active_children _cleanup() File "/usr/local/lib/python2.6/multiprocessing/process.py", line 53, in _cleanup if p._popen.poll() is not None: File "/usr/local/lib/python2.6/multiprocessing/forking.py", line 106, in poll pid, sts = os.waitpid(self.pid, flag) OSError: [Errno 10] No child processes </pre> <p>The daemon process (parent) spawns a number of processes (children) and then periodically polls the processes to see if they have completed. If the parent detects that one of the processes has completed, it then attempts to restart that process. It is at this point that the above exception is raised. It seems that once one of the processes completes, any operation involving the multiprocessing module will generate this exception. If I run the identical code in a non-daemon python script, it executes with no errors whatsoever.</p> <p><strong>EDIT:</strong></p> <p>Sample script</p> <pre><code>from daemon import runner class DaemonApp(object): def __init__(self, pidfile_path, run): self.pidfile_path = pidfile_path self.run = run self.stdin_path = '/dev/null' self.stdout_path = '/dev/tty' self.stderr_path = '/dev/tty' def run(): import multiprocessing as processing import time import os import sys import signal def func(): print 'pid: ', os.getpid() for i in range(5): print i time.sleep(1) process = processing.Process(target=func) process.start() while True: print 'checking process' if not process.is_alive(): print 'process dead' process = processing.Process(target=func) process.start() time.sleep(1) # uncomment to run as daemon app = DaemonApp('/root/bugtest.pid', run) daemon_runner = runner.DaemonRunner(app) daemon_runner.do_action() #uncomment to run as regular script #run() </code></pre>
5
2009-08-31T23:02:05Z
1,439,684
<p>Ignoring <code>SIGCLD</code> also causes problems with the <code>subprocess</code> module, because of a bug in that module (<a href="http://bugs.python.org/issue1731717" rel="nofollow">issue 1731717</a>, still open as of 2011-09-21).</p> <p>This behaviour is addressed in <a href="http://pypi.python.org/pypi/python-daemon/1.4.8/" rel="nofollow">version 1.4.8</a> of the <code>python-daemon</code> library; it now omits the default fiddling with <code>SIGCLD</code>, so no longer has this unpleasant interaction with other standard library modules.</p>
4
2009-09-17T15:45:43Z
[ "python", "daemon", "multiprocessing" ]
Killing the background window when running a .exe from a Python program
1,360,066
<p>the following is a line from a python program that calls the "demo.exe" file. a window for demo.exe opens when it is called, is there any way for demo.exe to run in the "background"? that is, i don't want the window for it show, i just want demo.exe to run.</p> <p><pre><code> p = subprocess.Popen(args = "demo.exe", stdout = subprocess.PIPE) </pre></code></p> <p>the output of demo.exe is used by the python program in real time, so demo.exe is not something that i can have run in advance of running the python program. demo.exe handles a lot of on the fly back-end calculations. i'm using windows xp.</p> <p>thanks in advance!</p>
2
2009-09-01T00:42:08Z
1,360,088
<p>Try this:</p> <pre><code>from subprocess import Popen, PIPE, STARTUPINFO, STARTF_USESHOWWINDOW startupinfo = STARTUPINFO() startupinfo.dwFlags |= STARTF_USESHOWWINDOW p = Popen(cmdlist, startupinfo=startupinfo, ...) </code></pre>
3
2009-09-01T00:51:40Z
[ "python", "executable" ]
Killing the background window when running a .exe from a Python program
1,360,066
<p>the following is a line from a python program that calls the "demo.exe" file. a window for demo.exe opens when it is called, is there any way for demo.exe to run in the "background"? that is, i don't want the window for it show, i just want demo.exe to run.</p> <p><pre><code> p = subprocess.Popen(args = "demo.exe", stdout = subprocess.PIPE) </pre></code></p> <p>the output of demo.exe is used by the python program in real time, so demo.exe is not something that i can have run in advance of running the python program. demo.exe handles a lot of on the fly back-end calculations. i'm using windows xp.</p> <p>thanks in advance!</p>
2
2009-09-01T00:42:08Z
1,360,102
<p>Thanks to <a href="http://stackoverflow.com/questions/1016384/cross-platform-subprocess-with-hidden-window">another StackOverflow thread</a>, I think this is what you need:</p> <pre><code>startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(args = "demo.exe", stdout=subprocess.PIPE, startupinfo=startupinfo) </code></pre> <p>I tested on my Python 2.6 on XP and it does indeed hide the window.</p>
4
2009-09-01T00:58:43Z
[ "python", "executable" ]
Generating a list from complex dictionary
1,360,507
<p>I have a dictionary <code>dict1['a'] = [ [1,2], [3,4] ]</code> and need to generate a list out of it as <code>l1 = [2, 4]</code>. That is, a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as <code>dict1['a'] = [2,4]</code>.</p>
2
2009-09-01T04:17:35Z
1,360,514
<p>Given a list:</p> <pre><code>&gt;&gt;&gt; lst = [ [1,2], [3,4] ] </code></pre> <p>You can extract the second element of each sublist with a simple list comprehension:</p> <pre><code>&gt;&gt;&gt; [x[1] for x in lst] [2, 4] </code></pre> <p>If you want to do this for every value in a dictionary, you can iterate over the dictionary. I'm not sure exactly what you want your final data to look like, but something like this may help:</p> <pre><code>&gt;&gt;&gt; dict1 = {} &gt;&gt;&gt; dict1['a'] = [ [1,2], [3,4] ] &gt;&gt;&gt; [(k, [x[1] for x in v]) for k, v in dict1.items()] [('a', [2, 4])] </code></pre> <p><code>dict.items()</code> returns (key, value) pairs from the dictionary, as a list. So this code will extract each key in your dictionary and pair it with a list generated as above.</p>
8
2009-09-01T04:22:45Z
[ "python-3.x", "python" ]
Generating a list from complex dictionary
1,360,507
<p>I have a dictionary <code>dict1['a'] = [ [1,2], [3,4] ]</code> and need to generate a list out of it as <code>l1 = [2, 4]</code>. That is, a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as <code>dict1['a'] = [2,4]</code>.</p>
2
2009-09-01T04:17:35Z
1,360,566
<blockquote> <p>a list out of the second element of each inner list</p> </blockquote> <p>that sounds like <code>[sl[1] for sl in dict1['a']]</code> -- so what's the QUESTION?!-)</p>
0
2009-09-01T04:46:58Z
[ "python-3.x", "python" ]
Generating a list from complex dictionary
1,360,507
<p>I have a dictionary <code>dict1['a'] = [ [1,2], [3,4] ]</code> and need to generate a list out of it as <code>l1 = [2, 4]</code>. That is, a list out of the second element of each inner list. It can be a separate list or even the dictionary can be modified as <code>dict1['a'] = [2,4]</code>.</p>
2
2009-09-01T04:17:35Z
1,360,674
<p>Assuming that each value in the dictionary is a list of pairs, then this should do it for you:</p> <pre><code>[pair[1] for pairlist in dict1.values() for pair in pairlist] </code></pre> <p>As you can see:</p> <ul> <li><code>dict1.values()</code> gets you just the values in your dict,</li> <li><code>for pairlist in dict1.values()</code> gets you all the lists of pairs,</li> <li><code>for pair in pairlist</code> gets you all the pairs in each of those lists,</li> <li>and <code>pair[1]</code> gets you the second value in each pair.</li> </ul> <p>Try it out. The Python shell is your friend!...</p> <pre><code>&gt;&gt;&gt; dict1 = {} &gt;&gt;&gt; dict1['a'] = [[1,2], [3,4]] &gt;&gt;&gt; dict1['b'] = [[5, 6], [42, 69], [220, 284]] &gt;&gt;&gt; &gt;&gt;&gt; dict1.values() [[[1, 2], [3, 4]], [[5, 6], [42, 69], [220, 284]]] &gt;&gt;&gt; &gt;&gt;&gt; [pairlist for pairlist in dict1.values()] [[[1, 2], [3, 4]], [[5, 6], [42, 69], [220, 284]]] &gt;&gt;&gt; # No real difference here, but we can refer to each list now. &gt;&gt;&gt; &gt;&gt;&gt; [pair for pairlist in dict1.values() for pair in pairlist] [[1, 2], [3, 4], [5, 6], [42, 69], [220, 284]] &gt;&gt;&gt; &gt;&gt;&gt; # Finally... &gt;&gt;&gt; [pair[1] for pairlist in dict1.values() for pair in pairlist] [2, 4, 6, 69, 284] </code></pre> <p>While I'm at it, I'll just say: <a href="http://ipython.scipy.org/moin/" rel="nofollow">ipython</a> loves you!</p>
2
2009-09-01T05:28:48Z
[ "python-3.x", "python" ]
How to get/set local variables of a function (from outside) in Python?
1,360,721
<p>If I have a function (in Python 2.5.2) like:</p> <pre><code>def sample_func(): a = 78 b = range(5) #c = a + b[2] - x </code></pre> <p>My questions are:</p> <ol> <li>How to get the local variables (a,b) of the function from outside <strong>without</strong> using <em>locals()</em> inside the function? (kind of reflection)</li> <li>Is it possible to set a local variable (say <strong><em>x</em></strong>) from outside so that the commented line works? (I know it sounds weird).</li> </ol> <p>Thanks in advance.</p> <p><strong>EDIT</strong>:</p> <p>Everyone is asking for a use-case. But it is a weird situation. (Don't blame me, I did not create it). Here is the scenario:</p> <ol> <li>I have an encrypted python source file containing a python function.</li> <li>A C extension module decrypts it and builds that function in-memory.</li> <li>A main python program first calls the C extension with that encrypted file location.</li> <li>Then the main program calls the function that has been built in-memory (by the C extension)</li> <li>But main program needs to know the local variables of that function (Dont ask me why, it was not me)</li> <li>For some (damn) reason, main program needs to set a variable too (weirdest of all)</li> </ol>
3
2009-09-01T05:50:41Z
1,360,732
<p>I'm not sure what your use-case is, but this may work better as a class. You can define the <code>__call__</code> method to make a class behave like a function.</p> <p>e.g.:</p> <pre><code>&gt;&gt;&gt; class sample_func(object): ... def __init__(self): ... self.a = 78 ... self.b = range(5) ... def __call__(self): ... print self.a, self.b, self.x ... &gt;&gt;&gt; f = sample_func() &gt;&gt;&gt; print f.a 78 &gt;&gt;&gt; f.x = 3 &gt;&gt;&gt; f() 78 [0, 1, 2, 3, 4] 3 </code></pre> <p>(this is based on your toy example, so the code doesn't make much sense. If you give more details, we may be able to provide better advice)</p>
6
2009-09-01T05:54:15Z
[ "python" ]
How to get/set local variables of a function (from outside) in Python?
1,360,721
<p>If I have a function (in Python 2.5.2) like:</p> <pre><code>def sample_func(): a = 78 b = range(5) #c = a + b[2] - x </code></pre> <p>My questions are:</p> <ol> <li>How to get the local variables (a,b) of the function from outside <strong>without</strong> using <em>locals()</em> inside the function? (kind of reflection)</li> <li>Is it possible to set a local variable (say <strong><em>x</em></strong>) from outside so that the commented line works? (I know it sounds weird).</li> </ol> <p>Thanks in advance.</p> <p><strong>EDIT</strong>:</p> <p>Everyone is asking for a use-case. But it is a weird situation. (Don't blame me, I did not create it). Here is the scenario:</p> <ol> <li>I have an encrypted python source file containing a python function.</li> <li>A C extension module decrypts it and builds that function in-memory.</li> <li>A main python program first calls the C extension with that encrypted file location.</li> <li>Then the main program calls the function that has been built in-memory (by the C extension)</li> <li>But main program needs to know the local variables of that function (Dont ask me why, it was not me)</li> <li>For some (damn) reason, main program needs to set a variable too (weirdest of all)</li> </ol>
3
2009-09-01T05:50:41Z
1,360,794
<p>The function's locals change whenever the function is run, so there's little meaning to access them while the function isn't running.</p>
1
2009-09-01T06:16:10Z
[ "python" ]
How to get/set local variables of a function (from outside) in Python?
1,360,721
<p>If I have a function (in Python 2.5.2) like:</p> <pre><code>def sample_func(): a = 78 b = range(5) #c = a + b[2] - x </code></pre> <p>My questions are:</p> <ol> <li>How to get the local variables (a,b) of the function from outside <strong>without</strong> using <em>locals()</em> inside the function? (kind of reflection)</li> <li>Is it possible to set a local variable (say <strong><em>x</em></strong>) from outside so that the commented line works? (I know it sounds weird).</li> </ol> <p>Thanks in advance.</p> <p><strong>EDIT</strong>:</p> <p>Everyone is asking for a use-case. But it is a weird situation. (Don't blame me, I did not create it). Here is the scenario:</p> <ol> <li>I have an encrypted python source file containing a python function.</li> <li>A C extension module decrypts it and builds that function in-memory.</li> <li>A main python program first calls the C extension with that encrypted file location.</li> <li>Then the main program calls the function that has been built in-memory (by the C extension)</li> <li>But main program needs to know the local variables of that function (Dont ask me why, it was not me)</li> <li>For some (damn) reason, main program needs to set a variable too (weirdest of all)</li> </ol>
3
2009-09-01T05:50:41Z
1,361,058
<p>No. A function that isn't being run doesn't have locals; it's just a function. Asking how to modify a function's locals when it's not running is like asking how to modify a program's heap when it's not running.</p> <p>You can modify constants, though, if you really want to.</p> <pre><code>def func(): a = 10 print a co = func.func_code modified_consts = list(co.co_consts) for idx, val in enumerate(modified_consts): if modified_consts[idx] == 10: modified_consts[idx] = 15 modified_consts = tuple(modified_consts) import types modified_code = types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, modified_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab) modified_func = types.FunctionType(modified_code, func.func_globals) # 15: modified_func() </code></pre> <p>It's a hack, because there's no way to know which constant in co.co_consts is which; this uses a sentinel value to figure it out. Depending on whether you can constrain your use cases enough, that might be enough.</p>
12
2009-09-01T07:34:41Z
[ "python" ]
How to get/set local variables of a function (from outside) in Python?
1,360,721
<p>If I have a function (in Python 2.5.2) like:</p> <pre><code>def sample_func(): a = 78 b = range(5) #c = a + b[2] - x </code></pre> <p>My questions are:</p> <ol> <li>How to get the local variables (a,b) of the function from outside <strong>without</strong> using <em>locals()</em> inside the function? (kind of reflection)</li> <li>Is it possible to set a local variable (say <strong><em>x</em></strong>) from outside so that the commented line works? (I know it sounds weird).</li> </ol> <p>Thanks in advance.</p> <p><strong>EDIT</strong>:</p> <p>Everyone is asking for a use-case. But it is a weird situation. (Don't blame me, I did not create it). Here is the scenario:</p> <ol> <li>I have an encrypted python source file containing a python function.</li> <li>A C extension module decrypts it and builds that function in-memory.</li> <li>A main python program first calls the C extension with that encrypted file location.</li> <li>Then the main program calls the function that has been built in-memory (by the C extension)</li> <li>But main program needs to know the local variables of that function (Dont ask me why, it was not me)</li> <li>For some (damn) reason, main program needs to set a variable too (weirdest of all)</li> </ol>
3
2009-09-01T05:50:41Z
1,364,790
<p>Not sure if this is what you mean, but as functions are objects in Python you can bind variables to a function object and access them from 'outside':</p> <pre><code>def fa(): print 'x value of fa() when entering fa(): %s' % fa.x print 'y value of fb() when entering fa(): %s' % fb.y fa.x += fb.y print 'x value of fa() after calculation in fa(): %s' % fa.x print 'y value of fb() after calculation in fa(): %s' % fb.y fa.count +=1 def fb(): print 'y value of fb() when entering fb(): %s' % fb.y print 'x value of fa() when entering fa(): %s' % fa.x fb.y += fa.x print 'y value of fb() after calculation in fb(): %s' % fb.y print 'x value of fa() after calculation in fb(): %s' % fa.x print 'From fb() is see fa() has been called %s times' % fa.count fa.x,fb.y,fa.count = 1,1,1 for i in range(10): fa() fb() </code></pre> <p>Please excuse me if I am terribly wrong... I´m a Python and programming beginner myself...</p>
1
2009-09-01T21:44:02Z
[ "python" ]
How to get/set local variables of a function (from outside) in Python?
1,360,721
<p>If I have a function (in Python 2.5.2) like:</p> <pre><code>def sample_func(): a = 78 b = range(5) #c = a + b[2] - x </code></pre> <p>My questions are:</p> <ol> <li>How to get the local variables (a,b) of the function from outside <strong>without</strong> using <em>locals()</em> inside the function? (kind of reflection)</li> <li>Is it possible to set a local variable (say <strong><em>x</em></strong>) from outside so that the commented line works? (I know it sounds weird).</li> </ol> <p>Thanks in advance.</p> <p><strong>EDIT</strong>:</p> <p>Everyone is asking for a use-case. But it is a weird situation. (Don't blame me, I did not create it). Here is the scenario:</p> <ol> <li>I have an encrypted python source file containing a python function.</li> <li>A C extension module decrypts it and builds that function in-memory.</li> <li>A main python program first calls the C extension with that encrypted file location.</li> <li>Then the main program calls the function that has been built in-memory (by the C extension)</li> <li>But main program needs to know the local variables of that function (Dont ask me why, it was not me)</li> <li>For some (damn) reason, main program needs to set a variable too (weirdest of all)</li> </ol>
3
2009-09-01T05:50:41Z
1,375,287
<p>Expecting a variable in a function to be set by an outside function BEFORE that function is called is such bad design that the only real answer I can recommend is changing the design. A function that expects its internal variables to be set before it is run is useless.</p> <p>So the real question you have to ask is why does that function expect x to be defined outside the function? Does the original program that function use to belong to set a global variable that function would have had access to? If so, then it might be as easy as suggesting to the original authors of that function that they instead allow x to be passed in as an argument. A simple change in your sample function would make the code work in both situations:</p> <pre><code>def sample_func(x_local=None): if not x_local: x_local = x a = 78 b = range(5) c = a + b[2] - x_local </code></pre> <p>This will allow the function to accept a parameter from your main function the way you want to use it, but it will not break the other program as it will still use the globally defined x if the function is not given any arguments.</p>
1
2009-09-03T18:57:56Z
[ "python" ]
stop python object going out of scope in c++
1,361,028
<p>Is there a way to transfer a new class instance (python class that inherits c++ class) into c++ with out having to hold on to the object return and just treat it as a c++ pointer.</p> <p>For example:</p> <p>C++</p> <pre><code>object pyInstance = GetLocalDict()["makeNewGamePlay"](); CGEPYGameMode* m_pGameMode = extract&lt; CGEPYGameMode* &gt;( pyInstance ); </code></pre> <p>pyth:</p> <pre><code>class Alpha(CGEPYGameMode): def someFunct(self): pass def makeNewGamePlay(): return Alpha() </code></pre> <p>pyInstance is the python class instance and m_pGameMode is a pointer to the c++ baseclass of the same instance. However if i store the pointer and let the object go out of scope, the python object is cleaned up. Is there any way to only have the c++ pointer with out the object getting cleaned up?</p> <p>More info: <a href="http://stackoverflow.com/questions/1355187/python-object-to-native-c-pointer">http://stackoverflow.com/questions/1355187/python-object-to-native-c-pointer</a></p>
0
2009-09-01T07:28:21Z
1,361,575
<p>You must increment the <a href="http://docs.python.org/extending/extending.html#reference-counting-in-python" rel="nofollow">reference count</a> of the pyInstance. That will prevent Python from deleting it. When you are ready to delete it, you can simply decrement the reference count and Python will clean it up for you.</p>
2
2009-09-01T09:53:45Z
[ "c++", "python", "boost", "object" ]
KeyboardInterrupt in Windows?
1,361,217
<p>How to generate a KeyboardInterrupt in Windows? </p> <pre><code>while True: try: print 'running' except KeyboardInterrupt: break </code></pre> <p>I expected <kbd>CTRL+C</kbd> to stop this program but it doesn't work.</p>
0
2009-09-01T08:22:24Z
1,361,524
<p>Your code is working ok when ran into a windows console.</p> <p>Ctrl+C generating a KeyboardInterrupt is a console feature. If you run it from a text editor like SciTE, it will not work.</p>
2
2009-09-01T09:39:59Z
[ "python", "windows", "keyboardinterrupt" ]
import csv file into mysql database using django web application
1,361,357
<p>thanks guys.i managed to complete it.million thanks again specially for DAVID,WM-EDDIE and S.LOTT.also STACKOVERFLOW</p> <p>The solution:</p> <pre><code> **model = Contact() model.contact_owner = request.user model.contact_name = row[1] model.contact_mobile_no = row[2] model.select_group = row[3] model.save()** </code></pre> <p>my user.py</p> <pre><code>def import_contact(request): if request.method == 'POST': form = UploadContactForm(request.POST, request.FILES) if form.is_valid(): csvfile = request.FILES['file'] print csvfile csvfile.read() testReader = csv.reader(csvfile,delimiter=' ', quotechar='|') **#what code should i write here to store data in mysql** for row in testReader: print "|".join(row) return HttpResponseRedirect('/admin') else: form = UploadContactForm() vars = RequestContext(request, { 'form': form }) return render_to_response('admin/import_contact.html', vars) </code></pre> <p>the data in csv file:</p> <p>abubakar,rooney,0178222123,student</p> <p>abubakar,ronaldo,0183886789,student</p> <p>abubakar,kaka,0197887898,bola</p> <p><strong>appreciated any suggestion.and hopefully can show me some coding example coz i'm still beginner in this language</strong></p> <p>my models.py:</p> <pre><code>class Contact(models.Model): contact_owner = models.ForeignKey(User, related_name="contacts") contact_name = models.CharField(max_length=20) contact_mobile_no = models.CharField(max_length=20) select_group = models.CharField(max_length=20, null=True) def __unicode__(self): return "contact {contact_owner=%s, contact_name=%s, contact_mobile_no=%s, select_group=%s}" % (self.contact_owner, self.contact_name, self.contact_mobile_no, self.select_group) </code></pre>
2
2009-09-01T09:00:16Z
1,361,418
<p>To tokenize a comma separated string:</p> <pre><code>&gt;&gt;&gt; a = 'abubakar,rooney,0178222123,student abubakar,rooneyzzz,0178222164' &gt;&gt;&gt; b = a.split(',') &gt;&gt;&gt; print b ['abubakar', 'rooney', '0178222123', 'student abubakar', 'rooneyzzz', '0178222164'] </code></pre> <p>See @wm_eddie's answer for how to create a new entry in your db.</p>
0
2009-09-01T09:13:54Z
[ "python", "django" ]
import csv file into mysql database using django web application
1,361,357
<p>thanks guys.i managed to complete it.million thanks again specially for DAVID,WM-EDDIE and S.LOTT.also STACKOVERFLOW</p> <p>The solution:</p> <pre><code> **model = Contact() model.contact_owner = request.user model.contact_name = row[1] model.contact_mobile_no = row[2] model.select_group = row[3] model.save()** </code></pre> <p>my user.py</p> <pre><code>def import_contact(request): if request.method == 'POST': form = UploadContactForm(request.POST, request.FILES) if form.is_valid(): csvfile = request.FILES['file'] print csvfile csvfile.read() testReader = csv.reader(csvfile,delimiter=' ', quotechar='|') **#what code should i write here to store data in mysql** for row in testReader: print "|".join(row) return HttpResponseRedirect('/admin') else: form = UploadContactForm() vars = RequestContext(request, { 'form': form }) return render_to_response('admin/import_contact.html', vars) </code></pre> <p>the data in csv file:</p> <p>abubakar,rooney,0178222123,student</p> <p>abubakar,ronaldo,0183886789,student</p> <p>abubakar,kaka,0197887898,bola</p> <p><strong>appreciated any suggestion.and hopefully can show me some coding example coz i'm still beginner in this language</strong></p> <p>my models.py:</p> <pre><code>class Contact(models.Model): contact_owner = models.ForeignKey(User, related_name="contacts") contact_name = models.CharField(max_length=20) contact_mobile_no = models.CharField(max_length=20) select_group = models.CharField(max_length=20, null=True) def __unicode__(self): return "contact {contact_owner=%s, contact_name=%s, contact_mobile_no=%s, select_group=%s}" % (self.contact_owner, self.contact_name, self.contact_mobile_no, self.select_group) </code></pre>
2
2009-09-01T09:00:16Z
1,361,462
<p>Python's manuals are pretty bad. You are "supposed" to infer that because they use the string.join() that row works like an list. So pretty much it parses the CSV file into a list of lists. It takes care of all the nasty quoting, and escaping for you.</p> <p>You use it just like you would use an array/list</p> <pre><code>for row in testReader: model = YourModel() model.property_a = row[0] model.property_b = row[1] model.save() </code></pre> <p>There's also a DictReader which allows you to write a more readable:</p> <pre><code>for row in testReader: model = YourModel() model.property_a = row["prop_a"] model.property_b = row["prop_b"] model.save() </code></pre>
0
2009-09-01T09:25:02Z
[ "python", "django" ]
import csv file into mysql database using django web application
1,361,357
<p>thanks guys.i managed to complete it.million thanks again specially for DAVID,WM-EDDIE and S.LOTT.also STACKOVERFLOW</p> <p>The solution:</p> <pre><code> **model = Contact() model.contact_owner = request.user model.contact_name = row[1] model.contact_mobile_no = row[2] model.select_group = row[3] model.save()** </code></pre> <p>my user.py</p> <pre><code>def import_contact(request): if request.method == 'POST': form = UploadContactForm(request.POST, request.FILES) if form.is_valid(): csvfile = request.FILES['file'] print csvfile csvfile.read() testReader = csv.reader(csvfile,delimiter=' ', quotechar='|') **#what code should i write here to store data in mysql** for row in testReader: print "|".join(row) return HttpResponseRedirect('/admin') else: form = UploadContactForm() vars = RequestContext(request, { 'form': form }) return render_to_response('admin/import_contact.html', vars) </code></pre> <p>the data in csv file:</p> <p>abubakar,rooney,0178222123,student</p> <p>abubakar,ronaldo,0183886789,student</p> <p>abubakar,kaka,0197887898,bola</p> <p><strong>appreciated any suggestion.and hopefully can show me some coding example coz i'm still beginner in this language</strong></p> <p>my models.py:</p> <pre><code>class Contact(models.Model): contact_owner = models.ForeignKey(User, related_name="contacts") contact_name = models.CharField(max_length=20) contact_mobile_no = models.CharField(max_length=20) select_group = models.CharField(max_length=20, null=True) def __unicode__(self): return "contact {contact_owner=%s, contact_name=%s, contact_mobile_no=%s, select_group=%s}" % (self.contact_owner, self.contact_name, self.contact_mobile_no, self.select_group) </code></pre>
2
2009-09-01T09:00:16Z
1,361,676
<p>This is approximately what we do.</p> <pre><code>header = 'contact_owner', 'contact_name', 'contact_mobile_number', 'select_group' rdr= csv.reader(request.FILES['file']) for row in rdr: data = zip( header, row ) owner, created = User.get_or_create( data['contact_owner'] data['contact_owner']= owner contact, created = Contact.get_or_create( **data ) logger.info( "Created %r", contact ) </code></pre> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs</a></p> <p>Your question says "tokenizer by comma". Your example data uses comma. But your <code>csv.reader</code> code shows spaces. Which is it? </p>
0
2009-09-01T10:19:11Z
[ "python", "django" ]
Match multiple patterns in a multiline string
1,361,373
<p>I have some data which look like that:</p> <pre><code>PMID- 19587274 OWN - NLM DP - 2009 Jul 8 TI - Domain general mechanisms of perceptual decision making in human cortex. PG - 8675-87 AB - To successfully interact with objects in the environment, sensory evidence must be continuously acquired, interpreted, and used to guide appropriate motor responses. For example, when driving, a red AD - Perception and Cognition Laboratory, Department of Psychology, University of California, San Diego, La Jolla, California 92093, USA. PMID- 19583148 OWN - NLM DP - 2009 Jun TI - Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic amyloidosis. PG - 482-6 AB - BACKGROUND: Amyloidosis represents a group of different diseases characterized by extracellular accumulation of pathologic fibrillar proteins in various tissues AD - Asklepios Hospital, Department of Medicine, Langen, Germany. innere2.longen@asklepios.com </code></pre> <p>I want to write a regex which can match the sentences which follow PMID, TI and AB.</p> <p>Is it possible to get these in a one shot regex?</p> <p>I have spent nearly the whole day to try to figure out a regex and the closest I could get is that:</p> <pre><code>reg4 = r'PMID- (?P&lt;pmid&gt;[0-9]*).*TI.*- (?P&lt;title&gt;.*)PG.*AB.*- (?P&lt;abstract&gt;.*)AD' for i in re.finditer(reg4, data, re.S | re.M): print i.groupdict() </code></pre> <p>Which will return me the matches only in the second "set" of data, and not all of them.</p> <p>Any idea? Thank you!</p>
0
2009-09-01T09:04:21Z
1,361,422
<p>How about:</p> <pre><code>import re reg4 = re.compile(r'^(?:PMID- (?P&lt;pmid&gt;[0-9]+)|TI - (?P&lt;title&gt;.*?)^PG|AB - (?P&lt;abstract&gt;.*?)^AD)', re.MULTILINE | re.DOTALL) for i in reg4.finditer(data): print i.groupdict() </code></pre> <p>Output:</p> <pre><code>{'pmid': '19587274', 'abstract': None, 'title': None} {'pmid': None, 'abstract': None, 'title': 'Domain general mechanisms of perceptual decision making in human cortex.\n'} {'pmid': None, 'abstract': 'To successfully interact with objects in the environment, sensory evidence must\n be continuously acquired, interpreted, and used to guide appropriate motor\n responses. For example, when driving, a red \n', 'title': None} {'pmid': '19583148', 'abstract': None, 'title': None} {'pmid': None, 'abstract': None, 'title': 'Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic\n amyloidosis.\n'} {'pmid': None, 'abstract': 'BACKGROUND: Amyloidosis represents a group of different diseases characterized by\n extracellular accumulation of pathologic fibrillar proteins in various tissues\n', 'title': None} </code></pre> <p><b>Edit</b></p> <p>As a verbose RE to make it more understandable (I think verbose REs should be used for anything but the simplest of expressions, but that's just my opinion!):</p> <pre><code>#!/usr/bin/python import re reg4 = re.compile(r''' ^ # Start of a line (due to re.MULTILINE, this may match at the start of any line) (?: # Non capturing group with multiple options, first option: PMID-\s # Literal "PMID-" followed by a space (?P&lt;pmid&gt;[0-9]+) # Then a string of one or more digits, group as 'pmid' | # Next option: TI\s{2}-\s # "TI", two spaces, a hyphen and a space (?P&lt;title&gt;.*?) # The title, a non greedy match that will capture everything up to... ^PG # The characters PG at the start of a line | # Next option AB\s{2}-\s # "AB - " (?P&lt;abstract&gt;.*?) # The abstract, a non greedy match that will capture everything up to... ^AD # "AD" at the start of a line ) ''', re.MULTILINE | re.DOTALL | re.VERBOSE) for i in reg4.finditer(data): print i.groupdict() </code></pre> <p>Note that you could replace the <code>^PG</code> and <code>^AD</code> with <code>^\S</code> to make it more general (you want to match everything up until the first non-space at the start of a line).</p> <p><b>Edit 2</b></p> <p>If you want to catch the whole thing in one regexp, get rid of the starting <code>(?:</code>, the ending <code>)</code> and change the <code>|</code> characters to <code>.*?</code>:</p> <pre><code>#!/usr/bin/python import re reg4 = re.compile(r''' ^ # Start of a line (due to re.MULTILINE, this may match at the start of any line) PMID-\s # Literal "PMID-" followed by a space (?P&lt;pmid&gt;[0-9]+) # Then a string of one or more digits, group as 'pmid' .*? # Next part: TI\s{2}-\s # "TI", two spaces, a hyphen and a space (?P&lt;title&gt;.*?) # The title, a non greedy match that will capture everything up to... ^PG # The characters PG at the start of a line .*? # Next option AB\s{2}-\s # "AB - " (?P&lt;abstract&gt;.*?) # The abstract, a non greedy match that will capture everything up to... ^AD # "AD" at the start of a line ''', re.MULTILINE | re.DOTALL | re.VERBOSE) for i in reg4.finditer(data): print i.groupdict() </code></pre> <p>This gives:</p> <pre><code>{'pmid': '19587274', 'abstract': 'To successfully interact with objects in the environment, sensory evidence must\n be continuously acquired, interpreted, and used to guide appropriate motor\n responses. For example, when driving, a red \n', 'title': 'Domain general mechanisms of perceptual decision making in human cortex.\n'} {'pmid': '19583148', 'abstract': 'BACKGROUND: Amyloidosis represents a group of different diseases characterized by\n extracellular accumulation of pathologic fibrillar proteins in various tissues\n', 'title': 'Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic\n amyloidosis.\n'} </code></pre>
2
2009-09-01T09:14:15Z
[ "python", "regex" ]
Match multiple patterns in a multiline string
1,361,373
<p>I have some data which look like that:</p> <pre><code>PMID- 19587274 OWN - NLM DP - 2009 Jul 8 TI - Domain general mechanisms of perceptual decision making in human cortex. PG - 8675-87 AB - To successfully interact with objects in the environment, sensory evidence must be continuously acquired, interpreted, and used to guide appropriate motor responses. For example, when driving, a red AD - Perception and Cognition Laboratory, Department of Psychology, University of California, San Diego, La Jolla, California 92093, USA. PMID- 19583148 OWN - NLM DP - 2009 Jun TI - Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic amyloidosis. PG - 482-6 AB - BACKGROUND: Amyloidosis represents a group of different diseases characterized by extracellular accumulation of pathologic fibrillar proteins in various tissues AD - Asklepios Hospital, Department of Medicine, Langen, Germany. innere2.longen@asklepios.com </code></pre> <p>I want to write a regex which can match the sentences which follow PMID, TI and AB.</p> <p>Is it possible to get these in a one shot regex?</p> <p>I have spent nearly the whole day to try to figure out a regex and the closest I could get is that:</p> <pre><code>reg4 = r'PMID- (?P&lt;pmid&gt;[0-9]*).*TI.*- (?P&lt;title&gt;.*)PG.*AB.*- (?P&lt;abstract&gt;.*)AD' for i in re.finditer(reg4, data, re.S | re.M): print i.groupdict() </code></pre> <p>Which will return me the matches only in the second "set" of data, and not all of them.</p> <p>Any idea? Thank you!</p>
0
2009-09-01T09:04:21Z
1,361,453
<p>The problem were the greedy qualifiers. Here's a regex that is more specific, and non-greedy:</p> <pre><code>#!/usr/bin/python import re from pprint import pprint data = open("testdata.txt").read() reg4 = r''' ^PMID # Start matching at the string PMID \s*?- # As little whitespace as possible up to the next '-' \s*? # As little whitespcase as possible (?P&lt;pmid&gt;[0-9]+) # Capture the field "pmid", accepting only numeric characters .*?TI # next, match any character up to the first occurrence of 'TI' \s*?- # as little whitespace as possible up to the next '-' \s*? # as little whitespace as possible (?P&lt;title&gt;.*?)PG # capture the field &lt;title&gt; accepting any character up the the next occurrence of 'PG' .*?AB # match any character up to the following occurrence of 'AB' \s*?- # As little whitespace as possible up to the next '-' \s*? # As little whitespcase as possible (?P&lt;abstract&gt;.*?)AD # capture the fiels &lt;abstract&gt; accepting any character up to the next occurrence of 'AD' ''' for i in re.finditer(reg4, data, re.S | re.M | re.VERBOSE): print 78*"-" pprint(i.groupdict()) </code></pre> <p>Output:</p> <pre><code>------------------------------------------------------------------------------ {'abstract': ' To successfully interact with objects in the environment, sensory evidence must\n be continuously acquired, interpreted, and used to guide appropriate motor\n responses. For example, when driving, a red \n', 'pmid': '19587274', 'title': ' Domain general mechanisms of perceptual decision making in human cortex.\n'} ------------------------------------------------------------------------------ {'abstract': ' BACKGROUND: Amyloidosis represents a group of different diseases characterized by\n extracellular accumulation of pathologic fibrillar proteins in various tissues\n', 'pmid': '19583148', 'title': ' Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic\n amyloidosis.\n'} </code></pre> <p>You may want to <code>strip</code> the whitespace of each field after scanning.</p>
0
2009-09-01T09:22:03Z
[ "python", "regex" ]
Match multiple patterns in a multiline string
1,361,373
<p>I have some data which look like that:</p> <pre><code>PMID- 19587274 OWN - NLM DP - 2009 Jul 8 TI - Domain general mechanisms of perceptual decision making in human cortex. PG - 8675-87 AB - To successfully interact with objects in the environment, sensory evidence must be continuously acquired, interpreted, and used to guide appropriate motor responses. For example, when driving, a red AD - Perception and Cognition Laboratory, Department of Psychology, University of California, San Diego, La Jolla, California 92093, USA. PMID- 19583148 OWN - NLM DP - 2009 Jun TI - Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic amyloidosis. PG - 482-6 AB - BACKGROUND: Amyloidosis represents a group of different diseases characterized by extracellular accumulation of pathologic fibrillar proteins in various tissues AD - Asklepios Hospital, Department of Medicine, Langen, Germany. innere2.longen@asklepios.com </code></pre> <p>I want to write a regex which can match the sentences which follow PMID, TI and AB.</p> <p>Is it possible to get these in a one shot regex?</p> <p>I have spent nearly the whole day to try to figure out a regex and the closest I could get is that:</p> <pre><code>reg4 = r'PMID- (?P&lt;pmid&gt;[0-9]*).*TI.*- (?P&lt;title&gt;.*)PG.*AB.*- (?P&lt;abstract&gt;.*)AD' for i in re.finditer(reg4, data, re.S | re.M): print i.groupdict() </code></pre> <p>Which will return me the matches only in the second "set" of data, and not all of them.</p> <p>Any idea? Thank you!</p>
0
2009-09-01T09:04:21Z
1,361,497
<p>Another regex:</p> <pre><code>reg4 = r'(?&lt;=PMID- )(?P&lt;pmid&gt;.*?)(?=OWN - ).*?(?&lt;=TI - )(?P&lt;title&gt;.*?)(?=PG - ).*?(?&lt;=AB - )(?P&lt;abstract&gt;.*?)(?=AD - )' </code></pre>
0
2009-09-01T09:33:01Z
[ "python", "regex" ]
Match multiple patterns in a multiline string
1,361,373
<p>I have some data which look like that:</p> <pre><code>PMID- 19587274 OWN - NLM DP - 2009 Jul 8 TI - Domain general mechanisms of perceptual decision making in human cortex. PG - 8675-87 AB - To successfully interact with objects in the environment, sensory evidence must be continuously acquired, interpreted, and used to guide appropriate motor responses. For example, when driving, a red AD - Perception and Cognition Laboratory, Department of Psychology, University of California, San Diego, La Jolla, California 92093, USA. PMID- 19583148 OWN - NLM DP - 2009 Jun TI - Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic amyloidosis. PG - 482-6 AB - BACKGROUND: Amyloidosis represents a group of different diseases characterized by extracellular accumulation of pathologic fibrillar proteins in various tissues AD - Asklepios Hospital, Department of Medicine, Langen, Germany. innere2.longen@asklepios.com </code></pre> <p>I want to write a regex which can match the sentences which follow PMID, TI and AB.</p> <p>Is it possible to get these in a one shot regex?</p> <p>I have spent nearly the whole day to try to figure out a regex and the closest I could get is that:</p> <pre><code>reg4 = r'PMID- (?P&lt;pmid&gt;[0-9]*).*TI.*- (?P&lt;title&gt;.*)PG.*AB.*- (?P&lt;abstract&gt;.*)AD' for i in re.finditer(reg4, data, re.S | re.M): print i.groupdict() </code></pre> <p>Which will return me the matches only in the second "set" of data, and not all of them.</p> <p>Any idea? Thank you!</p>
0
2009-09-01T09:04:21Z
1,361,611
<p>How about not using regexps for this task, but instead using programmatic code that splits by newlines, looks at prefix codes using .startswith() etc? The code would be longer that way but everyone would be able to understand it, without having to come to stackoverflow for help.</p>
2
2009-09-01T10:02:20Z
[ "python", "regex" ]
Match multiple patterns in a multiline string
1,361,373
<p>I have some data which look like that:</p> <pre><code>PMID- 19587274 OWN - NLM DP - 2009 Jul 8 TI - Domain general mechanisms of perceptual decision making in human cortex. PG - 8675-87 AB - To successfully interact with objects in the environment, sensory evidence must be continuously acquired, interpreted, and used to guide appropriate motor responses. For example, when driving, a red AD - Perception and Cognition Laboratory, Department of Psychology, University of California, San Diego, La Jolla, California 92093, USA. PMID- 19583148 OWN - NLM DP - 2009 Jun TI - Ursodeoxycholic acid for treatment of cholestasis in patients with hepatic amyloidosis. PG - 482-6 AB - BACKGROUND: Amyloidosis represents a group of different diseases characterized by extracellular accumulation of pathologic fibrillar proteins in various tissues AD - Asklepios Hospital, Department of Medicine, Langen, Germany. innere2.longen@asklepios.com </code></pre> <p>I want to write a regex which can match the sentences which follow PMID, TI and AB.</p> <p>Is it possible to get these in a one shot regex?</p> <p>I have spent nearly the whole day to try to figure out a regex and the closest I could get is that:</p> <pre><code>reg4 = r'PMID- (?P&lt;pmid&gt;[0-9]*).*TI.*- (?P&lt;title&gt;.*)PG.*AB.*- (?P&lt;abstract&gt;.*)AD' for i in re.finditer(reg4, data, re.S | re.M): print i.groupdict() </code></pre> <p>Which will return me the matches only in the second "set" of data, and not all of them.</p> <p>Any idea? Thank you!</p>
0
2009-09-01T09:04:21Z
1,361,692
<p>If the order of the lines can change, you could use this pattern:</p> <pre><code>reg4 = re.compile(r""" ^ (?: PMID \s*-\s* (?P&lt;pmid&gt; [0-9]+ ) \n | TI \s*-\s* (?P&lt;title&gt; .* (?:\n[^\S\n].*)* ) \n | AB \s*-\s* (?P&lt;abstract&gt; .* (?:\n[^\S\n].*)* ) \n | .+\n )+ """, re.MULTILINE | re.VERBOSE) </code></pre> <p>It will match consecutive non-empty lines, and capture the <code>PMID</code>, <code>TI</code> and <code>AB</code> items.</p> <p>The item values can span multiple lines, as long as the lines following the first start with a whitespace character.</p> <ul> <li>"<code>[^\S\n]</code>" matches any whitespace character (<code>\s</code>), except newline (<code>\n</code>).</li> <li>"<code>.* (?:\n[^\S\n].*)*</code>" matches consecutive lines that start with a whitespace character.</li> <li>"<code>.+\n</code>" matches any other non-empty line.</li> </ul>
0
2009-09-01T10:23:10Z
[ "python", "regex" ]