Tkinter on mac - Binding command-q to quit application
Hi All,
I'm attempting to develop a Tcl/Tk application on the mac using python
and Tkinter. The one problem I'm having is adding basic keyboard
support to my application, specifically binding command-q so that it
quits the application (this is standard behavior for almost every mac
application, the equivalent of alt-f4 on windows). Has anyone
successfully been able to do this? If so, could you please share some
code which demonstrates how?
If it matters, I've been working with both python 2.3.5 and python
2.4.1:
>>> print sys.version; print "-"*30; print Tkinter.__version__
2.3.5 (#1, Aug 22 2005, 22:13:23)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)]
--
$Revision: 1.177 $
and on python 2.4:
>>> print sys.version; print "-"*30; print Tkinter.__version__
2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)]
------
$Revision: 1.181.2.1 $
Thanks in advance,
Brandon
--
http://mail.python.org/mailman/listinfo/python-list
Re: Newbie namespace question
And I just realized that Jython doesn't support the __builtins__ variable... :( -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie namespace question
Thanks, that worked to get me past the "problem". Did you see my post regarding my issue? I just know that there's a "Python way" to resolve my issue, so if anyone has a better way, I'm really interested. Not only does it feel like a hack, it looks like one too! Even worse! -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie namespace question
Peter,
You're correct about the bug. I did need a 'self' parm... I was just
winging the example because the actual code is pretty large. I'm using
google groups for my posting and it didn't carry spaces through (I did
use spaces and not tabs).
The "fix" or workaround was to import __builtin__ and add the
AdminConfig reference there in configure_server_foo.py as follows:
import __builtin__
__builtin__.AdminConfig = AdminConfig
As for the indentations, substitute ~ with a space.
Hopefully, a bug free and "indented" version. :)
#jdbc.py
class DataSource:
~~~def __init__(self, servername):
~~self.servername = servername
~~~def create(self, name, connectionInfo, etc):
~~#Call the IBM supplied WebSphere config object
~~AdminConfig.create('DataSource')
--
http://mail.python.org/mailman/listinfo/python-list
Re: Newbie namespace question
I did the constructor thing and just didn't like it, it didn't feel clean (I know, I know and monkeying with __builtin__ is?) As for global, that will just make it modlue-level global (I think?) and I have this reference in multiple modules. I think I tried it already, but I can't remember for sure... Anyway, all of this got me brainstorming and I think I've got a solution that I think is clean and will be effective, I'll bust it out and post it here for comments. Thanks for your input! -- http://mail.python.org/mailman/listinfo/python-list
Awesome Python Information
Check out: www.ChezBrandon.com -- http://mail.python.org/mailman/listinfo/python-list
Exposing Excel as a Webservice
Hi all, I'm currently working on a project where we have a need to expose an Excel spreadsheet on the web as a webservice that needs to be reliable and available 24x7x365. I've implemented a prototype of this in python using the win32com library to interface with the Excel Automation API via COM. I've also used web.py as a way to expose this automation functionality to the network. This works just fine as a prototype that proves that it is possible to do something like this. I'm not revisiting the code with the goal of making it more reliable and available, able to support multiple users (although only allowing one at a time to use Excel). This means that Excel is going to potentially be used from multiple threads -- something I know that has historically caused problems for a lot of people based on my searches of the newsgroup. What I'd like to know is what is the proper strategy that I should be taking here? I see several options: 1) Ignore threads entirely. Let every incoming web thread interface directly with excel (one web thread at a time -- I'll have an interpreter scoped lock preventing multiple threads from accessing). 2) Dedicate a single worker thread to do all interaction with Excel. Pass data off to this thread from the incoming web thread via shared memory and let the worker thread get Excel to process it. This will ensure that exactly 1 thread ever interacts with Excel. 3) Spawn a new interpreter (literally spawn another python process) for each incoming web thread. This will ensure that when a process is finished with Excel there is no chance of any lingering state or something improperly cleaned up. I've actually attempted to implement 1) and 2) and have had problems with sporadic failures that cause the Excel to no longer be accessible from the interpreter. I've tried very hard to ensure that pythoncom._GetInterfaceCount() always returns 0 when I believe I'm finished with excel. I don't think I'm perfect at always getting a 0, but I'm pretty close. I believe that some of my problems are caused by not being perfect about this but haven't been able to track down the leaking references. I'm definitely not an expert in COM or its threading models. What techniques does the group suggest? Is spawning a new interpreter for every request a bit too extreme (I don't mind the performance hit). Has anyone ever done anything like this? How did you get around these problems? Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: Exposing Excel as a Webservice
Thanks for the reply. Unfortunately I cannot use a different format for the data since I'm really using Excel as a calculation engine. I don't own the authoring of these spreadsheets or even the data inside of them so I cannot change the format. The spreadsheets also are complicated enough and change frequently enough that it's not feasible for me to try to extract the logic and data inside of them into a different calculation engine (unless there's some existing tool which will do this for me?). My program is just one user of the spreadsheets among hundreds of human users. Unfortunately what's easy for the humans is always going to win out over what's easy for my program. My concern with my option 2) is that I appear to be experiencing some level of contamination between calls that I can't resolve. It's not truly transactional in that a call into the system guarantees that it will leave everything how it found it. That's sort of why I thought up option 3). Let the OS help me somewhat to clean up. I strongly suspect that my option 2) is to some extent at the mercy of the python garbage collector. I'm not positive of that though. Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Python Info.
Check it out: www.BrandonsMansion.com -- http://mail.python.org/mailman/listinfo/python-list
adding values to keys
Hi all,
I'm not sure if I'm calling the right method in a dictionary. I have:
for k,v in dict.items():
NT = k,range(alpha,omega)#where alpha and omega are
previously defined as 1 and 4, respectively
print NT
which gives:
('w', [0,1,2,3])
('x', [0,1,2,3])
('y', [0,1,2,3])
('z', [0,1,2,3])
And now I want a master dictionary like: [{'w': [0],[1],[2],[3]},
{'x': [0]...]
So I try:
MT = {}
MT.fromkeys(NT[0], range(alpha,omega))
print MT
but this only returns:
{}
{}
{}...
Anybody see what I'm doing wrong? Any advice is much appreciated.
Thanks,
Brandon
--
http://mail.python.org/mailman/listinfo/python-list
dictionary idiom needed
Hi all,
I have a series of lists in format ['word', 'tagA', 'tagB']. I have
converted this to a few dicts, such as one in which keys are tuples of
('word', 'tagB'), and the values are the number of times that key was
found. I need an dictionary idiom whereby I can find all instances of
a given 'word' with any 'tagB', and then subdivide into all instances
of a given 'tagB'. In both cases I would want the value as a count of
all instances found. Can this be done with dictionaries? Or should I
back up and do this with lists? All of the nested for loops I have
tried return replicated results, so I can't trust those values.
Thanks for any pointers,
Brandon
--
http://mail.python.org/mailman/listinfo/python-list
Re: dictionary idiom needed
Thanks bear - Some outside advice has me looking at nested dictionaries. But I am still bogged down because I've not created one before and all examples I can find are simple ones where they are created manually, not with loops. Maybe a further example: data: POS1POS2 POS3 ['word1','tagA','tagB'] ['word2','tagC','tagD'] ['word1','tagE','tagB'] ['word1','tagC','tagF'] ... and so on. FWIW: I am guaranteed that the set of tags that may occur in position2 is complementary to the set of tags that may occur in position3. Now I want to get an accounting of all the tags that occurred in position3 in the context of, say, word1. Here I've shown that for word1, tagB and tagF occurs. I want a way to access all this information such that nested_dict['word1']['tagB'] = 2, and nested_dict ['word1']['tagF'] = 1. As I mentioned, I already have dicts such that dictA['word1'] = 3, and dictB['tagB'] = 2. I used defaultdict to build those, and that seems to be causing me to get some funky values back from my initial attempts to build a nested dictionary. I am stumbling at constructing a "for" loop that automatically creates such nested dictionaries. I hope that clears things up. If you still have any advice, it's much appreciated. Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary idiom needed
> Smells like homework without a particular application. @Scott: Even if that were the case :) I'd still like to figure out how to create nested dictionaries! Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary idiom needed
> >>> d = defaultdict(lambda: defaultdict(int)) > > Arnaud Ah... so that's what lambdas are for. Many thanks! Brandon -- http://mail.python.org/mailman/listinfo/python-list
Convert string to char array
How do I convert a string to a char array? I am doing this so I can edit the string received from an sql query so I can remove unnecessary characters. -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert string to char array
Thank you both for your help. "Mike Kent" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] On Jul 1, 2:49 pm, "Brandon" <[EMAIL PROTECTED]> wrote: > How do I convert a string to a char array? I am doing this so I can edit > the string received from an sql query so I can remove unnecessary > characters. Answering your specific question: Python 2.5.1 (r251:54863, Mar 31 2008, 11:09:52) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = 'hello' >>> l = list(s) >>> l ['h', 'e', 'l', 'l', 'o'] >>> But more generally, you might want to read up on the string methods available to you, such as replace(): http://docs.python.org/lib/string-methods.html -- http://mail.python.org/mailman/listinfo/python-list
Required items in a form
What I'm trying to do is essentially force a user to fill in required items in a form, which will be saved to a database. How can I get it so that once the user clicks "OK" on the dialog box, it transfers control back to the form, and not save the empty fields into the database? -- http://mail.python.org/mailman/listinfo/python-list
Inserting into a combo box
I'm attempting to insert items into a combo box, but when it goes to run it, throws up the error: TypeError: argument 1 of QComboBox.insertItem() has an invalid type and here is what I'm trying to do: self.editUsername.insertItem(uname) editUsername is the combo box, and uname is a string I'm attempting to insert. Any suggestions? -- http://mail.python.org/mailman/listinfo/python-list
updating dictionaries from/to dictionaries
Hi all,
I am not altogether experienced in Python, but I haven't been able to
find a good example of the syntax that I'm looking for in any tutorial
that I've seen. Hope somebody can point me in the right direction.
This should be pretty simple: I have two dictionaries, foo and bar.
I am certain that all keys in bar belong to foo as well, but I also
know that not all keys in foo exist in bar. All the keys in both foo
and bar are tuples (in the bigram form ('word1', 'word2)). I have to
prime foo so that each key has a value of 1. The values for the keys
in bar are variable integers. All I want to do is run a loop through
foo, match any of its keys that also exist in bar, and add those key's
values in bar to the preexisting value of 1 for the corresponding key
in foo. So in the end the key,value pairs in foo won't necessarily
be, for example, 'tuple1: 1', but also 'tuple2: 31' if tuple2 had a
value of 30 in bar.
I *think* the get method might work, but I'm not sure that it can work
on two dictionaries the way that I'm getting at. I thought that
converting the dictionaries to lists might work, but I can't see a way
yet to match the tuple key as x[0][0] in one list for all y in the
other list. There's just got to be a better way!
Thanks for any help,
Brandon
(trying hard to be Pythonic but isn't there yet)
--
http://mail.python.org/mailman/listinfo/python-list
Re: updating dictionaries from/to dictionaries
"Harder to say what you want to do than to just do it." The truly terrible thing is when you know that's the case even as you're saying it. Thanks for the help, all! -- http://mail.python.org/mailman/listinfo/python-list
Re: updating dictionaries from/to dictionaries
I wasn't sure about the update method either, since AFAICT (not far) the values would in fact update, not append as I needed them to. But the iteritems and get combo definitely worked for me. Thank you for the suggested link. I'm familiar with that page, but my skill level isn't so far along yet that I can more or less intuitively see how to combine methods, particularly in dictionaries. What would be a dream for me is if somebody just had tons of use-case examples - basically this post, condensed, for every potent combination of dictionary methods. A guy can dream. -- http://mail.python.org/mailman/listinfo/python-list
Re: updating dictionaries from/to dictionaries
John:
> "append"? Don't you mean "add"???
Yes, that is what I meant, my apologies.
> What you need to do is practice translating from your
> requirements into Python, and it's not all that hard:
>
> "run a loop through foo" -> for key in foo:
> "match any of its keys that also exist in bar" -> if key in bar:
> "add those key's values in bar to the preexisting value for the
> corresponding key in foo" -> foo[key] += bar[key]
Due to my current level of numbskullery, when I start to see things
like tuples as keys, the apparent ease of this evaporates in front of
my eyes! I know that I need more practice, though, and it will come.
>
> But you also need to examine your requirements:
> (1) on a mechanical level, as I tried to point out in my first
> response, if as you say all keys in bar are also in foo, you can
> iterate over bar instead of and faster than iterating over foo.
> (2) at a higher level, it looks like bar contains a key for every
> possible bigram, and you are tallying actual counts in bar, and what
> you want out for any bigram is (1 + number_of_occurrences) i.e.
> Laplace adjustment. Are you sure you really need to do this two-dict
> caper? Consider using only one dictionary (zot):
>
> Initialise:
> zot = {}
>
> To tally:
> if key in zot:
>zot[key] += 1
> else:
>zot[key] = 1
>
> Adjusted count (irrespective of whether bigram exists or not):
> zot.get(key, 0) + 1
>
> This method uses space proportional to the number of bigrams that
> actually exist. You might also consider collections.defaultdict, but
> such a dict may end up containing entries for keys that you ask about
> (depending on how you ask), not just ones that exist.
You are very correct about the Laplace adjustment. However, a more
precise statement of my overall problem would involve training and
testing which utilizes bigram probabilities derived in part from the
Laplace adjustment; as I understand the workflow that I should follow,
I can't allow myself to be constrained only to bigrams that actually
exist in training or my overall probability when I run through testing
will be thrown off to 0 as soon as a test bigram that doesn't exist in
training is encountered. Hence my desire to find all possible bigrams
in train (having taken steps to ensure proper set relations between
train and test). The best way I can currently see to do this is with
my current two-dictionary "caper", and by iterating over foo, not
bar :)
And yes, I know it seems silly to wish for that document with the use-
cases, but personally speaking, even if the thing is rather lengthy, I
would probably pick up better techniques for general knowledge by
reading through it and seeing the examples.
I actually think that there would be a good market (if only in
mindshare) for a thorough examination of the power of lists, nested
lists, and dictionaries (with glorious examples) - something that
might appeal to a lot of non-full time programmers who need to script
a lot but want to be efficient about it, yet don't want to deal with a
tutorial that unnecessarily covers all the aspects of Python. My
$0.027 (having gone up due to the commodities markets).
Thanks again for the input, I do appreciate it!
Brandon
--
http://mail.python.org/mailman/listinfo/python-list
Re: updating dictionaries from/to dictionaries
On Aug 12, 7:26 am, John Machin <[EMAIL PROTECTED]> wrote: > On Aug 12, 12:26 pm, Brandon <[EMAIL PROTECTED]> wrote: > > > > > You are very correct about the Laplace adjustment. However, a more > > precise statement of my overall problem would involve training and > > testing which utilizes bigram probabilities derived in part from the > > Laplace adjustment; as I understand the workflow that I should follow, > > I can't allow myself to be constrained only to bigrams that actually > > exist in training or my overall probability when I run through testing > > will be thrown off to 0 as soon as a test bigram that doesn't exist in > > training is encountered. Hence my desire to find all possible bigrams > > in train (having taken steps to ensure proper set relations between > > train and test). > > The best way I can currently see to do this is with > > my current two-dictionary "caper", and by iterating over foo, not > > bar :) > > I can't grok large chunks of the above, especially these troublesome > test bigrams that don't exist in training but which you desire to find > in train(ing?). > > However let's look at the mechanics: Are you now saying that your > original assertion "I am certain that all keys in bar belong to foo as > well" was not quite "precise"? If not, please explain why you think > you need to iterate (slowly) over foo in order to accomplish your > stated task. I was merely trying to be brief. The statement of my certainty about foo/bar was precise as a stand-alone statement, but I was attempting to say that within the context of the larger problem, I need to iterate over foo. This is actually for a school project, but as I have already worked out a feasible (if perhaps not entirely optimized) workflow, I don't feel overly guilty about sharing this or getting some small amount of input - but certainly none is asked for beyond what you've given me :) I am tasked with finding the joint probability of a test sequence, utilizing bigram probabilities derived from train(ing) counts. I have ensured that all members (unigrams) of test are also members of train, although I do not have any idea as to bigram frequencies in test. Thus I need to iterate over all members of train for training bigram frequencies in order to be prepared for any test bigram I might encounter. The problem is that without Laplace smoothing, many POTENTIAL bigrams in train might have an ACTUAL frequency of 0 in train. And if one or more of those bigrams which have 0 frequency in train is actually found in test, the joint probability of test will become 0, and that's no fun at all. So I made foo dictionary that creates all POTENTIAL training bigrams with a smoothed frequency of 1. I also made bar dictionary that creates keys of all ACTUAL training bigrams with their actual values. I needed to combine the two dictionaries as a first step to eventually finding the test sequence probability. So any bigram in test will at least have a smoothed train frequency of 1 and possibly a smoothed train frequency of the existing train value + 1. Having iterated over foo, foo becomes the dictionary which holds these smoothed & combined train frequencies. I don't see a way to combine the two types of counts into one dictionary without keeping them separate first. Hence the caper. Sorry for the small essay. P.S. I do realize that there are better smoothing methods than Laplace, but that is what the problem has specified. -- http://mail.python.org/mailman/listinfo/python-list
Re: updating dictionaries from/to dictionaries
> (1) iterating over foo: > for key in foo: >foo[key] += bar.get(key, 0) > > (2) iterating over bar: > for key in bar: >foo[key] += bar[key] > > I (again) challenge you to say *why* you feel that the "iterating over > bar" solution will not work. Well if you're going to be clever enough to iterate over bar and then send the results to another dictionary altogether, I obviously cannot put up a good argument on this matter! Thanks for the input, I appreciate it. -- http://mail.python.org/mailman/listinfo/python-list
File copying from a menu
I'm attempting to have a file copied from a menu selection. The menu already exists, but it won't even create the menu item. If anyone has any ideas, please let me know. -- http://mail.python.org/mailman/listinfo/python-list
Re: File copying from a menu
Ok, below is a portion of the code that first (near as I can tell because I
had nothign to do with desgining the program) sets up the menu
(setupMenuBar) and then adds the commands to be used with the items:
def setupMenuBar(self):
menubar = self.menuBar()
file_ = menubar.addMenu("&File")
file_.addAction(self.importEx)
file_.addAction(self.exitAct)
def createActions(self):
fileMenu = QtGui.QMenu(self.tr("&File"), self)
self.importEx = QtGui.QAction(self.tr("&Import Excel Document"),
self)
self.importEx.setShortcut(self.tr("Ctrl+E"))
self.importEx.setStatusTip(self.tr("Import Excel Document"))
self.connect(self.importEx, QtCore.SIGNAL("triggered()"),
self.importExcel)
self.exitAct = QtGui.QAction(self.tr("E&xit"), self)
self.exitAct.setShortcut(self.tr("Ctrl+Q"))
self.exitAct.setStatusTip(self.tr("Exit the application"))
self.connect(self.exitAct, QtCore.SIGNAL("triggered()"), self,
QtCore.SLOT("close()"))
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Brandon wrote:
>
>> I'm attempting to have a file copied from a menu selection. The menu
>> already exists, but it won't even create the menu item. If anyone has
>> any ideas, please let me know.
>
> try cutting down your code to a minimal example that illustrates the
> problem, and post that code (that'll also allow us to figure out what
> library you're using to create the menu...).
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: File copying from a menu
Turns out I was missing a few lines of code here-and-there, but now it's visible and working. Thanks to anyone who was looking into this for me. "Fredrik Lundh" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Brandon wrote: > >> I'm attempting to have a file copied from a menu selection. The menu >> already exists, but it won't even create the menu item. If anyone has >> any ideas, please let me know. > > try cutting down your code to a minimal example that illustrates the > problem, and post that code (that'll also allow us to figure out what > library you're using to create the menu...). > > -- http://mail.python.org/mailman/listinfo/python-list
Question about getmtime
Hi everyone, Does copying or moving a file affect the return value of os.path.getmtime(path)? Thank you, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about getmtime
On Feb 19, 10:26 am, Krister Svanlund wrote: > On Fri, Feb 19, 2010 at 5:05 PM, Brandon wrote: > > Hi everyone, > > > Does copying or moving a file affect the return value of > > os.path.getmtime(path)? > > > Thank you, > > Brandon > > Wouldn't it be easier to make a script and see for yourself then to > write a mail about it? Gee, thanks for the help. I guess. -- http://mail.python.org/mailman/listinfo/python-list
tkFileDialogs
I'm wanting to allow users to select hidden directories in windows and it seems that using the tkFileDialog.askdirectory() won't allow for that. It's using the tkFileDialog.Directory class which calls an internal command 'tk_chooseDirectory' . However the file selector dialogs (askopenfilename, asksaveasfilename, etc) has the common windows dialog which supports showing hidden folders. It's using the tkFileDialog.Open class which is calling an internal command of 'tk_getOpenFile'. Can anyone shed light on why these two dialogs are so very different and possibly give me a solution to this hidden directory issue. I have found that you can't really use the Open class because it's going to require a file be selected, not a directory and the Directory class won't navigate to or have an initialdir that is hidden (on windows the %APPDAT% folder is hidden by default) Windows Example Code. import tkFileDialog # Won't start in or allow navigation to APPDATA test = tkFileDialog.askdirectory(initialdir='%APPDATA%') # Will start in and navigate to APPDATA test = tkFileDialog.askopenfile(initialdir='%APPDATA%') Thanks in advance for any help given! Brandon L. Harris -- http://mail.python.org/mailman/listinfo/python-list
RE: tkFileDialogs
It doesn't matter whether I pass the actual path in or the global variable name. The result is the same. Brandon L. Harris From: Karim [[email protected]] Sent: Friday, July 06, 2012 12:42 AM To: brandon harris Subject: Re: tkFileDialogs Le 06/07/2012 07:22, brandon harris a écrit : > I'm wanting to allow users to select hidden directories in windows and it > seems that using the tkFileDialog.askdirectory() won't allow for that. It's > using the tkFileDialog.Directory class which calls an internal command > 'tk_chooseDirectory' . However the file selector dialogs (askopenfilename, > asksaveasfilename, etc) has the common windows dialog which supports showing > hidden folders. It's using the tkFileDialog.Open class which is calling an > internal command of 'tk_getOpenFile'. > > Can anyone shed light on why these two dialogs are so very different and > possibly give me a solution to this hidden directory issue. I have found > that you can't really use the Open class because it's going to require a file > be selected, not a directory and the Directory class won't navigate to or > have an initialdir that is hidden (on windows the %APPDAT% folder is hidden > by default) > > Windows Example Code. > > import tkFileDialog > # Won't start in or allow navigation to APPDATA > test = tkFileDialog.askdirectory(initialdir='%APPDATA%') > # Will start in and navigate to APPDATA > test = tkFileDialog.askopenfile(initialdir='%APPDATA%') > > Thanks in advance for any help given! > > > Brandon L. Harris Heuu. Don't you use os.environ['APPDATA'] if this is an environment variable? Cheers karim -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python a commercial proposition ?
Another common use is to create automated regression testing frameworks, and other automation tools. I see posting for python developers for this type of thing all the time on stack overflow careers. On Sun, Jul 29, 2012 at 11:43 AM, Mark Lawrence wrote: > On 29/07/2012 17:01, lipska the kat wrote: >> >> Pythoners >> >> Firstly, thanks to those on the tutor list who answered my questions. >> >> I'm trying to understand where Python fits into the set of commonly >> available, commercially used languages of the moment. >> >> My most recent experience is with Java. The last project I was involved >> with included 6775 java source files containing 1,145,785 lines of code. >> How do I know this? because I managed to cobble together a python script >> that walks the source tree and counts the lines of code. It ignores >> block and line comments and whitespace lines so I'm fairly confident >> it's an accurate total. It doesn't include web interface files (mainly >> .jsp and HTML) or configuration files (XML, properties files and what >> have you). In fact it was remarkably easy to do this in python which got >> me thinking about how I could use the language in a commercial >> environment. >> >> I was first attracted to python by it's apparent 'Object Orientedness' I >> soon realised however that by looking at it in terms of the language I >> know best I wasn't comparing like with like. Once I had 'rebooted the >> bioware' I tried to approach python with an open mind and I have to say >> it's growing on me. >> >> The questions I have are ... >> >> How is python used in the real world. >> What sized projects are people involved with >> Are applications generally written entirely in python or is it more >> often used for a subset of functionality. >> >> I hope this is an acceptable question for this group > > > You are hard pushed to find anything here that's unacceptable, that's why I > like reading this list so much. > >> >> Many thanks >> >> Lipska >> > > There's a list of companies who use python on www.python.org top right of > the page. You may have heard of one or two of them. > > -- > Cheers. > > Mark Lawrence. > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Python threading/multiprocessing issue.
I'm working on a tool that runs a number of process is separate thread. I've, up to this point, been using threading.Thread, but from what I read multiprocess will allow multiple processors to be used From the python docs on multiprocessing. I have run into an issue when modifying the thread object from the run method. Threading.thread allows me to change an attribute in the run method and it hold while multiprocessing.Process loses it. Here is an example illustrating the inconsistency that I've seen. -- | import time import multiprocessing import threading def simple_process_call(): my_process = SimpleProcess() my_process.start() while not my_process.done.is_set(): pass print my_process.my_attribute class SimpleProcess(multiprocessing.Process): def __init__(self): super(SimpleProcess, self).__init__() self.my_attribute = 'Fail' self.done = multiprocessing.Event() def run(self): self.my_attribute = 'Success' time.sleep(5) self.done.set() def simple_thread_call(): my_thread = SimpleThread() my_thread.start() while not my_thread.done.is_set(): pass print my_thread.my_attribute class SimpleThread(threading.Thread): def __init__(self): super(SimpleThread, self).__init__() self.my_attribute = 'Fail' self.done = threading.Event() def run(self): self.my_attribute = 'Success' time.sleep(5) self.done.set() if __name__ == '__main__': # simple_process_call() simple_thread_call()| -- The odd thing is that I can modify the multiprocessing.Event and it holds, but modifying any attribute on the class goes away. If I am super ignorant of something, please cure me of it. Thanks in advance! Brandon L. Harris -- http://mail.python.org/mailman/listinfo/python-list
Python threading/multiprocessing issue.
I'm working on a tool that runs a number of process is separate thread. I've, up to this point, been using threading.Thread, but from what I read multiprocess will allow multiple processors to be used From the python docs on multiprocessing. I have run into an issue when modifying the thread object from the run method. Threading.thread allows me to change an attribute in the run method and it hold while multiprocessing.Process loses it. Here is an example illustrating the inconsistency that I've seen. -- | import time import multiprocessing import threading def simple_process_call(): my_process = SimpleProcess() my_process.start() while not my_process.done.is_set(): pass print my_process.my_attribute class SimpleProcess(multiprocessing.Process): def __init__(self): super(SimpleProcess, self).__init__() self.my_attribute = 'Fail' self.done = multiprocessing.Event() def run(self): self.my_attribute = 'Success' time.sleep(5) self.done.set() def simple_thread_call(): my_thread = SimpleThread() my_thread.start() while not my_thread.done.is_set(): pass print my_thread.my_attribute class SimpleThread(threading.Thread): def __init__(self): super(SimpleThread, self).__init__() self.my_attribute = 'Fail' self.done = threading.Event() def run(self): self.my_attribute = 'Success' time.sleep(5) self.done.set() if __name__ == '__main__': # simple_process_call() simple_thread_call()| -- The odd thing is that I can modify the multiprocessing.Event and it holds, but modifying any attribute on the class goes away. If I am super ignorant of something, please cure me of it. Thanks in advance! Brandon L. Harris -- http://mail.python.org/mailman/listinfo/python-list
Re: Python threading/multiprocessing issue.
I see. Well I was hoping to see the same result in the multiprocessing example as using the threading example. What you pointed out makes sense though, but what I don't understand is how modifying the queue in the example works fine in both. Possibly it was designed for that kind of use? Brandon L. Harris On 07/15/2011 03:55 PM, Lee Harr wrote: I'm working on a tool that runs a number of process is separate thread. I've, up to this point, been using threading.Thread, but from what I read multiprocess will allow multiple processors to be used From the python docs on multiprocessing. I have run into an issue when modifying the thread object from the run method. Threading.thread allows me to change an attribute in the run method and it hold while multiprocessing.Process loses it. I am not a multiprocessing expert, but I think the problem you are having is that Process is running your code in a separate process, so there is no way you could see those object changes in your main line code. In other words, Process is not an exact replacement for Thread. If you need to communicate between the different parts, you would want to use the abstractions provided by Queue or Pipe. Keep reading down the multiprocessing page in the docs until you get to "Exchanging objects between processes": http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes "Sharing state between processes" seems like it will be especially relevant to what you are doing: http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes Basically, it says "don't do that" :o) Here is an example illustrating the inconsistency that I've seen. One thing that would help here is a sample of what output you get from your code, and what you were hoping to get. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 8 and extraneous whitespace
I don't really think lining things up makes them any easier to read. In fact, the consistency in a single space on either side of an operator keeps things neat and clean. Also easier to maintain in any editor. Always lining up columns of stuff requires readjusting text every time you add a new longer variable and you can never be consistent in how much whitespace is there. Brandon L. Harris On 07/21/2011 01:46 PM, Andrew Berg wrote: -BEGIN PGP SIGNED MESSAGE- Hash: RIPEMD160 On 2011.07.21 01:32 PM, Thomas Jollans wrote: So, the PEP says: do not align operators. End of story. I'm pretty sure that colons, commas and equals signs are not operators. - -- CPython 3.2.1 | Windows NT 6.1.7601.17592 | Thunderbird 5.0 PGP/GPG Public Key ID: 0xF88E034060A78FCB -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.11 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iQEcBAEBAwAGBQJOKHQGAAoJEPiOA0Bgp4/LouMH/3sufiaJiwrD10eVsUlA4rZ0 XpHnXPOl8WY8C1Qv4OFmg2bN5Qd2S5qEhLgwoUDuZVInx8BAN5IPjIms5YQzgyD5 2PWntkPbxyiV+LfZXwKNPuCW4U4WDMznNThdZz3eUVruBkq6PZMv4yqL7XcZLx5T KQG+MNkOxGCXk6ZnNgWHGm2eGP01wAmZyvuB16vifVblH6Gk0Uq1FKjReVsszAI5 updUNgpPMskN9c3N8eU+vrHI839G7yPKtujEZ0LCO2552Ogn4vIsWR+Ir0FBLzcB EBqDzZRmEcCyHobeaLaBZ2qI3OpsF/CTVzx92gqfmf2qhwiSZUFrVqWdmLVhgQc= =P7QL -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 8 and extraneous whitespace
Poor sod? Makes it sound bad when you say it like that. I am not forced to work at that fixed width, but when I work with code, I often have my vim session split vertically and it's super important to keep things at 80 character to quickly read/edit code. Brandon L. Harris On 07/22/2011 02:13 PM, John Gordon wrote: In<[email protected]> Neil Cerutti writes: You can fit much more code per unit of horizontal space with a proportionally spaced font. As a result, that issue, while valid, is significantly reduced. Is it? I assume one major reason for the 80-character limit is to help the poor sod who will eventually get stuck working with your code on an 80-column fixed width terminal window. -- http://mail.python.org/mailman/listinfo/python-list
Re: new to python, trying to choose a book.
I'd suggest Zed Shaw's amazing Learn Python The Hard Way [1] (which isn't as hard as it sounds) - and it's free over the web (but, I believe - you can buy a copy). I dislike Pilgrim's Dive Into Python, but that's just me (though I thoroughly recommend Dive Into HTML5 to anyone interested in HTML5) - many disagree. Haven't read Head First Python. [1] - http://learnpythonthehardway.org/index On Sun, Mar 6, 2011 at 2:21 PM, sogeking99 wrote: > hey. been looking into book for learning python(or what ever resource > really) two books are frequently recommended, learn python the hard > way and think python. i have also been recommended dive into python by > one person, who said it was fantastic. but another person said it was > dated and even when it was made, it wasn't very good. > > i have some experience with programming (not much) i know the basics > of java like control flow and inheritance. but thats about it > > is head first python a good book? i quite liked what i read of head > first python. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Reading Huge UnixMailbox Files
List, I'm trying to import hundreds of thousands of e-mail messages into a database with Python. However, some of these mailboxes are so large that they are giving errors when being read with the standard mailbox module. I created a buffered reader, that reads chunks of the mailbox, splits them using the re.split function with a compiled regexp, and imports each chunk as a message. The regular expression work is where the bottle-neck appears to be, based on timings. I'm wondering if there is a faster way to do this, or some other method that you all would recommend. Brandon McGinty -- http://mail.python.org/mailman/listinfo/python-list
Key Press Not Working
I am trying to catch a key press but it is not working. How can I fix this
code? There is no error message so there is no error message to do a search on.
I am using Python3.5 64-bit inside the terminal.
while True:
key = input("Enter a letter: ")
if key == ord('q'):
break
The loop keeps running even though I have pressed the letter 'q'.
--
https://mail.python.org/mailman/listinfo/python-list
Try: Except: evaluates to True every time
I have this code that tests a server to see if it is listening on port 123 runs and evaluates to True every time. Even if the server does not exist but it is not supposed to do that. I am getting no error message at all. What is going on with this code? #!/usr/bin/env python import socket hostname = ["192.168.1.22", "192.168.1.23", "200.168.1.24", "19.0.0.0"] port = 123 def check_udp(hosts, port_num): '''Test the UDP port on a remove server.''' s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for host in hosts: try: s.connect((host, port_num)) return "Port 53 is reachable on: %s" % host except socket.error as e: return "Error on connect: %s" % e check_udp(hostname, port) -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Data base help
(Apologies for the old thread reviving)
On Sun, Oct 09, 2016 at 09:27:11PM +0200, Irmen de Jong wrote:
> What is your 'database'?
> >From the little information you provided it seems that it is just a text
> >file where
> every drone measurement is on a line. So simply read every line and check if
> the time
> entered is in that line, then print it.
On the other hand, if your "database" really is just a text file
and you want to find the records that match a strict time string
there's already a fast native utility for this available: grep
(*nix) or findstr (Windows).
The advantage being that you could search for more than just the
time. It's still limited to only textual matches, not smart
matches (e.g., ranges). In the end, a custom program will be more
powerful to process the data.
Alternatively, if the data is a text file and you want to query
it regularly, consider learning a bit about SQL and sqlite3 and
import the data into a "real" database first. Then you'll get the
full expressive power of a query language and the performance
improvements of binary data and indexing (if you tune it right).
Regards,
--
Brandon McCaig
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bambams.ca/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
--
https://mail.python.org/mailman/listinfo/python-list
Re: Quick way to calculate lines of code/comments in a collection of Python scripts?
(Sorry for the late reply)
On Wed, Oct 05, 2016 at 01:56:59PM -0400, Malcolm Greene wrote:
> Looking for a quick way to calculate lines of code/comments in a
> collection of Python scripts. This isn't a LOC per day per developer
> type analysis - I'm looking for a metric to quickly judge the complexity
> of a set of scripts I'm inheriting.
There is a CPAN module for a Perl application that calculates
SLOC. You or somebody else may find it useful for this task...
I believe it is packaged for some Linux distros. If applicable
you should be able to just install it:
sudo aptitude install cloc
Otherwise, if you have Perl installed already (e.g., *nix) and
already have a CPAN client [configured] it should be relatively
easy. cpanm is the most user-friendly client I've used.
cpanm App::cloc
Alternatively, you can do it with 'cpan' too, but that will
typically prompt you 3 million times... There are a few other
clients available. Use whatever suits you. You could also fetch
the module directly from CPAN and install it manually if so
inclined.
If you have none of these things (e.g., Windows) you could
install the free software Strawberry Perl distribution. It comes
with batteries included. If you're lucky cpanm will just work(tm)
to install it from there.
Hope that helps...
Regards,
--
Brandon McCaig
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bambams.ca/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
signature.asc
Description: Digital signature
--
https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On Tue, Jan 24, 2017 at 07:31:18PM +, Ben Bacarisse wrote:
> The trouble is that I've been programming for so long that I
> can't remember what it's like to make block and/or indent
> errors. Obviously I make typos but they don't survive more
> than a few seconds.
Agreed. In very rare circumstances (likely very tired) you might
make such a mistake without catching it, but typically you'll
catch it during testing, and code review is another chance to
catch it. Source control FTW. I think that a lot of these kinds
of problems happen to beginners and the beginners make the most
noise about how it will be a problem. I initially was against
Python's significant white-space, but in hindsight I can see how
it saves a bit of typing and is not necessarily any worse off.
Hell, considering the code that I have seen in the wild it might
even catch some extra errors that become syntax errors! It's not
at all rare for indentation to not match in languages that don't
require it to at least fit a pattern.
I think that an apples to apples comparison of an erroneous
indentation level would be comparing a misplaced brace:
foo {
bar;
}
baz;
wapz. Was that supposed to be "foo { bar; baz; }" or "foo { bar;
} baz;" ? That's effectively the same problem that you might
have with Python code. The answer? Hopefully it's obvious when
looking at the code! If it's not, hopefully source control can
tell you. And if you can't be certain, *talk* to somebody.
There's no substitute for communication.
> In Python the editor could, for example, highlight the block
> you are typing in, so as soon as you leave the body of the 'if'
> it would stop being marked and the containing code would be
> highlighted. Just moving the cursor up and down would show you
> what block everything is in. I don't know if any editors help
> like this -- that's part of my reason to ask.
That's actually a pretty neat idea. I don't think I've ever
encoutered an editor that does (or if I have, it has either been
too long or so subtle that it doesn't stand out). I think that it
is a pretty good idea though.
I certainly find it useful to highlight matching braces in
editors, but it can be a pain still. I think that highlighting
the entire block could be useful. Though I suppose it might be
too noisy and distract from what matters? Alternatively, you'd
need different levels of indentation to capture nested
indentation. That shouldn't be a problem if people are limiting
their indentation levels though...
Regards,
--
Brandon McCaig
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bambams.ca/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
signature.asc
Description: Digital signature
--
https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On Tue, Jan 24, 2017 at 07:50:20PM +, Ben Bacarisse wrote:
> I suspect that part of the reason these errors occur is
> precisely because they don't matter to the interpreter and
> students are doing a lot of self-easement based on "does it
> work?" tests.
I cringe when I hear "it works"! In particular, because it's
often followed by "but I don't know how". I can't even count the
number of times I have reviewed code, spotted something
questionable, approached the author about it, and heard "but it
works!" Well if my analysis is correct it shouldn't so one of us
is obviously wrong. Unfortunately, in my experience, they usually
expect the conversation to be over after "but it works"...
Regards,
--
Brandon McCaig
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bambams.ca/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
signature.asc
Description: Digital signature
--
https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On Tue, Jan 24, 2017 at 07:54:30PM -0600, Tim Chase wrote:
> The editor I use (vim) doesn't even require me to re-select the range
> to shift it. Just using
>
> >']
>
> or
>
> <']
>
> will indent/dedent from the cursor to the line where your paste ended.
(O_O) You learn something every day. Thank you.
I have been using Vim and vi for probably close to a decade by
now, but I still have a lot to learn... But nevertheless hate to
go without for even a few seconds.
Regards,
--
Brandon McCaig
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bambams.ca/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
signature.asc
Description: Digital signature
--
https://mail.python.org/mailman/listinfo/python-list
Gzip module does not support Unix compressed .Z files [SEC=UNOFFICIAL]
Hello, I have a query regarding the support of decompression for Unix compressed .Z files in Python's gzip module. The gzip system utility supports this using the '-d' switch, but the python module does not. Obviously this isn't an actual bug, as the Python module is an implementation of the zlib library (which does not actually specify .Z file decompression). But I'd rather not have to shell out to decompress files if possible - as there currently don't seem to be any core python modules which can decompress .Z files. What are the chances of this functionality being included in a core module at some point? Sorry if this is not the correct forum for questions like this - any help would be appreciated. Kind Regards Brandon Owen GNSS Network Operator | Geodesy and Seismic Monitoring Group Community Safety and Earth Monitoring Division | GEOSCIENCE AUSTRALIA Phone: +61 2 6249 9192Fax: +61 2 6249 Email: [email protected]<mailto:[email protected]>Web: www.ga.gov.au<http://www.ga.gov.au/> Cnr Jerrabomberra Avenue and Hindmarsh Drive Symonston ACT GPO Box 378 Canberra ACT 2601 Australia Applying geoscience to Australia's most important challenges Geoscience Australia Disclaimer: This e-mail (and files transmitted with it) is intended only for the person or entity to which it is addressed. If you are not the intended recipient, then you have received this e-mail by mistake and any use, dissemination, forwarding, printing or copying of this e-mail and its file attachments is prohibited. The security of emails transmitted cannot be guaranteed; by forwarding or replying to this email, you acknowledge and accept these risks. - -- https://mail.python.org/mailman/listinfo/python-list
RE: Gzip module does not support Unix compressed .Z files [SEC=UNOFFICIAL]
That's actually the module that I wrote for this purpose (adapted Mark Adler's C code) - I haven't optimised it very much. Brandon Owen GNSS Network Operator | Geodesy and Seismic Monitoring Group Community Safety and Earth Monitoring Division | GEOSCIENCE AUSTRALIA Phone: +61 2 6249 9192 Fax: +61 2 6249 Email: [email protected] Web: www.ga.gov.au Cnr Jerrabomberra Avenue and Hindmarsh Drive Symonston ACT GPO Box 378 Canberra ACT 2601 Australia Applying geoscience to Australia's most important challenges -Original Message- From: Python-list [mailto:[email protected]] On Behalf Of Robert Kern Sent: Tuesday, 5 July 2016 12:18 AM To: [email protected] Subject: Re: Gzip module does not support Unix compressed .Z files [SEC=UNOFFICIAL] On 2016-07-04 09:00, dieter wrote: > "Owen Brandon" writes: > >> I have a query regarding the support of decompression for Unix compressed .Z >> files in Python's gzip module. The gzip system utility supports this using >> the '-d' switch, but the python module does not. > > When I am right, then the "zipfile" module handles ".Z" compressed files. No, that handles PKZIP .zip files. There are third-party modules that handle the .Z format, but shelling out to external programs may still be preferable: https://github.com/umeat/unlzw -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- https://mail.python.org/mailman/listinfo/python-list Geoscience Australia Disclaimer: This e-mail (and files transmitted with it) is intended only for the person or entity to which it is addressed. If you are not the intended recipient, then you have received this e-mail by mistake and any use, dissemination, forwarding, printing or copying of this e-mail and its file attachments is prohibited. The security of emails transmitted cannot be guaranteed; by forwarding or replying to this email, you acknowledge and accept these risks. - -- https://mail.python.org/mailman/listinfo/python-list
Re: Were is a great place to Share your finished projects?
On Fri, Jul 15, 2016 at 10:39:05AM +1000, Steven D'Aprano wrote:
> About seven years ago, the senior technical manager at my work chose hg over
> git. When he left to go to greener pastures, the dev team took about 30
> seconds to to reverse his decision and migrate to git, after which the
> level of VCS-related screw-ups and queries went through the roof.
Git used to have much sharper edges than Mercurial, but that is
pretty much a thing of the past. With Git you pretty much can't
permanently lose history unless you try really, really hard.
It'll always be there in the reflog for a period of several days
minimum (I think 2 weeks by default?) and if you're worried about
it you can configure it to put that off for months or years...
On the other hand, I have had Mercurial bugs repeatedly lose work
of mine. The kind of bugs that aren't easy to reproduce so nearly
impossible to report and nearly impossible to fix. The ecosystem
of "extensions" makes this problem inevitable. You depend on
extensions, typically third-party extensions for the first few
years of their life, for all of the power-user stuff, and the
extensions have as much power to corrupt or lose history as the
main library does. And of course, they have the potential to
alter the behavior of the core library making reporting bugs that
much more difficult ("ok, but which extensions, official or
unofficial, do you have installed?"). Now instead of one team
writing bugs you have N teams writing them in isolation.
Combined with their failure to accomodate the distributed
development model properly you now have a bunch of incompatible
ideas for managing branches and history editing and they still
haven't gotten it all right yet (but they're getting closer the
more and more they model the design after Git).
> To give you an idea of how screwed up things are, even though I'm not one of
> the developer team, and have never pushed a thing into the code
> repositories (I have pushed into documentation repos), somehow according
> to "git blame" I'm responsible for a bunch of code.
The user name and email fields are not controlled in either Git
or Mercurial so anybody can commit code under your name without
you being involved. That would be pretty unprofessional though...
I can't imagine Git magically pulling your name out of nowhere
when it looks up the author of commits that are responsible for
lines of code... Maybe you should report that to the mailing list
and get to the bottom of it... I suspect that the explanation has
nothing to do with any bugs in Git.
Regards,
--
Brandon McCaig
Castopulence Software <https://www.castopulence.org/>
Blog <http://www.bambams.ca/>
perl -E '$_=q{V zrna gur orfg jvgu jung V fnl. }.
q{Vg qbrfa'\''g nyjnlf fbhaq gung jnl.};
tr/A-Ma-mN-Zn-z/N-Zn-zA-Ma-m/;say'
signature.asc
Description: Digital signature
--
https://mail.python.org/mailman/listinfo/python-list
Help with chaos math extensions.
Hi, I have programmed a fractal generator (Julia Set/Mandelbrot Set) in python in the past, and have had good success, but it would run so slowly because of the overhead involved with the calculation. I recently purchased VS .NET 2003 (Win XP, precomp binary of python 2.4.2rc1) to make my own extensions. I was wondering if anyone could help me figure out why I'm getting obscure memory exceptions (runtime errors resulting in automatic closing of Python) with my extension. It seems to run okay if imported alone, but when accompanied in a list of instructions such as a function it crashes. I have implemented it in C and C++, although I prefer the latter. In C I got errors only with certain ranges in my function. I have attached my source to this email and hope someone can help me. Thanks, Brandon c_lib(cpp).tar.gz Description: application/gzip -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with chaos math extensions.
In case you missed it, I said I have windows XP. Windows XP pre-compiled python binaries are built on VS .NET 2003. In order to build extensions, you need the compiler the interpreter was built on, or at least that is what is reported to me by calling setup.py. If I was using linux, which I currently am not, it'd be a different story. Additionally, GCC isn't available for windows XP, only MinGW, the port, and I don't know that much about it to use it running on a Windows platform. Furthermore, I was asking for help on an extension, not an economical question about my programming environment. Thanks > > > On Oct 4, 2005, at 10:25 PM, Brandon Keown wrote: >> >>I have programmed a fractal generator (Julia Set/Mandelbrot Set) >> in python in the past, and have had good success, but it would run so >> slowly because of the overhead involved with the calculation. I >> recently purchased VS .NET 2003 (Win XP, precomp binary of python >> 2.4.2rc1) to make my own extensions. > > Why did you need to purchase anything when gcc is available for free? > > > --- > Andrew Gwozdziewycz > [EMAIL PROTECTED] > http://ihadagreatview.org > http://plasticandroid.org > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with chaos math extensions.
Here's the Script it was being used in (forgive it if it seems a bit
messy, i have been tinkering with variables and such to try different
ideas and haven't really cleaned it up).
import ctest
import Tkinter
import threading
hue_map =
("#FF","#FEFEFF","#FDFDFF","#FCFCFF","#FBFBFF","#FAFAFF","#F9F9FF","#F8F8F8","#F7F7FF","#F6F6F6","#FF","#FF","#FF","#FF","#FF","#FF","#FF",\
"#FF","#FF","#FF","#FF","#FF","#FF","#FF","#FF")
class Mandelbrot_Set(Tkinter.Canvas):
def __init__(self,master,iters):
Tkinter.Canvas.__init__(self,master)
self.dims = {'x':500,'y':500}
self.config(height=self.dims['y'],width=self.dims['x'])
self.r_range = (-2.0,2.0)
self.i_range = (-2.0,2.0)
self.iters = iters
self.prec =
{'r':1.*(self.r_range[1]-self.r_range[0])/(self.dims['x']),'i':1.*(self.i_range[1]-self.i_range[0])/self.dims['y']}
self.escapemap
=
ctest.escapeMap(-1j,self.iters,(self.dims['x'],self.dims['y']),(self.r_range[0],self.r_range[1]),(self.i_range[0],self.i_range[1]))
self.select = False
self.select_event = (0,0)
self.sbox = None
self.bind("",self.selection_box)
self.bind("",self.select_update)
self.t_draw = threading.Thread(target=self.draw)
self.t_draw.start()
def draw(self):
for j in range(self.dims['y']):
i = 0
while i < self.dims['x']:
cur = 0;
try:
color = self.escapemap[j][i]
while self.escapemap[j][i+cur] == color:
cur+=1
except IndexError:
break;
hue_step = 1.*len(hue_map)/self.iters
if color == -1: f = "#00"
else: f = hue_map[int(hue_step*color)]
self.create_line(i,j,i+cur,j,fill=f)
i+=cur
def selection_box(self,event):
if not self.select:
self.select_event = (event.x,event.y)
self.select = True
else:
self.r_range = self.new_range(event.x,self.select_event[0])
self.i_range = self.new_range(event.y,self.select_event[1])
print self.r_range,self.i_range
self.select = False
self.delete(Tkinter.ALL)
self.t_draw.run()
self.select_update(event)
def new_range(self,x,y):
if x > y:
return (y,x)
else:
return (x,y)
def select_update(self,event):
if not self.select:
return
else:
if self.sbox != None:
self.delete(self.sbox)
self.sbox =
self.create_rectangle(self.select_event[0],self.select_event[1],event.x,event.y,fill=None,outline="#00")
else:
self.sbox =
self.create_rectangle(self.select_event[0],self.select_event[1],event.x,event.y,fill=None,outline="#00")
if __name__ == "__main__":
root = Tkinter.Tk()
c = Mandelbrot_Set(root,50)
c.pack()
root.mainloop()
The error occurs in the instantiation of the Mandelbrot_Set object.
Additionally in little mini timing scripts such as
import time
import ctest
t = time.time()
c = ctest.escapeMap(-1j,100,(500,500))
print time.time()-t
this will crash it too
however I found that just opening up the interpreter and typing
import ctest
ctest.escapeMap(-1j,100,(50,50)) #50 yields much
smaller output than 500x500
it generates a 2d tuple fine. So the error seems really obscure to me,
and I don't understand it.
Brandon Keown wrote:
I have programmed a fractal generator (Julia Set/Mandelbrot Set) in
python in the past, and have had good success, but it would run so
slowly because of the overhead involved with the calculation. I
recently purchased VS .NET 2003 (Win XP, precomp binary of python
2.4.2rc1) to make my own extensions. I was wondering if anyone could
help me figure out why I'm getting obscure memory exceptions (runtime
errors resulting in automatic closing of Python) with my extension. It
seems to run okay if imported alone, but when accompanied in a list of
instructions such as a function it crashes.
a short script or interpreter session that illustrates how to get the errors
would help.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Extending Python
I own Python in a Nutshell, as one person pointed out. Alex Martelli does a great job of introducing the concepts, as long as your'e familiar with C. Additionally he covers wrapping (which is sounds like you're trying to do) with SWIG, Pyrex, and a few other options. It's a great book, I have used no other (save python docs) after my introduction. > I am looking for a good tutorial on how to extend python with C code. I > have an application built in C that I need to be able to use in Python. > I have searched through various sources, starting of course with the > Python site itself, and others, but I felt a bit lacking from the > Python site, it seems it was only made for those who installed the > source distribution, as for the other people... Anyways, thanks for the > help! > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with chaos math extensions.
Well, I didn't buy it JUST to compile python extensions, I'm looking to write C++ apps as well, I just use python for a lot of math and science simulations, and I got VS .NET at heavy discount since I'm a student. > Brandon K wrote: >> In case you missed it, I said I have windows XP. Windows XP >> pre-compiled python binaries are built on VS .NET 2003. In order to >> build extensions, you need the compiler the interpreter was built on, >> or at least that is what is reported to me by calling setup.py. If I >> was using linux, which I currently am not, it'd be a different story. >> Additionally, GCC isn't available for windows XP, only MinGW, the >> port, and I don't know that much about it to use it running on a >> Windows platform. Furthermore, I was asking for help on an extension, >> not an economical question about my programming environment. >> >> Thanks >> >>> >>> On Oct 4, 2005, at 10:25 PM, Brandon Keown wrote: >>> >>>> I have programmed a fractal generator (Julia Set/Mandelbrot Set) >>>> in python in the past, and have had good success, but it would run >>>> so slowly because of the overhead involved with the calculation. I >>>> recently purchased VS .NET 2003 (Win XP, precomp binary of python >>>> 2.4.2rc1) to make my own extensions. >>> >>> Why did you need to purchase anything when gcc is available for free? >>> > Since gcc isn't an option, the logical way to proceed would be to do > what others have done and install the Microsoft Toolkit compiler, > available from their web site for the outrageous price of nothing. I can > vouch that it really does compile extensions for Python 2.4 on Windows, > having done that myself. > > See > > http://www.vrplumber.com/programming/mstoolkit/ > > regards > Steve == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: Absolultely confused...
> If I take out the "!" in the format string and just use "O", I can at > least get past PyArg_ParseTuple. Is this a compile-time error? Or a runtime error? == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: recursive function
Is there no way to implement your idea in a classical loop? Usually the syntax is cleaner, and there is no limit (except the limit of the range function in certain cases). For example what would be wrong with. def foo(j): while j < n: j+=1 return j I don't know much about the internals of python, but to me it seems like if you're going to be doing this on the level of 1000s of iterations, there might be some overhead to using recursion (i.e. function calls) that a loop wouldn't have (but that's just a guess). > Hello, > > In a recursive function like the following : > > > def foo( j ) : > j += 1 > while j < n : j = foo( j ) > return j > > > in found that the recursivity is limited (1000 iterations). Then, I have > two questions : > - why this mecanism has been implemented ? > - it is possible to increase or remove (and how) the number of iterations ? > > Regards, > Mathieu == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: recursive function
> def foo(j): > while j < n: > j+=1 > return j > of course I mean: def foo(j): while j < n: j+=1 return j sorry == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: new forum -- homework help/chit chat/easy communication
Hrm...i find it demeaning to relegate Python to a scripting language while Visual Basic is in the "software development" section. Python so outdoes VB in every way shape and form. > I've launched a new forum not too long ago, and I invite you all to go > there: www.wizardsolutionsusa.com (click on the forum link). We offer > all kinds of help, and for those of you who just like to talk, there's > a chit chat section just for you...Just remember that forum > communication is much easier, safer, and faster. > == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: new forum -- homework help/chit chat/easy communication
[EMAIL PROTECTED] wrote: > I've launched a new forum not too long ago, and I invite you all to go > there: www.wizardsolutionsusa.com (click on the forum link). We offer > all kinds of help, and for those of you who just like to talk, there's > a chit chat section just for you...Just remember that forum > communication is much easier, safer, and faster. > [.section Blurb] About me: My name is James (Cantley) Sheppard. I am a North Carolina resident, at the age of 16. I have been programming since the age of 12, and enjoy it as lifes[sic] greatest passion. In the future, I would love to become the leading Software Engineer at a fairly large company, and maybe someday own my own business. As of right now, I am currently in high school and planning on going to a four year college somewhere around the country. Well, that is my life story, and about all I got to say! [.section Commentary] Hrm, obviously hasn't had enough programming experience in 4 years to quite know what he's talking about. Before making random "assertions" James, you might want to take into account the community you're talking to. I don't know about you guys, but I've had enough teen start up webpages. They clog the web. No offense of course to the younger readers, its just...it's like E/N sites...junk most of the time. == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: new forum -- homework help/chit chat/easy communication
> In other words, what is the difference between a "scripting language" > and a "programming language". > Good point. == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows installer, different versions of Python on Windows
When you install Python it plug entries into the registry, so that when you go to install add-ons that are pre-compiled binaries, they look into the registry for the python directory. If you can find out how to manipulate the registry so that the binaries would recognize different installations, you'd be good to go. This would probably involve having copies of the same key with different values. > I would like to install several copies of Python 2.4.2 on my machine, > but it doesn't seem to be possible. > > If I allready has a version installed, the installer only gives the > options to: > > - change python 2.4.2 > - repair python 2.4.2 > - remove python 2.4.2 > > I would like to install different versions of Zope 3, and since it is > installed under a specific python version, the simplest solution would > be to install several Python versions, and install a different zope3 > version under each python install. > > Have I misunderstood something here? > > == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Confused on Kid
Hey, so I heard about the TurboGears posting and decided to investigate. I watched some of their video on building a wiki in 20 minutes and was totally blown away because I'm used to python...straight python, not melding together 4 different APIs into one to blah blah. ANYWAY. I was investigating each subproject individually and could not, for the life of me figure out how Kid worked. I understand that it takes a well-formed XML document and transforms it, but I could not figure out where it transforms it, or how to transform a document. They have plenty of template examples, but I'm left say, "What do I do with this?" I know I can't just pop in it a browser because it has no sort of style sheet or anything so it would just render as an XML document. What do you do after you have a kid template? == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: C Extension - return an array of longs or pointer?
All the veteran programmers out there can correct me, but the way I did
it in my extension was this:
static PyObject *wrap_doNumberStuff(PyObject* self, PyObject* args)
{
char* in = 0;
char* x = 0;
long* result = 0;
int i = 0;
PyObject* py = PyTuple_New()
int ok = PyArg_ParseTuple(args,"ss",&in, &x);
if(!ok) return NULL;
result = doNumberStuff(in,x):
len = sizeof(result)/sizeof(long)
for(i;i < len; i++)
PyTuple_SET_ITEM(py, i,Py_BuildValue("l",*result[i])
}
Simple enough idea...i'm not quite sure if I've done everything
correctly with the pointers, but I'm sure you can figure that out, the
algorithm is simple enough.
> Hi,
>I have been posting about writing a C extension for Python...so far,
> so good. At least for the "simple" functions that I need to wrap.
>
> Ok, my c function looks like...
>
> MY_NUM *doNumberStuff(const char *in, const char *x) { ... }
>
> MY_NUM is defined as, typedef unsigned long MY_NUM; (not sure if that
> matters, or can i just create a wrapper which handles longs?)
>
> anyhow..for my wrapper I have this..
>
> static PyObject *wrap_doNumberStuff(PyObject *self, PyObject args) {
> char *in = 0;
> char *x = 0;
> long *result = 0;
> int ok = PyArg_ParseTuple(args, "ss", &in, &x);
> if (!ok) return 0;
>
> result = doNumberStuff(in, x);
>
> return Py_BuildValue("l", result);
> }
>
> ...my question is...in the c code, result is a pointer to an array of
> longs, how can I get the returned result to be a list or something
> similar to an array in Python?
>
> ...I also have a function which returns a character array (denoted by a
> char *)...would it work the same as the previous question?
>
> Thanks!!
>
== Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups
==
Get Anonymous, Uncensored, Access to West and East Coast Server Farms!
== Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM ==
--
http://mail.python.org/mailman/listinfo/python-list
Re: C Extension - return an array of longs or pointer?
I'm sorry...I just woke up and forgot my C...must have left it in the
Coffee...Anyway, i made a few mistakes (can't initialize blank
tuple...function should return a value, lol).
static PyObject* wrap_doNumberStuff(PyObject* self, PyObject* args)
{
char* in = 0;
char* x = 0;
long* result = 0;
int i = 0;
PyObject* py = NULL;
if(!PyArg_ParseTuple(args,"ss",&in,&x) return NULL;
result = doNumberStuff(in,x);
len = sizeof(result)/sizeof(long);
py = PyTuple_New(len);
for(i; i < len; i++)
PyTuple_SET_ITEM(py, i, Py_BuildValue("l",*result[i]);
return py;
}
Additionally, the Python/C api in the docs tells you all of these nifty
little abstract layer functions that you can call from your extension.
> All the veteran programmers out there can correct me, but the way I did
> it in my extension was this:
>
> static PyObject *wrap_doNumberStuff(PyObject* self, PyObject* args)
> {
> char* in = 0;
> char* x = 0;
> long* result = 0;
> int i = 0;
> PyObject* py = PyTuple_New()
> int ok = PyArg_ParseTuple(args,"ss",&in, &x);
> if(!ok) return NULL;
>
> result = doNumberStuff(in,x):
> len = sizeof(result)/sizeof(long)
> for(i;i < len; i++)
> PyTuple_SET_ITEM(py, i,Py_BuildValue("l",*result[i])
> }
>
> Simple enough idea...i'm not quite sure if I've done everything
> correctly with the pointers, but I'm sure you can figure that out, the
> algorithm is simple enough.
>
== Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups
==
Get Anonymous, Uncensored, Access to West and East Coast Server Farms!
== Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM ==
--
http://mail.python.org/mailman/listinfo/python-list
Re: coloring a complex number
I'm not 100% sure about this, but from what it seems like, the reason
method B worked, and not method a is because class foo(complex) is
subclassing a metaclass. So if you do this, you can't init a meta class
(try type(complex), it equals 'type' not 'complex'. type(complex())
yields 'complex'), so you use the new operator to generator a class on
the fly which is why it works in method B. I hope that's right.
-Brandon
> Spending the morning avoiding responsibilities, and seeing what it would
> take to color some complex numbers.
>
> class color_complex(complex):
> def __init__(self,*args,**kws):
> complex.__init__(*args)
> self.color=kws.get('color', 'BLUE')
>
>>>> a=color_complex(1,7)
>>>> print a
> (1+7j) #good so far
>>>> a=color_complex(1,7,color='BLUE')
> Traceback (most recent call last):
> File "", line 1, in -toplevel-
>a=color_complex(1,7,color='BLUE')
> TypeError: 'color' is an invalid keyword argument for this function
>
> No good... it seems that I am actually subclassing the built_in function
> 'complex' when I am hoping to have been subclassing the built_in numeric
> type - complex.
>
> but some googling sends me to lib/test/test_descr.py
>
> where there a working subclass of complex more in
> accordance with my intentions.
>
> class color_complex(complex):
>def __new__(cls,*args,**kws):
>result = complex.__new__(cls, *args)
>result.color = kws.get('color', 'BLUE')
>return result
>
>>>> a=color_complex(1,7,color='BLUE')
>>>> print a
> (1+7j)
>>>> print a.color
> BLUE
>
> which is very good.
>
> But on the chance that I end up pursuing this road, it would be good if
> I understood what I just did. It would certainly help with my
> documentation ;)
>
> Assistance appreciated.
>
> NOTE:
>
> The importance of the asset of the depth and breadth of Python archives
> - for learning (and teaching) and real world production - should not be
> underestimated, IMO. I could be confident if there was an answer to
> getting the functionality I was looking for as above, it would be found
> easily enough by a google search. It is only with the major
> technologies that one can hope to pose a question of almost any kind to
> google and get the kind of relevant hits one gets when doing a Python
> related search. Python is certainly a major technology, in that
> respect. As these archives serve as an extension to the documentation,
> the body of Python documentation is beyond any normal expectation.
>
> True, this asset is generally better for answers than explanations.
>
> I got the answer I needed. Pursuing here some explanation of that answer.
>
> Art
>
>
== Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups
==
Get Anonymous, Uncensored, Access to West and East Coast Server Farms!
== Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM ==
--
http://mail.python.org/mailman/listinfo/python-list
Re: Xah's edu corner: the Journey of Foreign Characters thru Internet
So just stop talking. It's funny that you guys are having a conversations about not responding to a guys post. First of all, freedom of speech, blah blah, who cares, just let him alone. But certainly don't go on his post, reply, telling people not to reply. That's like saying EVEN THOUGH I'M doing this, YOU should not do it. JUST STOP ALREADY :-). There is of course, the option...instead of starving the troll...FEED HIM TILL HE BURSTS! == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: Most efficient way of storing 1024*1024 bits
BTW, it'd be 6 megabits or 750kb ;) > Six megabytes is pretty much nothing on a modern computer. == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
Re: computer programming
what is .tk? Turkmenistan? or is it just some arbitrary suffix. > www.javaholics.tk == Posted via Newsgroups.com - Usenet Access to over 100,000 Newsgroups == Get Anonymous, Uncensored, Access to West and East Coast Server Farms! == Highest Retention and Completion Rates! HTTP://WWW.NEWSGROUPS.COM == -- http://mail.python.org/mailman/listinfo/python-list
trouble importing modules
I come from a Perl and C background and have been given an application written in Python to maintain and I know very little about Python. I'm having trouble at run time with importing modules. Specifically, in several places time.strptime() is being used and Freeze is being used to produce binaries for each platform where this application runs. _strptime.py is also being supplied with the binaries. The first problem I encountered coming from _strptime.py was: ImportError: No module named calendar _strptime.py imports calendar, but my thought was that since freeze isn't being run against _strptime.py directly, the calendar module may not be getting built into the resulting binary. So, I added "import calendar" to the file I'm running freeze against. This fixed (probably not in the proper way) the above error, but now I'm getting from calendar.py: ImportError: No module named datetime So, my question is how can I ensure that all modules that _strptime.py, calendar.py, etc. rely are built in the resulting binaries without having to import everything explicitly in my code? I'm using Python 2.3.4. Thanks. -- Brandon -- http://mail.python.org/mailman/listinfo/python-list
ERROR: IDLEs subprocesses did not make a connection...
Hello! I am running into the following error and need some guidance. Please see the screenshots of the error, the files I currently have in the /python directory. As well as a link to a troubleshooting post on 'stackoverflow'. Thank you! -Brandon http://stackoverflow.com/questions/15888186/cant-run-python-via-idle-from-explorer-2013-idles-subprocess-didnt-make-c [cid:[email protected]] [cid:[email protected]] Best Regards, Brandon Lee Professional Services Delivery | SMC Softlayer Resident NetApp 469-631-5429 Mobile [email protected]<mailto:[email protected]> [NetApp honored for 13 consecutive years! FORTUNE's 100 Best Companies to Work For(r) 2015]<http://www.netapp.com/us/company/our-story/great-place-to-work/?REF_SOURCE=emsgptw032015> [Facebook]<http://www.facebook.com/NetApp?REF_SOURCE=ems-facebook> [Twitter] <http://twitter.com/#netapp?REF_SOURCE=ems-twitter> [Linked In] <http://www.linkedin.com/groups/NetApp-111681/about?REF_SOURCE=ems-linkedin> [YouTube] <http://www.youtube.com/user/NetAppTV?REF_SOURCE=ems-youtube> [Slideshare] <http://www.slideshare.net/NetApp?REF_SOURCE=ems-slideshare> [Community] <https://communities.netapp.com/welcome?REF_SOURCE=ems-cty> #netapp www.parsintl.com/web/Fortune100BestCreditNotice2015.html<http://www.parsintl.com/web/Fortune100BestCreditNotice2015.html> -- https://mail.python.org/mailman/listinfo/python-list
Try Except Specific Error Messages
Hi,
I am try to get more specific error messages using try/except.
I ran this code with the cable unplugged to see the error message. I got
#!/usr/bin/env python3
import urllib.request
webpage = urllib.request.urlopen("http://fakewebsite.com/";)
text = webpage.read().decode("utf8")
I got two errors. This:
[]
socket.gaierror: [Errno -2] Name or service not known
and this:
[]
urllib.error.URLError:
I tried this but got more error messages.
try:
webpage = urllib.request.urlopen("http://fakewebsite.com/";)
text = webpage.read().decode("utf8")
except URLError as err:
print("URLError: " + str(err))
How do I wrap urllib.request with try/except?
--
https://mail.python.org/mailman/listinfo/python-list
Python Pickling Issue
I have written a fairly large DAG with python and I've run into an issue
when attempting to pickle the data to disk.
It will pickle fine the first time, but if I call pickle again, it
throws this error.
/usr/lib64/python2.6/copy_reg.py in _reduce_ex(self, proto)
68 else:
69 if base is self.__class__:
---> 70 raise TypeError, "can't pickle %s objects" %
base.__name__
71 state = base(self)
72 args = (self.__class__, base, state)
TypeError: can't pickle function objects
I'm calling
save_file = open('my_file.rsf', 'w')
cPickle.dump(self, save_file)
I have attempted to pickle the object to a different file after the
first time, but the error is still thrown.
This wouldn't be very hard to track down if the error gave any
indication as to where or what this function it can't pickle is, so
if there's any possible way to at least get the name of what's failing
to be pickled, that would be a win.
Thanks in advance for all replies.
Brandon L. Harris
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Pickling Issue
After digging around a while I discovered I was attempting to pickle a
third party class that can't be pickled. Initially I was removing it
before pickling and everything was kosher, but at some point it got back
onto the class. Apologies.
Brandon L. Harris
On 11/03/2011 09:42 AM, Brandon Harris wrote:
I have written a fairly large DAG with python and I've run into an
issue when attempting to pickle the data to disk.
It will pickle fine the first time, but if I call pickle again, it
throws this error.
/usr/lib64/python2.6/copy_reg.py in _reduce_ex(self, proto)
68 else:
69 if base is self.__class__:
---> 70 raise TypeError, "can't pickle %s objects" %
base.__name__
71 state = base(self)
72 args = (self.__class__, base, state)
TypeError: can't pickle function objects
I'm calling
save_file = open('my_file.rsf', 'w')
cPickle.dump(self, save_file)
I have attempted to pickle the object to a different file after the
first time, but the error is still thrown.
This wouldn't be very hard to track down if the error gave any
indication as to where or what this function it can't pickle is, so
if there's any possible way to at least get the name of what's failing
to be pickled, that would be a win.
Thanks in advance for all replies.
Brandon L. Harris
--
http://mail.python.org/mailman/listinfo/python-list
ideas for programs?
Hi, I've been learning python for the past couple of months and writing misc scripts here and there, along with some web apps. I'm wondering if anyone has ideas of programs I might try my hand at making? I'd appreciate it if they don't use images, because I'm blind. Also, I'm thinking of hiring myself out as a free-lance programmer. Are there many individuals/companies which would aprove programs written in python? Most adds I've seen require the programmer have a strong grasp of c++ or java. Thanks much for all of your help. THX, Brandon McGinty -- http://mail.python.org/mailman/listinfo/python-list
PythonCard Auto Placement
Hi All, I'm getting started with pythoncard. I'm wondering if there is any way to auto-place the gui elements that I use, so that they are all visible, and aligned? I would use the "layout/resource" editors, but I'm blind, so I can't see where the elements end up, and the controls for moving don't show up as usable controls in my screen reader. Any help is appreciated. Thanks Much, Brandon McGinty -- http://mail.python.org/mailman/listinfo/python-list
RDFXML Parser For "qualified Dublin Core" Database File
Hi All, My goal is to be able to read the www.gutenberg.org <http://www.gutenberg.org/> rdf catalog, parse it into a python structure, and pull out data for each record. The catalog is a Dublin core RDF/XML catalog, divided into sections for each book and details for that book. I have done a very large amount of research on this problem. I've tried tools such as pyrple, sax/dom/minidom, and some others both standard and nonstandard to a python installation. None of the tools has been able to read this file successfully, and those that can even see the data can take up to half an hour to load with 2 gb of ram. So you all know what I'm talking about, the file is located at: http://www.gutenberg.org/feeds/catalog.rdf.bz2 Does anyone have suggestions for a parser or converter, so I'd be able to view this file, and extract data? Any help is appreciated. Thanks, Brandon McGinty [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Parsing Rdf (Rewrite)
Hi All,
I'm trying to parse the rdf catalog at:
http://www.gutenberg.org/feeds/catalog.rdf.bz2
I've put it into an _ElementTree as follows:
import time
import xml.etree.cElementTree as et
tree = et.parse('c:/tmp/catalog2.rdf')
root = tree.getroot()
I would think that I could do:
etexts=tree.findall('pgterms:etext')
(or something like that), Which would pull out each etext record in the
file.
I could then do:
for book in etexts:
print book.get('id')
This isn't yielding anything for me, no matter how I write it.
Any thoughts on this?
What am I doing wrong, or am I even in the realm of possibility, trying to
get thee elements by name?
Thanks,
Brandon
--
Brandon McGinty
McGinty Soft Ltd.
Website design, configuration, and maintenance
Python and PHP coder
Email:[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>
MSN:[EMAIL PROTECTED]
Phone:(480)-202-5790
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to Start
On Sep 13, 5:59 pm, [EMAIL PROTECTED] (Michael R. Copeland) wrote:
>I've decided that Python is a language/environment I'd like to learn
> (I've been a professional programmer for 45+ years), but I really don't
> know where and how to start! I have a number of books - and am buying
> some more - but because of the bewildering number of after-market
> packages, environments, and add-ons, I am really quite perplexed about
> starting. 8<{{
>Yes, I could fire up the interactive mode and play with some
> statements...but I consider that sort of thing for programming neophytes
> or experimenting with specific issues. First, I want to develop a
> simple Windows application, and because of the plethora of "stuff" the
> Python world offers, I don't know where to begin.
>For example, what basic, easy-to-use interface might I start with to
> build a simple text file parsing and analysis program? That is, I'd
> like to start with a simple Windows shell that prompts for a file name,
> processes it, and then displays some result.
>I am certainly impressed with the apparent experience and openness of
> the regular players here, but the discussions here (and in
> c.l.p.announce) truly presume knowledge and experience with Python I
> don't yet have. Yes, for even a very experienced programmer, entering
> the Python world is very daunting - but I want to get started.
>Please advise. TIA
Michael,
I suggest starting with Python's core documentation. Its rather well
written and contains many examples. If nothing else, a thorough
review of the Library reference may help you evaluate the
"after-market packages, environments, and add-ons" you describe.
http://docs.python.org/tut/tut.html (Tutorial)
http://docs.python.org/lib/lib.html (Library Reference)
http://docs.python.org/ref/ref.html (Language Reference)
The simple text parsing and analysis program you are considering seems
unlikely to require either "Extending and Embedding" or the Python/C
API, but if you find yourself drawn to either topic I again suggest
starting with the core documentation.
http://docs.python.org/ext/ext.html (Extending and Embedding)
http://docs.python.org/api/api.html (Python/C API)
You may also find it useful to examine others' programs. The Python
Package Index and ActiveState's Python Cookbook are both excellent
resources.
http://cheeseshop.python.org/pypi (Package Index)
http://aspn.activestate.com/ASPN/Python/Cookbook/
Every new Python user should read David Goodger's "Idiomatic Python"
tutorial.
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
I've benefited greatly from HOWTOs available at A.M. Kuchling's
website.
http://www.amk.ca/python/howto/
Be sure to consider the optparse and cmd modules if you decide to
develop the simple shell you've described.
I hope this helps,
Brandon
--
http://mail.python.org/mailman/listinfo/python-list
Algebraic Modules For Python
Hi All, I know that there is probably a great deal of literature on this on the net, but I don't have any time to go searching. Does anyone have any suggestions for modules that will allow python to do the functions of a graphing calculator or similar device, performing operations on matricies, graphing or listing points for function, etc? If not, I may be developing some; I am a blind highschool student and as of now there are no accessible graphing calculators for me to use in my algebra 2 class. Thanks for your help. Thanks, Brandon McGinty -- Brandon McGinty McGinty Soft Ltd. Website design, configuration, and maintenance Python and PHP coder Email:[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]> MSN:[EMAIL PROTECTED] Phone:(480)-202-5790 -- http://mail.python.org/mailman/listinfo/python-list
paths in modules
I am developing a project in Python which uses several external utilities.
For convenience, I am wrapping these accesses in a module. The problem is
that I cannot be sure where these modules are imported from, so I am
trying to figure out how to reliably execute e.g. a popen call. Example
layout:
toplevel_dir
+-main script
+-wrapper_dir
+-some_wrapper
+-utility_dir
+-some_external_utility
So in my main script, I might say:
from wrapper_dir import some_wrapper
some_wrapper.use_external_utility()
And then in some_wrapper, I would have code like:
import os
def use_external_utility():
f = os.popen('utility_dir/some_external_utility')
lines = f.readlines()
f.close()
return lines
Of course, the problem with that approach is that it fails because there
is no utility_dir in the CWD, which is actually top_level_dir. So my
question is whether there is any way to specify that specified paths are
relative to the module's directory rather than the importing file's
directory. I would really like to avoid kludging together some solution
that involves passing variables or having knowledge of where my module is
being imported from.
I am hoping that there is some simple solution to this problem that I
simply haven't found in my searches so far. If so, I will humbly accept
any ridicule that comes along with said simple solution :-).
Thanks in advance,
Brandon
--
http://mail.python.org/mailman/listinfo/python-list
Re: paths in modules
On Thu, 22 Feb 2007 11:13:46 -0500, Brandon Mintern wrote: > Of course, the problem with that approach is that it fails because there > is no utility_dir in the CWD... ...and of course by CWD, I actually mean "current working directory", which should have actually been PWD or "present working directory". Anyway, I just wanted to clear up any confusion that might result due to my improper terminology. -- http://mail.python.org/mailman/listinfo/python-list
Re: paths in modules (solved)
On Thu, 22 Feb 2007 08:28:50 -0800, Paul Boddie wrote: > And you really want to refer to utility_dir relative to some_wrapper. > What you can try is to split the __file__ attribute of some_wrapper - > it's a standard attribute on imported modules - in order to refer to > the module's parent directory (which should correspond to > wrapper_dir): > > parent_dir, filename = os.path.split(__file__) > > Then you can join the parent directory to the path of the command: > > cmd = os.path.join(parent_dir, "utility_dir", "some_external_utility") > > The __file__ attribute of modules is documented here: > > http://docs.python.org/ref/ty__file__ is the pathname of the file from > which the module was loadedpes.html#l2h-109 > > Paul Thanks a lot. I was hoping for a solution like that, and it worked perfectly for me (admittedly, in my trivial test files, but I'm sure that the solution will extend to my actual use case). Also, I had actually read that documentation you pointed me to, but the language, "__file__ is the pathname of the file from which the module was loaded" had me thinking that it was the pathname of the file doing the loading, rather than the file being loaded. I guess I should have actually tried it out. Anyways, thanks for the quick response and for the clarification. -- http://mail.python.org/mailman/listinfo/python-list
Re: paths in modules
On Thu, 22 Feb 2007 10:30:59 -0600, Larry Bates wrote:
> Normally this would be:
>
> f = os.popen('./wrapper_dir/utility_dir/some_external_utility')
>
> -Larry
Yes, but the problem with that solution is, let's say that I further
abstract the whole thing and I add a directory outside of my toplevel_dir,
which has the syntax:
from toplevel_dir.wrapper_dir import some_wrapper
some_wrapper.use_external_utility()
Now, once again, the module is broken. This is what I was trying to
avoid. At any rate, Paul's solution was exactly what I was looking for.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python beginner!
On 11/16/07, Shawn Milochik <[EMAIL PROTECTED]> wrote: > I completely support Wildemar. Lazy questions like that deserve absolutely > nothing. > > I agree that cushioning the reply with a brief explanation of why that > question sucks would have helped the original poster, but he doesn't deserve > any effort from any of us until he has shown evidence of his own efforts. > Then he will find a lot of friendly help. How do you know that he hasn't investigated this? Maybe all the google examples he found suck or he still has questions. *He* should have been wordier too, but you are assuming a lot. That being said, if he doesn't reply back my assumption is that he was just a troll, trying to ellicit a response similar Wildemar's. (which is all the more the reason to *not* respond in such a way) -- http://mail.python.org/mailman/listinfo/python-list
Compile with GLib-1.2 instead of 2.4
Hi, I am having to compile a standalone python because the webserver I use doesn't allow access to /usr/lib/python. I tried compiling on my lappy and uploading it, but the webserver does not have GLib-2.4. What arguments would I have to include in order for it to compile with GLib-1.2 instead of/and GLib2.4? Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: Compile with GLib-1.2 instead of 2.4
Sorry, I know what arg to use with ./configure. With --with-libc=STRING, do I put the version I want, or the path to my GLib 1.2 files? On Tue, 2008-01-15 at 14:53 -0600, Brandon Perry wrote: > Hi, I am having to compile a standalone python because the webserver I > use doesn't allow access to /usr/lib/python. I tried compiling on my > lappy and uploading it, but the webserver does not have GLib-2.4. What > arguments would I have to include in order for it to compile with > GLib-1.2 instead of/and GLib2.4? > > Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Unknown cause to error (new to python)
Hi, I am having to compile a standalone version of python for the web server I use (they don't allow access to /usr/bin/python). I posted earlier about a GLib error, but I have fixed that now. I am very close to getting this to work, but I am getting some weird errors. File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", line 41, in ? File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", line 71, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", line 4, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", line 4, in ? File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", line 15, in ? I am using 2.2 for compatibility purposes. Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: Unknown cause to error (new to python)
Sorry, this is all I can get. :-( This isn't my webserver, so the only error logs I get are what they give me. I guess I will just have to keep working at it. Thanks for looking at it though, Brandon On Wed, 2008-01-16 at 15:12 +0100, Bruno Desthuilliers wrote: > Brandon Perry a écrit : > > Hi, I am having to compile a standalone version of python for the web > > server I use (they don't allow access to /usr/bin/python). I posted > > earlier about a GLib error, but I have fixed that now. I am very close > > to getting this to work, but I am getting some weird errors. > > > > File "/home/vminds/public_html/torrents/python/lib/python2.2/socket.py", > > line 41, in ? > > File "/home/vminds/public_html/torrents/python/lib/python2.2/httplib.py", > > line 71, in ? > > File > > "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/zurllib.py", > > line 4, in ? > > File > > "/home/vminds/public_html/torrents/TF_BitTornado/BitTornado/download_bt1.py", > > line 4, in ? > > File "/home/vminds/public_html/torrents/TF_BitTornado/btphptornado.py", > > line 15, in ? > > Sorry but my crystal ball is broken. Please post the *whole* traceback. > -- http://mail.python.org/mailman/listinfo/python-list
Extracting file from zip archive in Python 2.6.1
Hello everyone, I'm having an issue specifying the path for extracting files from a .zip archive. In my method, I have: zip_file.extract(zip_name + '/' + thumbnail_image, thumbnail_path) What is happening is that the extract method is creating a folder with the name of 'zip_name' and extracting the files to it. Example: if 'thumbnail_path' is 'images/inventory/thumbnails/' extract is creating: 'images/inventory/thumbnails/test1/' and saving the files out. How can I set the path to be exactly: 'images/inventory/thumbnails' ? TIA, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting file from zip archive in Python 2.6.1
On Feb 3, 9:45 am, "Gabriel Genellina" wrote: > En Tue, 03 Feb 2009 05:31:24 -0200, Brandon Taylor > escribió: > > > I'm having an issue specifying the path for extracting files from > > a .zip archive. In my method, I have: > > > zip_file.extract(zip_name + '/' + thumbnail_image, thumbnail_path) > > > What is happening is that the extract method is creating a folder with > > the name of 'zip_name' and extracting the files to it. Example: > > extract will create all directories in member name. Use open instead: > > with zip_file.open(zip_name + '/' + thumbnail_image) as source: > with open(os.path.join(thumbnail_path, thumbnail_image), "wb") as target: > shutil.copyfileobj(source, target) > > (untested) > > -- > Gabriel Genellina Hi Gabriel, Thank you for the code sample. I figured I was going to have to use 'open', but I completely forgot about the 'with' statement. I was trying to figure out how to get access to the file object in the zip without having to loop over all of the items, and 'with' will allow me to do just that. I'll give it a shot when I get home this evening and post my results. Kind regards, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting file from zip archive in Python 2.6.1
On Feb 3, 1:16 pm, Brandon Taylor wrote: > On Feb 3, 9:45 am, "Gabriel Genellina" wrote: > > > > > En Tue, 03 Feb 2009 05:31:24 -0200, Brandon Taylor > > escribió: > > > > I'm having an issue specifying the path for extracting files from > > > a .zip archive. In my method, I have: > > > > zip_file.extract(zip_name + '/' + thumbnail_image, thumbnail_path) > > > > What is happening is that the extract method is creating a folder with > > > the name of 'zip_name' and extracting the files to it. Example: > > > extract will create all directories in member name. Use open instead: > > > with zip_file.open(zip_name + '/' + thumbnail_image) as source: > > with open(os.path.join(thumbnail_path, thumbnail_image), "wb") as target: > > shutil.copyfileobj(source, target) > > > (untested) > > > -- > > Gabriel Genellina > > Hi Gabriel, > > Thank you for the code sample. I figured I was going to have to use > 'open', but I completely forgot about the 'with' statement. I was > trying to figure out how to get access to the file object in the zip > without having to loop over all of the items, and 'with' will allow me > to do just that. > > I'll give it a shot when I get home this evening and post my results. > > Kind regards, > Brandon Ok, the first thing I needed to do was add: from __future__ import with_statement at the beginning of my file but: with zip_file.open(zip_name + '/' + thumbnail_image) as source: with open(os.path.join(thumbnail_path, thumbnail_image), 'wb') as target: shutil.copyfileobj(source, target) Returns an error on the first line: ZipExtFile instance has no attribute '__exit__' Googling this error message is turning up nothing, and there's no mention of the exception in the docs. Any thoughts? TIA, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting file from zip archive in Python 2.6.1
On Feb 3, 9:15 pm, [email protected] wrote: > Quoth Brandon Taylor : > > > > > Ok, the first thing I needed to do was add: > > > from __future__ import with_statement at the beginning of my file > > > but: > > > with zip_file.open(zip_name + '/' + thumbnail_image) as source: > > with open(os.path.join(thumbnail_path, > > thumbnail_image), 'wb') as target: > > shutil.copyfileobj(source, target) > > > Returns an error on the first line: > > > ZipExtFile instance has no attribute '__exit__' > > > Googling this error message is turning up nothing, and there's no > > mention of the exception in the docs. Any thoughts? > > Yeah, that means the ZipExtFile object hasn't been extended to > handle the context management protocol. It would be pretty > simple to roll your own for it. Take a look at the contextlib > module. > > --RDM Cool. Thanks for the pointers. In the meantime, I just used extract and os.rename to move the files where I need them, but I'll see if I can save that extra step if possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting file from zip archive in Python 2.6.1
On Feb 4, 12:16 am, "Gabriel Genellina" wrote: > En Wed, 04 Feb 2009 00:36:40 -0200, Brandon Taylor > escribió: > > > > > On Feb 3, 1:16 pm, Brandon Taylor wrote: > >> On Feb 3, 9:45 am, "Gabriel Genellina" wrote: > >> > En Tue, 03 Feb 2009 05:31:24 -0200, Brandon Taylor > >> > escribió: > >> > > zip_file.extract(zip_name + '/' + thumbnail_image, thumbnail_path) > >> > > What is happening is that the extract method is creating a folder > > >> > with > >> > > the name of 'zip_name' and extracting the files to it. Example: > >> > extract will create all directories in member name. Use open instead: > >> > with zip_file.open(zip_name + '/' + thumbnail_image) as source: > >> > with open(os.path.join(thumbnail_path, thumbnail_image), "wb") as > >> > target: > >> > shutil.copyfileobj(source, target) > > Ok, the first thing I needed to do was add: > > > from __future__ import with_statement at the beginning of my file > > That should not be necesary with your Python version (2.6.1 isn't it?) > > > with zip_file.open(zip_name + '/' + thumbnail_image) as source: > > with open(os.path.join(thumbnail_path, > > thumbnail_image), 'wb') as target: > > shutil.copyfileobj(source, target) > > > Returns an error on the first line: > > > ZipExtFile instance has no attribute '__exit__' > > Ouch, sorry, this new feature will appear in the not-yet-released 2.7 > version... > Try this instead: > > source = zip_file.open(zip_name + '/' + thumbnail_image) > try: > with open(os.path.join(thumbnail_path, thumbnail_image), 'wb') as target: > shutil.copyfileobj(source, target) > finally: > source.close() > > -- > Gabriel Genellina Awesome. Works perfectly, and saves me the extra step of having to move the files. Many, many thanks! Kind regards, Brandon -- http://mail.python.org/mailman/listinfo/python-list
cx_Oracle-5.0 Problem
Hello everyone, I'm Brandon Taylor, senior web developer with the University of Texas at Austin. We're using Python 2.6.1 and having a lot of difficulty getting the cx_Oracle-5.0 library to install on one of our MacBooks running OS X 10.5.6. We can get cx_Oracle to compile, but after running setup.py install and trying to import the library, we are getting an error: Traceback (most recent call last): File "", line 1, in ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/site-packages/cx_Oracle.so, 2): Symbol not found: ___divdi3 Referenced from: /Users/mas80/Library/Oracle/instantclient_10_2/ libclntsh.dylib.10.1 Expected in: flat namespace Can anyone shed some light on how we can solve this issue? It's a show stopper for us of we can not connect to Oracle from Python. Kind regards, Brandon Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: cx_Oracle-5.0 Problem
On Feb 12, 9:31 am, redbaron wrote: > > ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ > > lib/python2.6/site-packages/cx_Oracle.so, 2): Symbol not found: > > ___divdi3 > > You didn't link cx_Oracle.so all libs which it use. run "ldd -r > cx_Oracle.so" and you'll have an idea about all missing symbols. The > names of missed symbols could give you an idea what else should > cx_Oracle.so should be linked with We are getting a "command not found" error for the ldd command in OS X 10.5.6 Please advise. -- http://mail.python.org/mailman/listinfo/python-list
Problem with environment variables and cx_Oracle
Hello everyone,
Here's my setup: OS X (10.5.6 - Intel), Oracle Instant Clinet 10_2,
Python 2.6.1, Django trunk
I have my Oracle instantclient folder at: /Users/bft228/Library/Oracle/
instantclient_10_2
In my .bash_profile, I have ORACLE_HOME and LD_LIBRARY_PATH specified
as:
ORACLE_HOME="$HOME/Library/Oracle/instantclient_10_2"
export ORACLE_HOME
LD_LIBRARY_PATH=$ORACLE_HOME
export LD_LIBRARY_PATH
When I try to compile cx_Oracle-4.4.1 or 5.0.1, I get an error stating
that it cannot find an Oracle installation. setup.py will error here:
# try to determine the Oracle home
userOracleHome = os.environ.get("ORACLE_HOME")
Now, here's where things get wierd...
If I: echo $ORACLE_HOME = /Users/bft228/Library/Oracle/
instantclient_10_2
If I: python
import os
os.environ
'ORACLE_HOME': '/Users/bft228/Library/Oracle/
instantclient_10_2',
'LD_LIBRARY_PATH': '/Users/bft228/Library/Oracle/
instantclient_10_2'
If I hard-code the userOracleHome, cx_Oracle will compile, but I'm
getting errors wen attempting to connect to Oracle, like:
cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle
I've been wrestling with this for quite some time. My Oracle person
assures me that my user has appropriate permissions for the schema. My
Oracle experience is pretty limited, but this seems like it's an issue
with the environment on my Mac.
Does anyone have any ideas? I would REALLY appreciate some insight.
Kind regards,
Brandon Taylor
Senior Web Developer
The University of Texas at Austin
--
http://mail.python.org/mailman/listinfo/python-list
dictionary with tuple keys
Hi all, I am probably not thinking straight anymore about this problem. I have a dictionary with tuple keys in the format (a, b, A, B) and float values. I want to collect all the keys with identical (a, b...), disregarding whatever (... A, B) might be. Specifically, I want to sum the float values once I've collected these keys. I am staring at my screen, pondering ugly things, and I just know I must be missing a Pythonic solution. Any suggestions? Thanks for any help, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary with tuple keys
So grateful! Thanks to all. The breadth of Python continues to amaze
me, as does your generosity.
("Relative clarity like relative beauty is in the eye of the
beholder,
and few parents have ugly children"... fantastic!)
Brandon
--
http://mail.python.org/mailman/listinfo/python-list
Problem embedding Python.
I am going to try to embed python in an application, but in simple
testing, I could not get it to work. The following code seems like it
should work, but it crashes, and I have tried several things. What
could I be doing wrong?
#include
int main(int argc, char* argv[])
{
FILE* fp = fopen("test.py","r");
Py_Initialize();
PyRun_SimpleFile(fp,"test.py");
Py_Finalize();
return 0;
}
--
http://mail.python.org/mailman/listinfo/python-list
Re: Problem embedding Python.
On Oct 27, 2:47 am, "Gabriel Genellina"
wrote:
>
> Crashes, how? Try running inside a debugger to see where it crashes, or at
> least put a few printf.
> You didn't test for the fopen result; are you sure "test.py" exists in the
> current directory at the time you run it?
>
> --
> Gabriel Genellina
Ok, so I assumed that the file, if supplied without a path, would use
current working directory, which was evidently a false assumption. I
put in an if statement to check to see if the pointer was null which
it was. So I fully qualified the path in the test file. Now it
throws an unhandled exception when it goes to execute the line with
PyRun_SimpleFile. The following code yields the errors after it.
#include
int main(int argc, char* argv[])
{
FILE* fp = fopen("c:\\Patches\\Test\\Debug\\test.py","w");
if(fp == NULL)
printf("error");
Py_Initialize();
PyRun_SimpleFile(fp,"test.py");
Py_Finalize();
return 0;
}
"First-chance exception at 0x77d2dbba in Test.exe: 0xC005: Access
violation writing location 0x0014.
Unhandled exception at 0x77d2dbba in Test.exe: 0xC005: Access
violation writing location 0x0014.
First-chance exception at 0x77d2dbba in Test.exe: 0xC005: Access
violation writing location 0x0014.
Unhandled exception at 0x77d2dbba in Test.exe: 0xC005: Access
violation writing location 0x0014."
In the debug output.
This is the call stack (the first line is where execution halted).
Test.exe!main(int argc=1, char** argv=0x006d1b88) Line 9 + 0x15 bytes
Test.exe!__tmainCRTStartup() Line 586 + 0x19 bytes
Test.exe!mainCRTStartup() Line 403
(There is more after this, but it goes back to system calls and
execution is halted here so I thought this was relevant).
--
http://mail.python.org/mailman/listinfo/python-list
