problem on multi-threading
The right program is as following,everything is ok. import requests import threading import queue class webdata(object): def __init__(self,name): self.jobs=queue.Queue() for x in name: url='http://stockhtm.finance.qq.com/sstock/ggcx/%s.shtml' %x self.jobs.put(url) def download(self): while not self.jobs.empty(): try: url = self.jobs.get() print(requests.get(url).status_code,url) print(threading.currentThread()) self.jobs.task_done() except: print("wrong",url) self.jobs.task_done() def run(self): for i in range(3): threading.Thread(target=self.download).start() self.jobs.join() print("i am over") name=['60', '01', '600319', '600531','600661', '600983', '600202', '600149'] x=webdata(name) x.run() question1: when i delete the line of `self.jobs.join()` ,the program will never finished ,why? import requests import threading import queue class webdata(object): def __init__(self,name): self.jobs=queue.Queue() for x in name: url='http://stockhtm.finance.qq.com/sstock/ggcx/%s.shtml' %x self.jobs.put(url) def download(self): while not self.jobs.empty(): try: url = self.jobs.get() print(requests.get(url).status_code,url) print(threading.currentThread()) self.jobs.task_done() except: print("wrong",url) self.jobs.task_done() def run(self): for i in range(3): threading.Thread(target=self.download).start() self.jobs.join() print("i am over") name=['60', '01', '600319', '600531','600661', '600983', '600202', '600149'] x=webdata(name) x.run() never quit from the thread ,why? question2: I can get every son-thread thread number with `print(threading.currentThread()) `,how can i get the main thread number in the program? 08221DA3@7B7BB14B.140BD253.PNG Description: Binary data -- https://mail.python.org/mailman/listinfo/python-list
How to index an array with even steps?
Hi, I have an array arr which is indexed from 0 to 999. I would like to construct a column in two steps. The first step is input from 200 data, evenly spread from 0 to 999 of the target array. Then, I want to use interpolate it from 200 to 1000 with interpolate method. In Python, ':' is used to indicate range (while in Matlab I know it can be used to control steps). How to index an array with 0, 5, 10, 15...995? Thanks, -- https://mail.python.org/mailman/listinfo/python-list
Re: How to index an array with even steps?
On Fri, 25 Jul 2014 04:45:31 -0700, fl wrote: > Hi, > > I have an array arr which is indexed from 0 to 999. I would like to > construct a column in two steps. The first step is input from 200 data, > evenly spread from 0 to 999 of the target array. Then, I want to use > interpolate it from 200 to 1000 with interpolate method. > > In Python, ':' is used to indicate range (while in Matlab I know it can > be used to control steps). How to index an array with 0, 5, 10, > 15...995? You can take a slice of the array and specify the step size. This works with lists, tuples, arrays and strings. For convenience, I will use strings, since there is less typing: py> data = "abcdefghijklmnopqrstuvwxyz" py> data[::5] 'afkpuz' py> data[::3] 'adgjmpsvy' You can specify a slice using any combination of: start : end : step If you leave the start out, it defaults to 0, if you leave the end out, it defaults to the end of the string or list, and if you leave the step out, it defaults to 1. Similarly, range() takes up to three arguments: range(end) range(start, end) range(start, end, step) -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: How to index an array with even steps?
On Friday, July 25, 2014 7:45:31 AM UTC-4, fl wrote: > to 999 of the target array. Then, I want to use interpolate it from 200 to > 1000 > > with interpolate method. > > In Python, ':' is used to indicate range (while in Matlab I know it can be > used > to control steps). How to index an array with 0, 5, 10, 15...995? > > Thanks, Sorry, I got it. x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> x[1:7:2] array([1, 3, 5]) -- https://mail.python.org/mailman/listinfo/python-list
Re: How to index an array with even steps?
fl writes: > In Python, ':' is used to indicate range (while in Matlab I know it can be > used > to control steps). How to index an array with 0, 5, 10, 15...995? Just use slicing: >>> L = range(1000) # your array goes here >>> L[::5] [0, 5, 10, 15, ..., 995] # Python 2 range(0, 1000, 5)# Python 3 -- Akira -- https://mail.python.org/mailman/listinfo/python-list
Re: Exploring Python for next desktop GUI Project
On Thursday, July 24, 2014 6:35:02 PM UTC-5, Terry Reedy wrote: > On 7/24/2014 1:04 PM, Chris "Kwpolska" Warrick wrote: > > > > > And it might be better to stay with Python 2, there are still > > > things that don't work with Py3k that you might find crucial. > > > > It is true that there are 3rd-party modules that do not work with 3.x, > > including a few that one might want to use is a new project. > > > > It is also true that there are language features in 3.4 that do not work > > with 2.x, or 3.2- or 3.3, including some that one might want to use in a > > new project. For instance, Unicode works much better in 3.3 than in any > > version before. That is *only* available in 3.3+. > > > > And it is true that there are 'feature' still in 2.7 that do not work in > > 3.x. But these are mostly nuisances that we are better of without. > > > > -- > > Terry Jan Reedy I would like to thank everyone for their insights. You all have been most helpful. I believe that I am going to start out using Tk and Python 3.x and see where that leads me. If I find that I don't like it I will try PySide. I intend on messing around with PyGame and Django in the future as well. -- https://mail.python.org/mailman/listinfo/python-list
Page layout in Python
The first step in grabbing information from a pdf file is to translate it into text format with pdftotext -layout command. Is it available any specific python tool or library to describe the layout of a page with ascii characters and to help in identifying and extracting the useful pieces of information? For example a function allowing to select N characters at line I starting from column Y. If a such tool is not available, what is in your mind the best structure to describe in python a two dimensions page layout? -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
Edit: I did went for IronPythonStudio but its dead now and they are not updating it anymore -- https://mail.python.org/mailman/listinfo/python-list
.Net Like Gui Builder for Python?
Hi, This Question may sound lame ,but I am searching for .Net Like Gui Builder for Python. I tried PyQt Designer' and 'Glade', No doubt its great but it created only interface. I have to code all the things in separate file. what I was searching for is Visual Studio .Net like Gui builder where you drag and drop widgets and just double click on the widget to edit code of that widget.All other formalities of creating a function and class for the main window and widget(e.g Button) is already done. So,Is there any Gui App builder like Visual Studio or having features like Visual Studio for Python. Thank You! -- https://mail.python.org/mailman/listinfo/python-list
rpath alike feature for python scripts
Hello, ELF binaries have a concept of RPATH, that means the interpreter looks for libraries first in a list of directories provided by the binary before falling back to default system directories. Since python scripts also do some sort of library loading, but lack an RPATH like feature, I'm asking here how to simulate it. The specific case I'm trying to address is the pygrub script which is included in the xen-tools package. This script makes use of other python libs provided by xen-tools. If xen is configured with --prefix=/some/where the python libs will be installed (in my case) in "/some/where/lib64/python2.6/site-packages". However, there seems to be no way in advance to know that exact location. If it would be known at build time, then something could tweak the pygrub script and insert the searchpath below "/some/where". And is this the right approach anyway? +sys.path.insert(0, "/some/where/lib64/python2.6/site-packages") After browsing the disutils documentation its not clear if setup.py has a way to help with this. Here is a pointer to a discussion I started a while ago, and the sources: http://lists.xenproject.org/archives/html/xen-devel/2014-04/msg02931.html http://xenbits.xen.org/gitweb/?p=xen.git;a=tree;f=tools/pygrub http://xenbits.xen.org/gitweb/?p=xen.git;a=tree;f=tools/python Thanks for any pointers. Olaf -- https://mail.python.org/mailman/listinfo/python-list
ArgumentParser maps dash to underscore in flags, but not positional arguments?
I'm using Python 2.7.3. It looks like ArgumentParser maps "--foo-bar" to "foo_bar" in the argument namespace, but doesn't do the same kind of mapping for positional arguments. Is this intentional? I can't find in the docs where it describes this mapping, but it's certainly convenient, and seems wrong that it doesn't do it everywhere. - from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("upload-dir") parser.add_argument("--file-name") args = parser.parse_args() print args - $ python args.py x Namespace(file_name=None, upload-dir='x') --- Roy Smith r...@panix.com -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
On Fri, Jul 25, 2014 at 10:55 AM, Orochi wrote: > So,Is there any Gui App builder like Visual Studio or having features like > Visual Studio for Python. I'm not aware of anything with the same level of functionality as Visual Studio's GUI building tools. Glade is the closest I've seen, and as you mentioned, it's not as interactive and integrated into an IDE as Visual Studio is. -- Jerry -- https://mail.python.org/mailman/listinfo/python-list
Re: Exploring Python for next desktop GUI Project
Zachary Ware wrote: > How so? Like any other facet of programming, using Tk(inter) has it's > frustrations, but for the most part it has always worked as expected > for me. Granted, I haven't done anything terribly fancy. In my experience, tkinter and ttk is fine until you need to do something more advanced, like using OpenGL or creating custom controls. Then it starts to suck incredibly. Sturla -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
Orochi wrote: > I tried PyQt Designer' and 'Glade', No doubt its great but it created only > interface. > I have to code all the things in separate file. That's what you should do. Keep autogenerated and hand-written code separate. Also take a look at wxFormBuilder. > what I was searching for is Visual Studio .Net like Gui builder where you > drag and drop widgets and just double click on the widget to edit code of > that widget. Most Python GUI frameworks are based on layout managers. "Drag and drop" does not work so well then. Sturla -- https://mail.python.org/mailman/listinfo/python-list
Re: problem on multi-threading
"水静流深" <1248283...@qq.com> wrote: > name=['60', '01', '600319', '600531','600661', '600983', '600202', > '600149'] > x=webdata(name) > x.run() > > never quit from the thread ,why? Call .start() instead of .run() -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
Am 25.07.2014 16:55, schrieb Orochi: So,Is there any Gui App builder like Visual Studio or having features like Visual Studio for Python. Unfortunately there's nothing like that. IMHO the lack of such a tool is a major blocking point in many (corporate) environments... From the GUI builders that I have tried, wxFormBuilder comes next. Regards, Dietmar -- https://mail.python.org/mailman/listinfo/python-list
Re: What is the simplest method to get a vector result?
On Thursday, July 24, 2014 9:49:14 AM UTC-4, Vlastimil Brom wrote: > 2014-07-24 14:53 GMT+02:00 fl : > internally): > http://mpmath.org/ > Using the sensible defaults, the plotting of a function can be as simple as: > > mpmath.plot(mpmath.sin) > > As for your original question, you can use a library designed for > working with this data: > http://www.numpy.org/ > > numpy.arange(100) * numpy.pi > > > hth, > >vbr I want to use your reply about numpy, but I find only the following works: import numpy as numpy Do you have other ways to import? (I find the above import a little more letters) Thanks, -- https://mail.python.org/mailman/listinfo/python-list
Strange Error with pip install.
Hello, I am using Windows 8.1 (I do have a linux box setup with virtualbox also) and I've used python previously but now it is giving me problems whenever I try to install anything from PyPI using pip. The error I get from the command line is "Cannot fetch index base URL http://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement..." I tried within the MinGW environment setup when I installed Git and was given Git Bash as a console. I also installed Bitnami Django stack and even in that environment, I get that error. I did some Google searches but I seem to only happen when people are trying to install Django. For me it is happening with django and any other pypi installation with pip. Interestingly, as I started trying to get advice with this, in the django chat room - at the time I was trying to get django to work in my Windows environment, someone suggested Vagrant. I started creating some boxes with Vagrant and Puppet, Chef or bash scripts. I had problems with this inside a Windows command prompt. So, I tried it under the MinGW environment I mentioned above, and half the time, when I run Vagrant up, it starts the environment but then it tries to connect using a public key authentication. Sometimes it will just give up and let me run vagrant ssh or use putty. Other times it just times out. One idea I have is to import a VirtualBox "box" from Bitnami into VirtualBox, their Django stack. Does anyone have any suggestions about this problem I am having using pip install inside Windows (Windows 8, if that matters)? Thanks in advance, Bruce -- https://mail.python.org/mailman/listinfo/python-list
Prob. Code Downloaded for Programming the Semantic Web (python code)
Hello all, I downloaded some code accompanying the book "Programming the Semantic Web." This question is not Semantic Web related and I doubt that one needs to know anything about the Semantic Web to help me with this. It's the first code sample in the book, I'm embarrassed to say. I have the code shared here (just one file, not the majority of the book or anything): http://pastebin.com/e870vjYK OK, Eclipse with PyDev doesn't like this first line, with the function: def add(self, (sub, pred, obj)): It complains about the parentheses just before sub. Simply removing them just moves me down to another error. I did try using python 3.x (3.4 to be specific), which meant changing print statements to function calls. Of course, that didn't fix the errors I was mentioning. The text uses python 2.7.x. There are other places where I thought that there were too many parentheses and I tried removing one set of them. For example this snippet here: def remove(self, (sub, pred, obj)): """ Remove a triple pattern from the graph. """ triples = list(self.triples((sub, pred, obj))) Are the two sets parentheses needed after self.triples? That syntax is confusing to me. It seems that it should be triples = list(self.triples(sub, pred, obj)) The full listing is here: http://pastebin.com/e870vjYK I agree with the authors that python is a fun and easy language to use, thus it is strange that I am getting stuck here. Thanks, Bruce -- https://mail.python.org/mailman/listinfo/python-list
Re: Prob. Code Downloaded for Programming the Semantic Web (python code)
> OK, Eclipse with PyDev doesn't like this first line, with the function: > def add(self, (sub, pred, obj)): > > It complains about the parentheses just before sub. Seems like this code is Python 2.x. Skip -- https://mail.python.org/mailman/listinfo/python-list
Re: What is the simplest method to get a vector result?
On Fri, Jul 25, 2014 at 5:08 PM, fl wrote: > I want to use your reply about numpy, but I find only the following works: > > import numpy as numpy > > Do you have other ways to import? (I find the above import a little more > letters) What's wrong with: import numpy -- https://mail.python.org/mailman/listinfo/python-list
Re: Prob. Code Downloaded for Programming the Semantic Web (python code)
On Fri, Jul 25, 2014 at 5:21 PM, Skip Montanaro wrote: >> OK, Eclipse with PyDev doesn't like this first line, with the function: >> def add(self, (sub, pred, obj)): >> >> It complains about the parentheses just before sub. > > Seems like this code is Python 2.x. For me, this code ran on all of 2.4, 2.5, 2.6 and 2.7, but not on any of 3.0, 3.1, 3.2, 3.3 or 3.4. HTH -- https://mail.python.org/mailman/listinfo/python-list
Re: Prob. Code Downloaded for Programming the Semantic Web (python code)
On Jul 25, 2014 6:54 PM, "Dan Stromberg" wrote: > > On Fri, Jul 25, 2014 at 5:21 PM, Skip Montanaro wrote: > >> OK, Eclipse with PyDev doesn't like this first line, with the function: > >> def add(self, (sub, pred, obj)): > >> > >> It complains about the parentheses just before sub. > > > > Seems like this code is Python 2.x. > > For me, this code ran on all of 2.4, 2.5, 2.6 and 2.7, but not on any > of 3.0, 3.1, 3.2, 3.3 or 3.4. Python 3.x no longer allows tuple parameter unpacking in function signatures. See PEP 3113. -- https://mail.python.org/mailman/listinfo/python-list
Re: one to many (passing variables)
On 7/24/2014 2:58 AM, Ben Finney wrote: Here is an article on good API design; the principles apply to Python http://blog.isnotworking.com/2007/05/api-design-guidelines.html>. You know your API and its requirements better than we; see whether that sheds any light on improvements to make. Thank you for the link. I'm curious about one item mentioned in the article: "Avoid return values that Demand Exceptional Processing: return zero-length array or empty collection, not null" Isn't a zero-length array, empty collection and null all the same thing? Or does the "Demand Exceptional Processing" comes from testing to see if the object is empty versus being null? And does this apply to Python? Thank you, Chris Reimer -- https://mail.python.org/mailman/listinfo/python-list
Re: What is the simplest method to get a vector result?
On Friday, July 25, 2014 8:37:14 PM UTC-4, Ian wrote: > On Fri, Jul 25, 2014 at 5:08 PM, fl wrote: > > Do you have other ways to import? (I find the above import a little more > > letters) > > What's wrong with: > > import numpy I was wrong, maybe some careless key inputs. "import numpy" works. -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
On Sat, Jul 26, 2014 at 7:23 AM, Dietmar Schwertberger wrote: > Am 25.07.2014 16:55, schrieb Orochi: > >> So,Is there any Gui App builder like Visual Studio or having features like >> Visual Studio for Python. > > Unfortunately there's nothing like that. > IMHO the lack of such a tool is a major blocking point in many (corporate) > environments... > > From the GUI builders that I have tried, wxFormBuilder comes next. The OP asked for two things, which I'll separate because they're actually quite different. 1) Drag and drop widgets to create a window 2) Double-click a widget to edit its code (presumably event handler) I have used a number of GUI toolkits that did provide the first one, but the second is a lot more restrictive than you might think: it implies that there's exactly one code block per widget. For simple projects, you might think "Uhh, yeah, a button has its click event", but there are plenty of other events to attach to a button, and you might want to have the same function attached to several buttons (either because they actually do the same thing, or because they do very similar things and it's parameterized). The nearest I've seen to "double-click to edit code" is VX-REXX, which had a right-click menu with all that widget's events; it didn't cope with having the same code attached to multiple widgets (for that, you need to manually attach events), but as that's a lot rarer than having multiple code blocks attached to one widget (eg a hover event and a click event), that's acceptable for a convenience feature. As to dragging and dropping widgets to create a window, though... that's fine for a pixel-based layout, but it's high time pixel-based layouts were deprecated. They're vulnerable to way too many variations (twip-based layouts, like VX-REXX uses, are at least independent of font size, but still vulnerable to plenty of other issues), and they're rigid. Cross-platform GUI toolkits are generally based around rules, rather than exact positions, so you end up with a tree. Think of HTML and how markup affects layout; you place containers and containers within containers, and everything is held within its parent. (Well, okay. With position:relative you can mess that up. And of course position:absolute and position:fixed basically put a new top-level window onto the page. But normal object layout is based on the tree structure.) Rather than a drag-and-drop builder, then, all you need is a text editor and a way to quickly run your code. As well as demanding nothing in terms of development time (believe you me, a good d'n'd builder would cost quite a few dev hours), this guarantees perfect accuracy; imagine the hassles if your code ended up producing something not quite identical to your preview! Take the easy and safe option, and just write your code and look at it. WYSIWYG editors have their uses in some places, but more and more I'm seeing them as just too restrictive. Editing text files is the way to do things. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: one to many (passing variables)
On Sat, Jul 26, 2014 at 11:47 AM, C.D. Reimer wrote: > Isn't a zero-length array, empty collection and null all the same thing? Definitely not. In C++ and Java, which he's primarily looking at, there's a definite difference in usage, and potentially in memory usage/performance. > Or does the "Demand Exceptional Processing" comes from testing to see if the > object is empty versus being null? > > And does this apply to Python? In Python, if you have something that might return a list of somethings, but in certain circumstances won't have any to return, don't have it return None in that case; just return an empty list. Compare: def func(args): if condition: return None return [1,2,3] x = func(142857) if x: for i in x: do_stuff(i) With this: def func(args): if condition: return [] return [1,2,3] x = func(142857) for i in x: do_stuff(i) The second one will always return a list, ergo you can always iterate over it. You can still use "if x" to see if you got the empty one. The point he's making is distinctly stronger in Python than in C++ or Java, to the extent that it's a complete non-issue. In lower-level languages, returning a null pointer is cheaper than constructing a zero-length array, and testing an array for contents is both slower and more verbose than testing for null-ness; but in Python, the cost difference between "return None" and "return []" is negligible (there is a difference, of course, but honestly - if you're worried about that, Python is the wrong language for you), and the difference between "if x" and "if x" is... uhh, nonexistent. :) His point is that it's better to make things simple and clear and understandable than to save a little bit of memory by returning null rather than an empty array; and I don't think any Python programmers will disagree. (There are, of course, times when you need to distinguish between a non-result and a result with no items in it, which would be done by returning None and returning [], respectively. That's different. Then it's part of your API, as a separate state.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Prob. Code Downloaded for Programming the Semantic Web (python code)
On Fri, 25 Jul 2014 17:06:17 -0700, Bruce Whealton wrote: > OK, Eclipse with PyDev doesn't like this first line, with the function: > def add(self, (sub, pred, obj)): In Python 2, you could include parenthesised parameters inside function declarations as above. That is effectively a short cut for this version, where you collect a single argument and then expand it into three variables: def add(self, sub_pred_obj): sub, pred, obj = sub_pred_obj In Python 3, that functionality was dropped and is no longer allowed. Now you have to use the longer form. [...] > There are other places where I thought that there were too many > parentheses and I tried removing one set of them. For example this > snippet here: > > def remove(self, (sub, pred, obj)): > """ > Remove a triple pattern from the graph. """ > triples = list(self.triples((sub, pred, obj))) Firstly, the remove method expects to take a *single* argument (remember that self is automatically provided by Python) which is then automatically expanded into three variables sub, pred, obj. So you have to call it with a list or tuple of three items (or even a string of length exactly 3). Then, having split this list or tuple into three items, it then joins them back again into a tuple: (sub, pred, obj) passes that tuple to the triples method: self.triples((sub, pred, obj)) (not shown, but presumably it uses the same parenthesised parameter trick), and then converts whatever triples returns into a list: list(self.triples((sub, pred, obj))) that list then being bound to the name "triples". > Are the two sets parentheses needed after self.triples? That syntax is > confusing to me. It seems that it should be triples = > list(self.triples(sub, pred, obj)) It's needed because the triples method is written def triples(self, (sub, pred, obj)): instead of the more obvious: def triples(self, sub, pred, obj): -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: Prob. Code Downloaded for Programming the Semantic Web (python code)
On Sat, Jul 26, 2014 at 10:06 AM, Bruce Whealton wrote: > OK, Eclipse with PyDev doesn't like this first line, with the function: > def add(self, (sub, pred, obj)): As others have said, this is something that changed in Python 3. So you have two parts to the problem: firstly, your code is bound to Python 2 by a triviality, and secondly, Eclipse is complaining about it. One solution would be to teach Eclipse that this is legal, or for you to just ignore its complaints. If your code works in Python 2.7, then there's no big problem. You could try telling Eclipse that you're using Python 2 (maybe by putting a shebang at the top of your script), but that may not work; in any case, that's just an issue with the editor. But a better solution, IMO, would be to avoid that implicit tuple unpacking. It's not a particularly clear feature, and I'm not sorry it's gone from Py3. The simplest way to change it is to just move it into the body: def add(self, args): sub, pred, obj = args # rest of code as before Preferably with a better name than 'args'. Alternatively, change the places that call add() and have them provide four separate arguments, in which case the signature would simply be: def add(self, sub, pred, obj): like you'd expect. > triples = list(self.triples((sub, pred, obj))) > > Are the two sets parentheses needed after self.triples? That syntax is > confusing to me. It seems that it should be > triples = list(self.triples(sub, pred, obj)) No, that's correct. The extra parens force that triple to be a single tuple of three items, rather than three separate arguments. Here's a simpler example: >>> lst = [] >>> lst.append(1,2,3) Traceback (most recent call last): File "", line 1, in lst.append(1,2,3) TypeError: append() takes exactly one argument (3 given) >>> lst.append((1,2,3)) >>> addme = 4,5,6 >>> lst.append(addme) >>> lst [(1, 2, 3), (4, 5, 6)] The list append method wants one argument, and appends that argument to the list. Syntactically, the comma has multiple meanings; when I assign 4,5,6 to a single name, it makes a tuple, but in a function call, it separates args in the list. I don't see why the triples() function should be given a single argument, though; all it does is immediately unpack it. It'd be better to just remove the parens and have separate args: triples = list(self.triples(sub, pred, obj)) def triples(self, sub, pred, obj): While I'm looking at the code, a few other comments. I don't know how much of this is your code and how much came straight from the book, but either way, don't take this as criticism, but just as suggestions for ways to get more out of Python. Inside remove(), you call a generator (triples() uses yield to return multiple values), then construct a list, and then iterate exactly once over that list. Much more efficient and clean to iterate directly over what triples() returns, as in save(); that's what generators are good for. In triples(), the code is deeply nested and repetitive. I don't know if there's a way to truly solve that, but I would be inclined to flatten it out a bit; maybe check for just one presence, to pick your index, and then merge some of the code that iterates over an index. Not sure though. (Also: It's conventional to use "is not None" rather than "!= None" to test for singletons. It's possible for something to be equal to None without actually being None.) I would recommend moving to Python 3, if you can. Among other benefits, the Py3 csv module allows you to open a text file rather than opening a binary file and manually encoding/decoding all the parts separately. Alternatively, if you don't need this to be saving and loading another program's files, you could simply use a different file format, which would remove the restrictions (and messes) of the CSV structure. Instead of explicitly putting "f.close()" at the end of your load and save methods, check out the 'with' statement. It'll guarantee that the file's closed even if you leave early, get an exception, or anything like that. Also, I'd tend to use the .decode() and .encode() methods, rather than the constructors. So here's how I'd write a Py2 load: def load(self, filename): with open(filename, "rb") as f: for sub, pred, obj in csv.reader(f): self.add((sub.decode("UTF-8"), pred.decode("UTF-8"), obj.decode("UTF-8"))) (You might want to break that back out into three more lines, but this parallels save(). If you break this one, you probably want to break save() too.) Hope that helps! ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
On 07/25/2014 08:55 AM, Orochi wrote: > Hi, This Question may sound lame ,but I am searching for .Net Like > Gui Builder for Python. I tried PyQt Designer' and 'Glade', No doubt > its great but it created only interface. I have to code all the > things in separate file. what I was searching for is Visual Studio > .Net like Gui builder where you drag and drop widgets and just double > click on the widget to edit code of that widget.All other formalities > of creating a function and class for the main window and widget(e.g > Button) is already done. > > So,Is there any Gui App builder like Visual Studio or having features > like Visual Studio for Python. You can easily compile Qt Designer .ui files to python code with pyuic. But loading the .ui file at runtime is a good idea too, and what I do for my programs. It adds a certain amount of flexibility. https://blog.safaribooksonline.com/2014/01/22/create-basic-gui-using-pyqt/ I do the same thing with Glade. Modern GUI toolkits are moving away from coding GUIs explicitly, at least on Linux and Mac. Can't speak for windows. -- https://mail.python.org/mailman/listinfo/python-list
Re: one to many (passing variables)
On Fri, 25 Jul 2014 18:47:55 -0700, C.D. Reimer wrote: > On 7/24/2014 2:58 AM, Ben Finney wrote: >> Here is an article on good API design; the principles apply to Python >> http://blog.isnotworking.com/2007/05/api-design-guidelines.html>. >> You know your API and its requirements better than we; see whether that >> sheds any light on improvements to make. > Thank you for the link. I'm curious about one item mentioned in the > article: "Avoid return values that Demand Exceptional Processing: return > zero-length array or empty collection, not null" > > Isn't a zero-length array, empty collection and null all the same thing? No. Since an array is a kind of collection, a zero-length array is an empty array, which is an empty collection. But null is not the same thing. In Python terms, it is the difference between: return [] return None While I agree that in general it is better to return (say) a consistent list result, sometimes you need an exceptional result that is different from the "empty" or "zero" result. In that case, there are two obvious ways to deal with exceptional circumstances: - raise an exception, e.g. "spam".index("e") raises - return a special result, e.g. "spam".find("e") returns -1 Raising an exception is the obvious way to handle it, but exception handling is a little less convenient than testing for a special value. Hence the find() convenience method. However, find() makes a silly mistake: it returns -1 to indicate Not Found, and -1 is acceptable as an index. So if you forget to test for the Not Found case, you might write this: p = some_string.find(needle) return another_string[p] which is wrong. If find() returns -1, another_string[p] returns the *last* character in the string, which is probably not what you want. A better API is that of the regular expression module. re.search() and re.match() return either a match object, or None if the regex doesn't match at all. So if you forget to test for None, and blindly try to treat the result as if it where a match object, you will immediately get an exception instead of invalid results: mo = re.search(text, needle) return mo.group() # will raise if mo is None In summary: * if you're returning a list of results, deal with no results by returning an empty list [] rather than None; * if you need to distinguish between the empty list case and some exceptional situation, the best way is to raise an exception; * if you don't wish to raise an exception, it is better to return some result which clearly cannot be mistaken for, or accidentally used as, a regular non-exceptional result; * e.g. if your function normally returns an integer, better to return None as a "no result exists" than 0 or -1, since they are valid integers and None isn't. -- Steven -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
On Fri, Jul 25, 2014 at 7:40 PM, Chris Angelico wrote: > The OP asked for two things, which I'll separate because they're > actually quite different. > > 1) Drag and drop widgets to create a window > 2) Double-click a widget to edit its code (presumably event handler) > > I have used a number of GUI toolkits that did provide the first one, > but the second is a lot more restrictive than you might think > Not that I disagree with the overall point of just using a text editor (especially for Python GUIs) but apparently you've never created a C# WPF app using Visual Studio? WPF fully supports layout controls, is *not* generally pixel based it's more similar to HTML + CSS (although you do pixel perfect layout if you try), and still easily does (2). And while I almost exclusively use the Visual Studio XAML tab view rather than bothering with the Designer view you can drag & drop if you really want to. And Microsoft's Expression Blend takes that to a whole 'nother level supposedly making it easy for "even" graphic designers to create GUIs without delving too much into raw code wrangling. One of the nice things about VIsual Studio and WPF (even in the XAML view) is its Properties window. This lets you select a control and see all the applicable possible properties and what legal choices you have for setting them. This is an incredible aid to discovering how to use said controls. And as far as any limitations of (2) goes, I still like using the Events view of the Properties window to initially hook up an event handler. This automatically creates a "correctly" (or at least consistently) named and argumented event handler and adds the proper attribute to the XAML. It is easy enough to then mess around with the generated code if that doesn't quite suit your needs. Having the list of possible event handlers all in one place instead of having to look up the doc is invaluable. And being able to press F1 just about anywhere and have the relevant document open up is even more so. As far as I've seen Visual Studio + WPF really is state of the art for GUI building. I wish more developers were familiar with all its capabilities so they could know what to whine for in their own programming environment :) -- https://mail.python.org/mailman/listinfo/python-list
Re: .Net Like Gui Builder for Python?
On Sat, Jul 26, 2014 at 2:13 PM, TP wrote: > Not that I disagree with the overall point of just using a text editor > (especially for Python GUIs) but apparently you've never created a C# WPF > app using Visual Studio? WPF fully supports layout controls, is *not* > generally pixel based it's more similar to HTML + CSS (although you do pixel > perfect layout if you try), and still easily does (2). And while I almost > exclusively use the Visual Studio XAML tab view rather than bothering with > the Designer view you can drag & drop if you really want to. And Microsoft's > Expression Blend takes that to a whole 'nother level supposedly making it > easy for "even" graphic designers to create GUIs without delving too much > into raw code wrangling. No, I haven't. (I haven't done anything with C#. There's a limit to how much I have time to learn, and I'd much rather work with something like Pike than C#.) In the light of this, I'd best separate out my concerns a little further: 1) GUI layouts that use pixel positioning 2) Drag and drop GUI layout interfaces The first has all the problems I mentioned, of being tightly bound to so many things. A twip-based layout solves one of them (font size), and it's possible to get simple features like "match sizes on all these widgets" and "align these widgets' left margins" (both of which I had in VX-REXX) to help; but none of that deals with run-time layout requirements, which are much MUCH better served by a rule-based layout. The second, though, still does have issues. While it'll give you a good result at the end, it's not nearly as advantageous as the d'n'd interface for laying out pixel-precise positions. WYSIWYG HTML editors aren't exactly sweeping the board (in fact, every serious web developer I know prefers to work with the markup itself), and even then, they're not so much "drag and drop positioning of stuff" as they are "word processor that saves as HTML". You may as well skip the WYSIWYG editor and just work directly with code; the benefit isn't enough to justify the risks, the biggest of which is that your lovely layout will look completely ugly on a different platform, theme, font size, etc. There is one special case, though. When it comes to *mocking up* an interface, it is sometimes helpful to have a drag-and-drop system that allows a non-programmer to put something together - a sketch, if you like. Imagine taking a sheet of physical paper and an actual physical pencil, and drawing out a layout; now imagine making that both easier and clearer by dragging widgets around. At no point do you ever expect the paper sketch to be perfect, and certainly you don't expect it to work on all platforms, font sizes, etc; but it's a lot easier than manually crafting ASCII art, and it's something that a programmer can look at to decide how to lay things out. It's far from perfect, though, as it assumes a fundamentally 2D layout; GUI design, even back in the 90s when I first started, was always a tree of parent-child relationships. But if you want that sort of thing for your mock-up, I'm sure it'd be possible to abuse something to do it; I used the Open Watcom C++ Dialog Editor for the job, a few times. It doesn't even have to be backed by the same language or toolkit. We're broadly in agreement, though. Instead of searching for the ideal GUI window builder (and, by the way, one person's ideal will differ hugely from another's), just write the code directly. Life's better. Plus, it plays more nicely with source control. Ever tried to dig through a git repo to figure out when a change happened to an Open Office document? Not so useful. But I can 'git blame' a source file and know for sure that I'm getting meaningful results. LilyPond files are source code; NoteWorthy Composer files are binary blobs. (I'm not sure about other music formats, like Sibelius's save file, as I haven't used them.) I'd much rather work with a format where the disk changes mirror the conceptual changes. Readable diffs FTW. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: rpath alike feature for python scripts
Olaf Hering writes: > ELF binaries have a concept of RPATH, that means the interpreter looks > for libraries first in a list of directories provided by the binary > before falling back to default system directories. > > Since python scripts also do some sort of library loading, but lack an > RPATH like feature, I'm asking here how to simulate it. The "binary" corresponds to a script. The script could have a function "setup_path" which enhances "sys.path" as appropriate and ensure that this function is called near its beginning. -- https://mail.python.org/mailman/listinfo/python-list
Re: Strange Error with pip install.
Bruce Whealton writes: > I am using Windows 8.1 (I do have a linux box setup with virtualbox > also) and I've used python previously but now it is giving me problems > whenever I try to install anything from PyPI using pip. The error I get from > the command line is > "Cannot fetch index base URL http://pypi.python.org/simple/ That might be a temporary problem ("pypi" not accessible for a short time frame). Should the problem persist over a longer period, something might be wrong with your firewall (or network access). -- https://mail.python.org/mailman/listinfo/python-list
回复: problem on multi-threading
>>> x=webdata(name) >>> x.start() Traceback (most recent call last): File "", line 1, in AttributeError: 'webdata' object has no attribute 'start' There is a relation with jobs.join() method in threading module,your answer is wrong. -- 原始邮件 -- 发件人: "Sturla Molden";; 发送时间: 2014年7月26日(星期六) 凌晨4:04 收件人: "python-list"; 主题: Re: problem on multi-threading "水静流深" <1248283...@qq.com> wrote: > name=['60', '01', '600319', '600531','600661', '600983', '600202', > '600149'] > x=webdata(name) > x.run() > > never quit from the thread ,why? Call .start() instead of .run() -- https://mail.python.org/mailman/listinfo/python-list-- https://mail.python.org/mailman/listinfo/python-list
Re: problem on multi-threading
On Fri, Jul 25, 2014 at 12:45 AM, 水静流深 <1248283...@qq.com> wrote: > > never quit from the thread ,why? > I am going to guess that you can actually run code in the interpreter here. When printing from threads, the prompt will end up in the wrong place as the prompt is printed in the main thread. Similarly, there is a (decent) chance that the prints will be done out-of-order (multiple " 08221DA3@7B7BB14B.140BD253.PNG Description: Binary data -- https://mail.python.org/mailman/listinfo/python-list
python template lint
Hi there List, I am looking for a little guidance here. I am taking a series of template files for building configuration. I want to design some simple lint rules to check for some of the syntax of the template files I created. For instance if an open brace is seen indent 4 spaces each time. unindent when a close brace is seen. remove blank lines. Remove comments after '#' and so on. I could write this with search adn replace rules but I might want a module that allows for some complexity down the road. Any cool python module recommendations out there that does this well? Cheers, Noah -- https://mail.python.org/mailman/listinfo/python-list