Re: PySerial could not open port COM4: [Error 5] Access is denied - please help
Adam wrote: "John Nagle" wrote in message news:jse604$1cq$1...@dont-email.me... On 6/26/2012 9:12 PM, Adam wrote: Host OS:Ubuntu 10.04 LTS Guest OS:Windows XP Pro SP3 I am able to open port COM4 with Terminal emulator. So, what can cause PySerial to generate the following error ... C:\Wattcher>python wattcher.py Traceback (most recent call last): File "wattcher.py", line 56, in ser.open() File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 56, in open raise SerialException("could not open port %s: %s" % (self.portstr, ctypes.WinError())) serial.serialutil.SerialException: could not open port COM4: [Error 5] Access is denied. Are you trying to access serial ports from a virtual machine? Which virtual machine environment? Xen? VMware? QEmu? VirtualBox? I wouldn't expect that to work in most of those. What is "COM4", anyway? Few machines today actually have four serial ports. Is some device emulating a serial port? John Nagle Thanks, and yes, I am using VirtualBox. My laptop does not have a serial port so I use a USB-to-serial converter, which is assigned COM4. Doesn't VirtualBox allow "remapping" serial ports ? I thought you could have COM 4 in the host OS, and make it COM 1 or COM 2 in the guest. Something like that. http://virtuatopia.com/images/6/60/Virtualbox_serial_port_settings.jpg Also, Windows (as a host), is notorious for stealing control of COM ports. Even Windows software, when you run it, would report "COM 4 is busy". Then, you have to track down *why* it's busy. Is it that FAX software you installed ? The GPS software that talks to your GPS serial interface ? In theory, the "Handle" program is supposed to identify what is keeping a COM port busy, but I don't get the desired results from it very often. You need to know the naming convention for virtual COM ports (COM4 via USB to serial, is more virtual than physical). That's what makes it harder to track down. These are some names for COM ports, in Windows. The last two entries, are my USB to serial adapters. VCP1 functions as COM3. VCP0 functions as COM4. The VCP part is what would be listed in "Handle" from Sysinternals. The \device\serial format, is more likely to be used with true "native" motherboard serial ports. \device\serial ups.exe pid: 1072 NT AUTHORITY\SYSTEM 98: File (---) \Device\VCP0 hypertrm.exe pid: 3404 ComputerName\UserID (claims to use COM3) E0: File (---) \Device\VCP1 You can download "Handle" and play with it here. http://technet.microsoft.com/en-us/sysinternals/bb896655 Note that, in my Handle results, at the time I was running the Windows provided ups.exe to talk to my external UPS (uninterruptible power supply). So that's what that reference is. The "hypertrm" one, is me using the built-in Windows terminal software, to talk to COM3, to keep the port artificially busy for the purposes of testing. If things were working well in your case, you *might* see something of this form. If not, you'd instead see the name of the process that has "stolen" the com port. virtualbox.exe pid: 1234 ComputerName\UserID E0: File (---) \Device\VCP0 HTH, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: PySerial could not open port COM4: [Error 5] Access is denied - please help
Adam wrote: "Paul" wrote in message news:jseu9c$sp3$1...@dont-email.me... Adam wrote: "John Nagle" wrote in message news:jse604$1cq$1...@dont-email.me... On 6/26/2012 9:12 PM, Adam wrote: Host OS:Ubuntu 10.04 LTS Guest OS:Windows XP Pro SP3 I am able to open port COM4 with Terminal emulator. So, what can cause PySerial to generate the following error ... C:\Wattcher>python wattcher.py Traceback (most recent call last): File "wattcher.py", line 56, in ser.open() File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 56, in open raise SerialException("could not open port %s: %s" % (self.portstr, ctypes.WinError())) serial.serialutil.SerialException: could not open port COM4: [Error 5] Access is denied. Are you trying to access serial ports from a virtual machine? Which virtual machine environment? Xen? VMware? QEmu? VirtualBox? I wouldn't expect that to work in most of those. What is "COM4", anyway? Few machines today actually have four serial ports. Is some device emulating a serial port? John Nagle Thanks, and yes, I am using VirtualBox. My laptop does not have a serial port so I use a USB-to-serial converter, which is assigned COM4. Doesn't VirtualBox allow "remapping" serial ports ? I thought you could have COM 4 in the host OS, and make it COM 1 or COM 2 in the guest. Something like that. http://virtuatopia.com/images/6/60/Virtualbox_serial_port_settings.jpg Also, Windows (as a host), is notorious for stealing control of COM ports. Even Windows software, when you run it, would report "COM 4 is busy". Then, you have to track down *why* it's busy. Is it that FAX software you installed ? The GPS software that talks to your GPS serial interface ? In theory, the "Handle" program is supposed to identify what is keeping a COM port busy, but I don't get the desired results from it very often. You need to know the naming convention for virtual COM ports (COM4 via USB to serial, is more virtual than physical). That's what makes it harder to track down. These are some names for COM ports, in Windows. The last two entries, are my USB to serial adapters. VCP1 functions as COM3. VCP0 functions as COM4. The VCP part is what would be listed in "Handle" from Sysinternals. The \device\serial format, is more likely to be used with true "native" motherboard serial ports. \device\serial ups.exe pid: 1072 NT AUTHORITY\SYSTEM 98: File (---) \Device\VCP0 hypertrm.exe pid: 3404 ComputerName\UserID (claims to use COM3) E0: File (---) \Device\VCP1 You can download "Handle" and play with it here. http://technet.microsoft.com/en-us/sysinternals/bb896655 Note that, in my Handle results, at the time I was running the Windows provided ups.exe to talk to my external UPS (uninterruptible power supply). So that's what that reference is. The "hypertrm" one, is me using the built-in Windows terminal software, to talk to COM3, to keep the port artificially busy for the purposes of testing. If things were working well in your case, you *might* see something of this form. If not, you'd instead see the name of the process that has "stolen" the com port. virtualbox.exe pid: 1234 ComputerName\UserID E0: File (---) \Device\VCP0 HTH, Paul Thanks (Guru Paul), I've been using the USB-to-serial converter successfully without enabling/remapping via VBox Settings=>Serial Ports (which are both "not" enabled). I can see the serial port COM4 under Device Manager though. So, maybe enabling is necessary when the host has "native" serial ports, which my laptop does not have. From the output generated by Handle.exe, here's the section for TeraTerm ... -- ttermpro.exe pid: 596 VBOX_WINXPPRO\adam(claims to use COM4) C: File (RW-) D:\downloads\Tera Term Pro\ttpro313 2C: Section \BaseNamedObjects\ttset_memfilemap 44: File (RW-) C:\WINDOWS.0\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.6028_x-ww_61e65202 54: File (RW-) C:\WINDOWS.0\WinSxS\x86_Microsoft.VC80.CRT_1fc8b3b9a1e18e3b_8.0.50727.6195_x-ww_44262b86 70: Section \BaseNamedObjects\_ISWINTERNAL_EPT32_SHEX_K32_0_1c9aa25ea688500_7c80_S-1-5-21-1801674531-1078145449-1957994488-1004 78: File (RWD) C:\DOCUME~1\adam\LOCALS~1\Temp\IswTmp\Logs\ISWSHEX.swl AC: Section \BaseNamedObjects\_ISWINTERNAL_EPT32_SHEX_A32_0_1c98aa70f70ec00_77dd_S-1-5-21-1801674531-1078145449-1957994488-1004 100: Section \BaseNamedObjects\CiceroSharedMemDefaultS-1-5-21-1801674531-1078145449-1957994488-1004 108: File (RW-) D:\downloads\Tera Term Pro\ttpro313\httplog.log 120: Section \BaseNamedObjects\CTF.TimListCache.FMPDefaultS-1-5-21-
Re: PySerial could not open port COM4: [Error 5] Access is denied - please help
Adam wrote: This is a tough one. Try handle -a > allhand.txt Then open the allhand.txt with Notepad and look for interesting entries. *** I tested right now, and first opened a session in HyperTerminal with one of my USB to serial adapters. The second serial adapter, is connect to a UPS, looking for a shutdown message. So the second entry should be present at all times. hypertrm.exe pid: 3452 ... 120: File (---) \Device\VCP1 ups.exe pid: 1568 NT AUTHORITY\SYSTEM ... 98: File (---) \Device\VCP0 I don't have any "serial" entries on this machine. But one of my other machines, has a real COM port on the SuperI/O chip, so the entries for that would involve the word "serial" in some way. The USB ones, at least the ones I've got, say VCP. Possibly because one of the driver files sets up virtual COM ports. There is a control panel for the driver, that maps a virtual COM port, to a COM port number, like COM3 and COM4 in this case. Paul -- http://mail.python.org/mailman/listinfo/python-list
doctests/unittest problem with exception
Hello. I converted doctests into DocTestSuite() to use with unittest. And try it under Python 3. And, sure, I get errors with unmatched exceptions details (mismatched name of exception class: a.b.c.MyError instead of MyError). So, I have 2 questions: 1) how to turn on option IGNORE_EXCEPTION_DETAIL for all doctests in DocStestSuite (like 'optionflags' argument in doctest.testmod()) 2) Is a way to ignore all 'package path' of exception but not message? Something like: ---cut--- Traceback (most recent call last): ... ...MyError: 'details are not ignored!' ---cut--- see, ellipsis-prefix in MyError -- http://mail.python.org/mailman/listinfo/python-list
Re: Fonts & Tinker
class FontSpec: """Wrapper for something like 'Arial 10 bold #red' """ tkf = None # Tk Font spec = "" # specification tkspec = "" # specification for Tk family = None size = 0 color = "black" weight = "normal" slant = "roman" underline = 0 overstrike = 0 linespace = 0 descent = 0 ascent = 0 def __init__(self, spec=None): """spec: familty with capital letter, color with # (#red, ##FF00FF), size - int, other are styles""" try: if not spec: return spec = spec.split() family = [s for s in spec if s.istitle()] if family: self.family = family[0] spec.remove(self.family) color = [s for s in spec if s.startswith('#')] if color: self.color = color[0] spec.remove(self.color) self.color = self.color[1:] size = [s for s in spec if s.isdigit()] if size: self.size = size[0] spec.remove(self.size) self.size = int(self.size) if "bold" in spec: self.weight = "bold" if "italic" in spec: self.slant = "italic" if "underline" in spec: self.underline = 1 if "overstrike" in spec: self.overstrike = 1 # create tkFont for metrics self.tkf = tkFont.Font(family=self.family, size=self.size, weight=self.weight, slant=self.slant, underline=self.underline, overstrike=self.overstrike) self.ascent = self.tkf.metrics("ascent") self.descent = self.tkf.metrics("descent") self.linespace = self.tkf.metrics("linespace") # tkspec - specific. of font in Tk standard self.tkspec = [] if self.family: self.tkspec.append(self.family) if self.size: self.tkspec.append(str(self.size)) if self.weight == "bold": self.tkspec.append("bold") if self.slant == "italic": self.tkspec.append("italic") if self.underline: self.tkspec.append("underline") if self.overstrike: self.tkspec.append("overstrike") self.tkspec = " ".join(self.tkspec) except: raise ValueError("invalid font specification") def __str__(self): return self.tkspec --- only for ideas -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a graph image
On May 13, 11:19 pm, Bastian Ballmann wrote: > Hi python lovers out there, > > I am searching for a library to parse data from a graph in an image file > something likehttp://pytseries.sourceforge.net/_images/yahoo.png > Any suggestions, hints, links? > > TIA && have a nice day! :) > > Basti > > signature.asc > < 1KViewDownload Hi, If you are trying to digitize data from the graph, you could try Dagra: http://www.BlueLeafSoftware.com/Products/Dagra/ There is a Python library for reading the files it produces. hth paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python homework
from random import randint rolls = [randint(1, 6) for x in range(50)] print("Average: %s" % (sum(rolls) / len(rolls))) print("Most Common: %s" % max(rolls, key=rolls.count)) -- https://mail.python.org/mailman/listinfo/python-list
random.choices() Suggest that the code confirm that cum_weights sequence is in ascending order
Hi, I just learned how to use random.choices(). I initially misunderstood the documentation for cum_weights as meaning that a cumulative sequence would be *constructed from* the sequence which I supplied. Consequently, I specified 'cum_weights' with a sequence which wasn't in ascending order. I got back k results but I determined that they weren't correct (eg, certain population values were never returned). Since the non-ascending sequence, which I had supplied, could not possibly be valid input, why isn't this checked (and an error returned)? Returning incorrect results (which could be hard to spot as being incorrect) is much more dangerous. Also, checking that the list is in ascending order need only be done once, and seems like it would be inexpensive. Thanks, Paul -- https://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 176, Issue 16
Hello all, Thanks for the thoughtful (and non-snarky) replies. First, a suggestion for a documentation change: To this paragraph: *If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence. It is a TypeError <https://docs.python.org/3/library/exceptions.html#TypeError> to specify both weights and cum_weights.* Add this sentence: "A cum_weights sequence, if supplied, must be in strictly-ascending order, else incorrect results will be (silently) returned." Secondly, about the cost of verifying the sequence: 1) I understand the added cost of verifying the sequence. However, this appears to be a one-time cost. E.G., if I submit this, random.choices(lm,cum_weights=[25,26,36,46,136],k=400 then the code will do an O(n log n) operation 400 times. If verification was added, then the the code would do an O(n log n) operation 400 times, plus an O(n) operation done *one* time. So, I'm not sure that this would be a significant efficiency hit (except in rare cases). 2) Paul Moore wrote: > So the people who *really* need cum_weights are those > who have the cumulative weights already, and cannot > afford an O(n)precalculation step. I agree that with the "already have the cum_weights" argument. Based on my point #1, I'm not convinced about the "can't afford" argument. 3) A minor point. The documentation also says: "so supplying the cumulative weights saves work." However, this is work done (once, as noted above) by a computer rather than work done (even if aided by a a computer) by a human, so I'd vote for having the computer do it. :) To conclude, I would still lean slightly toward having the code enforce the 'strictly-ascending sequence' requirement. However, given that a) improving the documentation is much more doable and that, b) in some cases, the addition of an order O(n) step might be significant, I'd be more than happy if the documentation could be improved (as suggested). thanks Paul Czyzewki PS. I see the issue which steven.daprano opened. Thanks, Steven. However, I'm not sure what's appropriate in terms of updating that issue, or even if I have permission to update it, so I'd appreciate if someone would add this response to the issue. Thanks. > From: Paul Moore > To: "Steven D'Aprano" > Cc: Python > Bcc: > Date: Mon, 14 May 2018 14:35:34 +0100 > Subject: Re: random.choices() Suggest that the code confirm that > cum_weights sequence is in ascending order > On 14 May 2018 at 14:07, Steven D'Aprano > wrote: > > On Mon, 14 May 2018 12:59:28 +0100, Paul Moore wrote: > > > >> The problem is that supplying cum_weights allows the code to run in > >> O(log n) by using bisection. This is significantly faster on large > >> populations. Adding a test that the cumulative weights are nondecreasing > >> would add an O(n) step to the code. > >> > >> So while I understand the OP's problem, I don't think it's soluble > >> without making the cum_weights argument useless in practice. > > > > How does O(N) make it "useless"? There are lots of O(N) algorithms, even > > O(N**2) and O(2**N) which are nevertheless still useful. > > Well, I've never seen an actual use case for this argument (I can't > think of a case where I'd even have cumulative weights rather than > weights, and obviously calculating the cumulative weights from the > actual weights is what we're trying to avoid). And if you have > cum_weights and O(n) is fine, then calculating weights from > cum_weights is acceptable (although pointless, as it simply duplicates > work). So the people who *really* need cum_weights are those who have > the cumulative weights already, and cannot afford an O(n) > precalculation step. > > But yes, clearly in itself an O(n) algorithm isn't useless. And > agreed, in most cases whether random.choices() is O(n) or O(log n) is > irrelevant in practice. > > Paul > -- https://mail.python.org/mailman/listinfo/python-list
Re: random.choices() Suggest that the code confirm that cum_weights sequence is in ascending order
forgot to edit the subject. Sorry. paul c. On Mon, May 14, 2018 at 12:02 PM, Paul wrote: > Hello all, >Thanks for the thoughtful (and non-snarky) replies. > > First, a suggestion for a documentation change: > > To this paragraph: > > *If neither weights nor cum_weights are specified, selections are made > with equal probability. If a weights sequence is supplied, it must be the > same length as the population sequence. It is a TypeError > <https://docs.python.org/3/library/exceptions.html#TypeError> to specify > both weights and cum_weights.* > Add this sentence: > > "A cum_weights sequence, if supplied, must be in strictly-ascending order, > else incorrect results will be (silently) returned." > > Secondly, about the cost of verifying the sequence: > > 1) I understand the added cost of verifying the sequence. However, this > appears to be a one-time cost. E.G., if I submit this, > > random.choices(lm,cum_weights=[25,26,36,46,136],k=400 > > then the code will do an O(n log n) operation 400 times. > > If verification was added, then the the code would do an O(n log n) > operation 400 times, plus an O(n) operation done *one* time. So, I'm not > sure that this would be a significant efficiency hit (except in rare cases). > > 2) Paul Moore wrote: > > > So the people who *really* need cum_weights are those > > > who have the cumulative weights already, and cannot > > > afford an O(n)precalculation step. > > > I agree that with the "already have the cum_weights" argument. Based on > my point #1, I'm not convinced about the "can't afford" argument. > > 3) A minor point. The documentation also says: "so supplying the > cumulative weights saves work." However, this is work done (once, as noted > above) by a computer rather than work done (even if aided by a a computer) > by a human, so I'd vote for having the computer do it. :) > > > To conclude, I would still lean slightly toward having the code enforce > the 'strictly-ascending sequence' requirement. However, given that a) > improving the documentation is much more doable and that, b) in some cases, > the addition of an order O(n) step might be significant, I'd be more than > happy if the documentation could be improved (as suggested). > > thanks > Paul Czyzewki > > PS. I see the issue which steven.daprano opened. Thanks, Steven. > However, I'm not sure what's appropriate in terms of updating that issue, > or even if I have permission to update it, so I'd appreciate if someone > would add this response to the issue. Thanks. > > > >> From: Paul Moore >> To: "Steven D'Aprano" >> Cc: Python >> Bcc: >> Date: Mon, 14 May 2018 14:35:34 +0100 >> Subject: Re: random.choices() Suggest that the code confirm that >> cum_weights sequence is in ascending order >> On 14 May 2018 at 14:07, Steven D'Aprano >> wrote: >> > On Mon, 14 May 2018 12:59:28 +0100, Paul Moore wrote: >> > >> >> The problem is that supplying cum_weights allows the code to run in >> >> O(log n) by using bisection. This is significantly faster on large >> >> populations. Adding a test that the cumulative weights are >> nondecreasing >> >> would add an O(n) step to the code. >> >> >> >> So while I understand the OP's problem, I don't think it's soluble >> >> without making the cum_weights argument useless in practice. >> > >> > How does O(N) make it "useless"? There are lots of O(N) algorithms, even >> > O(N**2) and O(2**N) which are nevertheless still useful. >> >> Well, I've never seen an actual use case for this argument (I can't >> think of a case where I'd even have cumulative weights rather than >> weights, and obviously calculating the cumulative weights from the >> actual weights is what we're trying to avoid). And if you have >> cum_weights and O(n) is fine, then calculating weights from >> cum_weights is acceptable (although pointless, as it simply duplicates >> work). So the people who *really* need cum_weights are those who have >> the cumulative weights already, and cannot afford an O(n) >> precalculation step. >> >> But yes, clearly in itself an O(n) algorithm isn't useless. And >> agreed, in most cases whether random.choices() is O(n) or O(log n) is >> irrelevant in practice. >> >> Paul >> > -- https://mail.python.org/mailman/listinfo/python-list
Re: syntax oddities
Top posting saves a huge amount of useless scrolling time. Is it frowned upon on this list? On Thu, May 17, 2018, 7:26 AM Tobiah wrote: > Top posting is awesome for the reader plowing through > a thread in order. In that case the cruft at the bottom > is only for occasional reference. > > Ok, I yield! I know the bottom-posting party has congress > right now. > > On 05/17/2018 06:29 AM, Grant Edwards wrote: > > On 2018-05-17, Abdur-Rahmaan Janhangeer wrote: > > > >> just a remark that people help and discuss on more issues unrelated to > >> python > > [...] > >> On Thu, 17 May 2018, 07:45 Steven D'Aprano, < > >> steve+comp.lang.pyt...@pearwood.info> wrote: > >>> On Thu, 17 May 2018 05:25:44 +0400, Abdur-Rahmaan Janhangeer wrote: > >>> > > > > And one such popular issue is how top-posting is evil. > > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: syntax oddities
wrote: > > Is it frowned > > upon on this list? > > Trimming your replies saves even more. Yes, it is. > > ChrisA > - > kk. Thanks Paul > > -- https://mail.python.org/mailman/listinfo/python-list
Re: syntax oddities
> > > That concept is meaningful only email between two parties, where > the > quoted material is a "courtesy copy" for content the other party likely > provided a week earlier (snail mail). > > But mailing lists/newsgroups are the equivalent of a bulletin board > open to anyone walking past. Bottom posting (or better, trim and > intersperse) allows someone who has no prior knowledge of the message chain > to read it from top-down, picking up the relevant points as they go... > Rather than having to flip through a stack of pages looking for information > being referenced by the top-most sheet of paper. > > > -- > Wulfraed Dennis Lee Bieber I've been using email for thirty years, including thousands of group emails at many tech companies, and no one has ever suggested, let alone insisted on, bottom posting. If someone's late to a thread they can read from it the bottom up. But, for everyone who has been keeping up, not having to scroll is a big advantage. I'm not suggesting that the convention on this list be changed, but it's by no means the only option which makes sense. Paul C. > > -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to remove leading zeros from a tuple like string
> > > This works for me: mytuplestring.replace("0","") > > Your regex will also eliminate non-leading zeros. -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to remove leading zeros from a tuple like string
On Sun, May 20, 2018, 5:53 PM Paul wrote: > This works for me: mytuplestring.replace("0","") > >> >>> Your regex will also eliminate non-leading zeros. >> >> > If you Google > > regex tester > > you will find several useful sites where you can test regexes. Regex > errors are very common, even after you have experience with them. > -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to remove leading zeros from a tuple like string
Thomas Jollans wrote: > On 2018-05-20 23:54, Paul wrote: > > you will find several useful sites where you can test regexes. > > What's the benefit of those compared to simply trying out the regex in a > Python console? > Possibly nothing. But there are obvious benefits compared to trying to write and test such an expression in one's head, which was the situation which led me to suggest it. :) > -- https://mail.python.org/mailman/listinfo/python-list
Re: List replication operator
How would one make a multi-dimensional list now, with truly-separate sub lists? Is there just no way to do it with the replication operator? IE, would I just have to do X = [[], [], [], [], []] or perhaps write a function to insert new sub lists into a list, or...? Thanks > Paul C. > > -- https://mail.python.org/mailman/listinfo/python-list
Re: List replication operator
how often would people here have needed this new operator, if it had existed? -- https://mail.python.org/mailman/listinfo/python-list
how to read a syntax diagram
hi, I'm using the Google Sheets API (the client library rather than the RESTful interface) and I'm confused about the meaning of the syntax diagrams. This is from https://developers.google.com/resources/api-libraries/documentation/sheets/v4/python/latest/sheets_v4.spreadsheets.values.html#update efaults to ROWS. } update(spreadsheetId=*, range=*, body=*, valueInputOption=None, x__xgafv=None, responseValueRenderOption=None, includeValuesInResponse=None, responseDateTimeRenderOption=None) Sets values in a range of a spreadsheet. The caller must specify the spreadsheet ID, range, and a valueInputOption. Args: spreadsheetId: string, The ID of the spreadsheet to update. (required) range: string, The A1 notation of the values to update. (required) body: object, The request body. (required) The object takes the form of: { # Data within a range of the spreadsheet. "range": "A String", # The range the values cover, in A1 notation. # For output, this range indicates the entire requested range, # even though the values will exclude trailing rows and columns. # When appending values, this field represents the range to search for a # table, after which values will be appended. "values": [ # The data that was read or to be written. This is an array of arrays, # the outer array representing all the data and each inner array # representing a major dimension. Each item in the inner array # corresponds with one cell. # # For output, empty trailing rows and columns will not be included. # # For input, supported value types are: bool, string, and double. # Null values will be skipped. # To set a cell to an empty value, set the string value to an empty string. [ "", ], ], "majorDimension": "A String", # The major dimension of the values. # # For output, if the spreadsheet data is: `A1=1,B1=2,A2=3,B2=4`, # then requesting `range=A1:B2,majorDimension=ROWS` will return # `[[1,2],[3,4]]`, # whereas requesting `range=A1:B2,majorDimension=COLUMNS` will return # `[[1,3],[2,4]]`. # # For input, with `range=A1:B2,majorDimension=ROWS` then `[[1,2],[3,4]]` # will set `A1=1,B1=2,A2=3,B2=4`. With `range=A1:B2,majorDimension=COLUMNS` # then `[[1,2],[3,4]]` will set `A1=1,B1=3,A2=2,B2=4`. # # When writing, if this field is not set, it defaults to ROWS. } valueInputOption: string, How the input data should be interpreted// I CUT IT OFF, HERE My specific questions are: 1) is this standard (python?) syntax notation? I haven't found a key to this form of documentation. 1) What does '=*' mean? 2) What does '=None' mean?[my guess is that this means "no default value"]. 3) Note that it says that range is required. Through trial, I see that *one* of the 'range' specifications is required. I.E., I can specify 'range' outside body, or 'range' as part of body, or both, but I must have 'range' someplace. This is a bit confusing to me ( as opposed to my usual understanding of "required"). Also, what does range mean, in these two different spots, and what does it mean if two different values of range are specified? thanks Paul Czyzewski -- https://mail.python.org/mailman/listinfo/python-list
Re: how to read a syntax diagram
oops, please ignore the bit before "update(spreadsheetId=*, range=*, ..." On Sun, May 27, 2018 at 9:17 PM, Paul wrote: > hi, >I'm using the Google Sheets API (the client library rather than the > RESTful interface) and I'm confused about the meaning of the syntax > diagrams. This is from > https://developers.google.com/resources/api-libraries/ > documentation/sheets/v4/python/latest/sheets_v4.spreadsheets.values.html# > update > > efaults to ROWS. > } > > update(spreadsheetId=*, range=*, body=*, valueInputOption=None, > x__xgafv=None, responseValueRenderOption=None, > includeValuesInResponse=None, responseDateTimeRenderOption=None) > > Sets values in a range of a spreadsheet. > The caller must specify the spreadsheet ID, range, and > a valueInputOption. > > Args: > spreadsheetId: string, The ID of the spreadsheet to update. (required) > range: string, The A1 notation of the values to update. (required) > body: object, The request body. (required) > The object takes the form of: > > { # Data within a range of the spreadsheet. > "range": "A String", # The range the values cover, in A1 notation. > # For output, this range indicates the entire requested range, > # even though the values will exclude trailing rows and columns. > # When appending values, this field represents the range to search for a > # table, after which values will be appended. > "values": [ # The data that was read or to be written. This is an array of > arrays, > # the outer array representing all the data and each inner array > # representing a major dimension. Each item in the inner array > # corresponds with one cell. > # > # For output, empty trailing rows and columns will not be included. > # > # For input, supported value types are: bool, string, and double. > # Null values will be skipped. > # To set a cell to an empty value, set the string value to an empty > string. > [ > "", > ], > ], > "majorDimension": "A String", # The major dimension of the values. > # > # For output, if the spreadsheet data is: `A1=1,B1=2,A2=3,B2=4`, > # then requesting `range=A1:B2,majorDimension=ROWS` will return > # `[[1,2],[3,4]]`, > # whereas requesting `range=A1:B2,majorDimension=COLUMNS` will return > # `[[1,3],[2,4]]`. > # > # For input, with `range=A1:B2,majorDimension=ROWS` then `[[1,2],[3,4]]` > # will set `A1=1,B1=2,A2=3,B2=4`. With > `range=A1:B2,majorDimension=COLUMNS` > # then `[[1,2],[3,4]]` will set `A1=1,B1=3,A2=2,B2=4`. > # > # When writing, if this field is not set, it defaults to ROWS. > } > > valueInputOption: string, How the input data should be interpreted// I > CUT IT OFF, HERE > > > My specific questions are: >1) is this standard (python?) syntax notation? I haven't found a key > to this form of documentation. >1) What does '=*' mean? >2) What does '=None' mean?[my guess is that this means "no default > value"]. >3) Note that it says that range is required. Through trial, I see > that *one* of the 'range' specifications is required. I.E., I can specify > 'range' outside body, or 'range' as part of body, or both, but I must have > 'range' someplace. This is a bit confusing to me ( as opposed to my usual > understanding of "required"). Also, what does range mean, in these two > different spots, and what does it mean if two different values of range are > specified? > > thanks > Paul Czyzewski > -- https://mail.python.org/mailman/listinfo/python-list
Re: Pink Floyd: is there anybody in here?
I see it on the mailing list. Paul C On Wed, May 30, 2018, 10:07 AM Rob Gaddi wrote: > On 05/30/2018 09:34 AM, Paul Rubin wrote: > > I think Usenet posts are no longer getting forwarded to the mailing > > list, but now I wonder if this is getting out at all, even to usenet. > > > > Does anyone see it? > > > > Can't speak for the mailing list, but this came out to Usenet just fine. > > -- > Rob Gaddi, Highland Technology -- www.highlandtechnology.com > Email address domain is currently out of order. See above to fix. > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Sorting and spaces.
In the US, at least, spaces should sort before letters. MRAB brought up an important point. It depends on your purpose, of course, but having all the capitalized-beginning items appear separately from all of the lower-cased-beginning items can be very annoying to a user. -- https://mail.python.org/mailman/listinfo/python-list
Attachments? Re: Indented multi-line strings (was: "Data blocks" syntax specification draft)
I have heard that attachments to messages are not allowed on this list, which makes sense. However I notice that messages from Peter do have an attachment, i.e., a signature.asc file. I'm just curious; why and how do those particular attachments get through? And should they get through, I guess? E.G., what if I attach a malicious file labeled as .asc? [Peter, I am not suggesting anything about you! ;). ] Paul C. -- https://mail.python.org/mailman/listinfo/python-list
Re: Attachments? Re: Indented multi-line strings (was: "Data blocks" syntax specification draft)
I gave it a different subject line. On Fri, Jun 1, 2018 at 2:45 AM, Abdur-Rahmaan Janhangeer < arj.pyt...@gmail.com> wrote: > as this sig file is a common occurance, attaching the topic to the data > blocks thread is not really necessary > > Abdur-Rahmaan Janhangeer > https://github.com/Abdur-rahmaanJ > > On Fri, 1 Jun 2018, 01:49 Paul, wrote: > >> I have heard that attachments to messages are not allowed on this list, >> which makes sense. However I notice that messages from Peter do have an >> attachment, i.e., a signature.asc file. >> >> I'm just curious; why and how do those particular attachments get through? >> And should they get through, I guess? E.G., what if I attach a malicious >> file labeled as .asc? >> >> [Peter, I am not suggesting anything about you! ;). ] >> >> Paul C. >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > -- https://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
Tim Tyler wrote: > Javascript can be turned off in *mail readers* - by their manufacturers. Yes, mail readers, browsers, combined mail reading and Web browsing "suites", or whatever combination of functions you care to consider. In any case, in the not-exactly-unknown mail reader I use, I can't seem to find a setting that will turn JavaScript on. Meanwhile, HTML mail is flagged and presented as plain text with a prominent warning about viewing the message as HTML - an acceptable tradeoff which only slightly delays the viewing of the very few legitimate messages I get sent in that format. Of course, the most excitable manufacturers of mail readers with respect to enabling a "rich experience" are those pitching "enterprise functionality", although a full treatment of their mistakes (amplifying my previous rant) would take this discussion even further away from the tenuous connection it has with Python, related discussions on type safety, private/protected/public, using Python in Mozilla, and the disappearance of the Bastion module notwithstanding. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP on path module for standard library
Michael Hoffman wrote: > Reinhold Birkenfeld wrote: > > Probably as Terry said: a path is both a list and a string. [...] > One way to divide this is solely based on path separators: > > ['c:', 'windows', 'system32:altstream', 'test.dir', > 'myfile.txt.zip:altstream'] I would argue that any proposed solution has to work with VMS pathnames. ;-) > The current stdlib solution, os.path.splitext(os.path.splitext(filename) > [0])[0] is extremely clunky, and I have long desired something better. > (OK, using filename.split(os.extsep) works a little better, but you get > the idea.) And also with unusual (eg. RISC OS) filename extensions. To do any justice to the existing solutions, any PEP should review at least the following projects: * The path module (of course): http://www.jorendorff.com/articles/python/path/ * The py.path module (or at least the ideas for it): http://codespeak.net/py/current/doc/future.html * itools.uri http://www.ikaaro.org/itools * Results from the "Object-Oriented File System Virtualisation" project in the "Summer of Code" programme: http://wiki.python.org/moin/SummerOfCode And I hope that the latter project is reviewing some of the other work, if only to avoid the "framework proliferation" that people keep complaining about. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Chronological Processing of Files
untested, ugly, but something like this would sort all the files in the directory on os.path.getctime (not using os.walk() though). I'm sure there is probably better ways to do it :) filelist = [] def walkdir(currdir): for files in os.listdir(currdir): path = os.path.join(currdir, files) if not os.path.isdir(path): filelist.append([os.path.getctime(path), path]) else: walkdir(path) walkdir(r'c:\somedirectory') filelist.sort() for item in filelist: dosomething(item[1]) dosomething is whatever function to process the files -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling python scripts from C# programs
Another option is to implement the needed python code in COM server and call that from C#. A simple example of python COM server can be seen about halfway down the page here http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html -- http://mail.python.org/mailman/listinfo/python-list
Daemon module
Hi, I find myself writing quite a few daemons in Python and have finally gotten round to abstracting out a lot of the common code. You can find my first attempt at a generic daemon module at: http://www.westpoint.ltd.uk/dist/daemon.py It's not perfect, but it does work reliably for my purposes. It would be great if people can use this as a starting point to develop further features. I'd also be very interested in feedback about whether the code does the right sequence of calls to start a daemon. Best wishes, Paul -- http://mail.python.org/mailman/listinfo/python-list
Sorting in huge files
Hi all I have a sorting problem, but my experience with Python is rather limited (3 days), so I am running this by the list first. I have a large database of 15GB, consisting of 10^8 entries of approximately 100 bytes each. I devised a relatively simple key map on my database, and I would like to order the database with respect to the key. I expect a few repeats for most of the keys, and that s actually part of what I want to figure out in the end. (Said loosely, I want to group all the data entries having "similar" keys. For this I need to sort the keys first (data entries having _same_ key), and then figure out which keys are "similar"). A few thoughts on this: - Space is not going to be an issue. I have a Tb available. - The Python sort() on list should be good enough, if I can load the whole database into a list/dict - each data entry is relatively small, so I shouldn't use pointers - Keys could be strings, integers with the usual order, whatever is handy, it doesn't matter to me. The choice will probably have to do with what sort() prefers. - Also I will be happy with any key space size. So I guess 100*size of the database will do. Any comments? How long should I hope this sort will take? It will sound weird, but I actually have 12 different key maps and I want to sort this with respect to each map, so I will have to sort 12 times. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting in huge files
I really do need to sort. It is complicated and I haven't said why, but it will help in finding similar keys later on. Sorry I can't be more precise, this has to do with my research. Your two other suggestions with itertools and operator are more useful, but I was mostly wondering about performance issue. Is this reasonnable to do on 10^8 elements with repeats in the keys? I guess I should just try and see for myself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting in huge files
I really do need to sort. It is complicated and I haven't said why, but it will help in finding similar keys later on. Sorry I can't be more precise, this has to do with my research. Your two other suggestions with itertools and operator are more useful, but I was mostly wondering about performance issue. Is this reasonnable to do on 10^8 elements with repeats in the keys? I guess I should just try and see for myself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting in huge files
The reason I am not telling you much about the data is not because I am afraid anyone would steal my ideas, or because I have a non-disclosure agreement or that I don't want to end up pumping gas. It is just that it is pretty freaking damn hard to even explain what is going on. Probably a bit harder than your usual database. If you really want to know, my entries are elliptic curves and my hashing function is an attempt at mapping them to their Serre resdual representation modulo a given prime p. Now, for you to tell me something relevant about the data that I don't already know from some big-shot conjecture/theorem would probably require that you read a few grad school books on number theory. Happy? -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting in huge files
Thanks! I definitely didn't want to go into any elaborate programming for this, and the Unix sort is perfect for this. It sorted a tenth of my data in about 8 min, which is entirely satisfactory to me (assuming it will take ~ 20 times more to do the whole thing). Your answer greatly helped! Paul -- http://mail.python.org/mailman/listinfo/python-list
isbntools. (python script to download book informaiton)
Hello, I am trying to make up a catalogue of my books. I found tools on isbntools.com in python. YAY i thought. Something happens! But I cant seem to get the part to download the books information from amazon.com working correctly. It connects, but I think the regular expressions used in the code aren't upto date(amazon has changed the form or html code). I was wondering has anyone hacked around with it to get it working. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Logic problem: need better logic for desired thruth table.
Skybuck Flying wrote: Hello, I was just coding and ran into a little logic problem which is as follows: There are two booleans/variables which can be either false or true. The desired thrutle table is: A = input B = input C = output A B C: --- F F T F T F T F T T T T Surpisingly enough I don't think there is a casual/common operator for this thruth table. AND does not apply. OR does not apply. XOR does not apply. So I would need some combined operators to give the desired result. I tried logic below... but funny enough it failed, now I feel like a noob lol and share this funny little fail logic with you. Can you improve/fix the logic ? This is python code, but this^ logic/thruth table problem basically applies to any programming language: # loop has to run if: # while DesiredResult==True: # Desired truth table for BotWaitForCooldown and CooldownDetected # BotWaitForCooldown: CooldownDetected: Desired Result: # False FalseTrue # False True False # True FalseTrue # True True True # desired/suiting logic: # (BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected)) def TestLogic( BotWaitForCooldown, CooldownDetected ): return BotWaitForCooldown or ((not BotWaitForCooldown) and CooldownDetected) # this logic is flawed, please improve logic. if TestLogic( False, False ) == True: print "test 1 ok" else: print "test 1 failed" if TestLogic( False, True ) == False: print "test 2 ok" else: print "test 2 failed" if TestLogic( True, False ) == True: print "test 3 ok" else: print "test 3 failed" if TestLogic( True, True ) == True: print "test 4 ok" else: print "test 4 failed" Bye, Skybuck. If you ever have a really complicated truth table, you can use Quine McCluskey minimization. At work, I had no tool for minimizing boolean equations, so I got some code from another engineer, code that ran on a mainframe computer. And I converted the code to run on a personal computer. The computers were so slow back then, it might take ten to fifteen minutes to minimize a ten variable truth table. On the mainframe you could have a 2MB array for storage, whereas on my personal computer at the time, the memory was segmented and required some tricks to get enough. http://en.wikipedia.org/wiki/Quine%E2%80%93McCluskey_algorithm If it isn't a scam, the source code should be reasonably short. The program I was using, might have been on the order of 120 lines of source. This example is a bit longer, and the couple programs I've been looking at the source, I don't recognize what they're doing. http://sourceforge.net/projects/mini-qmc/files/?source=navbar Your problem isn't large enough to need this sort of thing, but I thought I'd throw it in as a topic of general interest. If it's one thing I've learned over the years, hand-optimization of boolean equations frequently leads to errors. And it's when you start engaging your brain, and saying stuff like "I know the answer", instead of sticking with your boolean algebra, that errors creep in. If you need a test case for your QM code, enter an "XOR tree", as an XOR tree is irreducible and should cough out the same info, as you entered in the first place. That was one of my test cases, when porting the code maybe 30 years ago. (And no, I didn't keep a copy of the code. We didn't do stuff like that back then. I didn't even have a computer at home back then.) Paul -- https://mail.python.org/mailman/listinfo/python-list
Thread handling issue
I'm wondering what the best solution for this problem is. I've got a wxpython app, in one part a user makes some selections then opens a dialog to select where to output. At which point the app starts a thread processing their selection while they're choosing an output location, hopefully ready for when they're done. My problem is if the user doesn't select an output location and cancels the dialog to go back to the selection I want to terminate the thread to avoid the user opening and closing the output selection firing off a ton of threads. As there's no inbuilt way of killing threads I was wondering the best way to prevent this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread handling issue
Tim Golden timgolden.me.uk> writes: > > On 07/10/2011 09:29, Paul wrote: > > I'm wondering what the best solution for this problem is. > > > > I've got a wxpython app, in one part a user makes some selections then > > opens a > > dialog to select where to output. At which point the app starts a thread > > processing their selection while they're choosing an output location, hopefully > > ready for when they're done. > > > > My problem is if the user doesn't select an output location and cancels the > > dialog to go back to the selection I want to terminate the thread to avoid the > > user opening and closing the output selection firing off a ton of threads. > > > > As there's no inbuilt way of killing threads I was wondering the best way to > > prevent this? > > The most common approach is to have the thread monitor an event which is > set if, for example, the user cancels. The thread may of course have to > wait, for example, for a long-running database query to complete before > it can discover that its time has been wasted :) > > The exact mechanism will depend on how your code is structured, > what the thread is doing, and how it's passing anything back > to the main thread. > > TJG > My first thought was to use a flag but wouldn't the new thread see the cancel flag and stop as well? I could set it back but then any other threads might have been busy and not seen it while the flag was on. The thread goes through the selection and does a few quick server calls for each one building up a data file. I guess as the server calls are quite fast the thread would be able to check flags quite often unless it's getting time-outs or something. The threads don't pass anything back they're passed a reference to a data object which is constructed before the thread starts. The thread makes updates to the data object and sets a complete attribute flag in the object before finishing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread handling issue
Basically there can be quite a big job to do based on the user selection and I've pipelined it so after the user selects the output location the next job can get started so long as the first job (preparing the data) has been running for 5 or so seconds roughly. Its just a lot nicer to have this done by the time the user has selected an output folder so the main job can start instantly. Of course the user can kill the main job too and go back to the user input so I need to be able to kill the threads anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread handling issue
Tim Golden timgolden.me.uk> writes: > > On 07/10/2011 11:15, Paul wrote: > > My first thought was to use a flag but wouldn't the new thread see the cancel > > flag and stop as well? I could set it back but then any other threads might have > > been busy and not seen it while the flag was on. > > > > The thread goes through the selection and does a few quick server calls for each > > one building up a data file. I guess as the server calls are quite fast the > > thread would be able to check flags quite often unless it's getting time- outs or > > something. > > > > The threads don't pass anything back they're passed a reference to a data object > > which is constructed before the thread starts. The thread makes updates to the > > data object and sets a complete attribute flag in the object before finishing. > > Well a lot depends on how you're doing things. (ie "It Depends"). You > could generate an event for each thread so a second thread started while > the first was running down wouldn't cause confusion. It's not clear > whether the data object is common to all threads -- in which case > you need to make sure you're locking etc. -- or is a new instance > for each thread. > > I did try a couple of passes at a code-sketch, but there are too > many unknowns to do justice to it. Basically, have the thread poll > an event as it moves through. Have the UI set the event and join to > the existing thread (ie wait for it to finish) and then fire off > a new one. Or -- if the data items are independent -- fire off > the new one regardless and let the old one die when it sees its > event, assuming that the data object it's populating is disposable. > > TJG Yea currently I create a new data object for each thread. I could make it a bit smarter and if the user goes back makes a change I could re-use the old data object and modify it but currently I'm not going to worry about that. I think I'll wait for the user to actually make a change after cancelling the output selection, in case they go straight back without making changes. If they make a change I think I'll try what you suggested and send off a new thread, and send an event to the previous thread. Would this mean I'd need to use wx.lib.newevent.NewCommandEvent() to get a new event for each thread I create? and I'd have to pass the second return value from that, the event binder to the thread to bind to a clean up and exit method? -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert StringIO to string
Jonathan Bowlas schrieb: > Hi listers, > > I've written this little script to generate some html but I cannot get it to > convert to a string so I can perform a replace() on the >, < > characters that get returned. > > from StringIO import StringIO > > def generator_file(rsspath,titleintro,tickeropt): > scripter=StringIO() > scripter.write('\n') > scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath, > titleintro, tickeropt)) > scripter.write('\n') > return scripter.getvalue() > > I tried adding this: > > scripter = scripter.replace("<", "<") > scripter = scripter.replace(">", ">") I'm not sure why you are using a StringIO instance here, but the standard library has all you need: from StringIO import StringIO from xml.sax.saxutils import escape, unescape def generator_file(rsspath, titleintro, tickeropts): #unescape your strings first rsspath, titleintro, tickeropts = map(unescape, [rsspath, titleintro, tickeropts]) scripter=StringIO() scripter.write('\n') scripter.write('new rss_ticker(%s, %s, %s)\n' % (rsspath, titleintro, tickeropt)) scripter.write('\n') return scripter.getvalue() I'm still curious what all this StringIO stuff is for ;) cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: wx.grid question (trying to use code from Grid_Example.py)
[EMAIL PROTECTED] schrieb: > To extend and revise my remarks my error is > > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\csoundgrid.py", line 8, in create_grid > win = Grid_MegaExample.MegaTable(self, data, colnames, pugins) > NameError: global name 'self' is not defined > Script terminated. This has nothing to do with wx, you just don't use "self" if you're _calling_ a method. So: def create_grid(): win = Grid_MegaExample.MegaTable(data, colnames, pugins) win.Show(True) should get you to the next error ;) cheers paul -- http://mail.python.org/mailman/listinfo/python-list
Re: correct parameter usage for "select * where id in ..."
Frank Millman schrieb: > If you want it to handle a variable number of values, you will have to > programmatically construct the sql statement with the appropriate > number of parameters. >>> vals = (1,2,3,4,5) >>> sql = "select * from table where value in ("+','.join("?"*len(vals))+")" >>> print sql 'select * from table where value in (?,?,?,?,?)' cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Draw rectangle on a Window DC
Raymond schrieb: > Hi: > > I want to Draw rectangle on Dc when gived a position. Can you teach me? Let > me view your code? Well, you haven't given us much background but I'd suggest if your boss asks you to draw a rectangle on your corporate domain controller and the position allows this, you better do so or you'll get fired. Use chalk so you can wipe it off the case if your boss changes his/her mind. Disclaimer: I haven't tested this and the DC might get unstable or crash... scnr Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 3107 and stronger typing (note: probably a newbie question)
Bruno Desthuilliers schrieb: > Stephen R Laniel a écrit : >> On Wed, Jun 20, 2007 at 09:41:09PM +0100, Michael Hoffman wrote: >>> If you asked Java programmers why you couldn't turn *off* Java's static >>> type checking if you wanted to, you'd probably get a similar response. >> Perhaps it would help for me to explain what I'd like. >> >> Under both Perl and Python, I've found myself >> having/wanting to write things like so: >> >> def my_func( int_arg, str_arg ): >> try: >> int_arg = int( int_arg ) >> str_arg = str( str_arg ) >> except ValueError: >> sys.stderr.write( "Args are not of the right type\n" ) >> sys.exit(1) >> > > Just a question : what will happen if you get rid of the try/except > block ?-) > The error will remain unnoticed and the argument might survive another few function calls but eventually fails deep down somewhere with: TypeError: cannot concatenate 'str' and 'list' objects then you have to examine the traceback and hope the real error is visible somewhere (an argument not conforming to the specification of the function prototype, or the lack thereof). cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems Drawing Over Network
Andrew schrieb: > Hello Everyone [snipped stuff] Sorry not being helpful, but I suggest you post a minimal sample of your code demonstrating your program. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: itertools.groupby
Steve Howell schrieb: > --- Steve Howell <[EMAIL PROTECTED]> wrote: > >> --- 7stud <[EMAIL PROTECTED]> wrote: >> >>> Bejeezus. The description of groupby in the docs >> is >>> a poster child >>> for why the docs need user comments. > > Regarding the pitfalls of groupby in general (even > assuming we had better documentation), I invite people > to view the following posting that I made on > python-ideas, entitled "SQL-like way to manipulate > Python data structures": > > http://mail.python.org/pipermail/python-ideas/2007-May/000807.html > > In the thread, I don't really make a proposal, so much > as a problem statement, but my radical idea is that > lists of dictionaries fit the relational model > perfectly, so why not allow some kind of native SQL > syntax in Python that allows you to manipulate those > data structures more naturally? LINQ? cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Why PHP is so much more popular for web-development
Carsten Haese schrieb: >> Also, PHP, and PHP frameworks, are supported everywhere. If you going >> to use a PHP MVC framework, like codeignitor, you would have a hard >> time finding a hoster that didn't support it - all you need is php4 >> and mysql. Dollar-hosting, for $10 a year, should work just fine with >> codeignitor. With codeignitor, just copy your files to whatever host, >> and that's it, you're done. >> >> By contrast, the most popular Python frameworks have sky-high system >> requirements. Take a look at the requirements and/or recomendations >> for popular Python frameworks like Django, TurboGears, or CherryPy: >> Apache 2.0, mod_python (latest version), fastcgi (at least), command >> line access, PostgreSQL. And a lot of low-cost hosters don't support >> Python at all. > > The comparison is not fair on many levels. PHP is not a framework like > Django or TG. You get a lot more stuff with Django or TG, so of course > the requirements are higher. Wait a minute, did he write "Also, PHP and PHP frameworks are supported everywhere..."? And he is right, you can drop symphony or cakePHP in your webroot and it will work, period. > > Seriously, take a closer look at CherryPy. With CherryPy, you don't even > need Apache since it provides its own web server. So how do you run this in production? There's only one port 80, you'd need e.g. mod_proxy + CherryPy on a high port as a long running process. That's just not possible in most shared hosting envs, plus you'd have to monitor cherrypy and whatnot. Don't get me wrong, I'm not defending PHP but from a deployment POV python is definitely more complex. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Fast socket write
Greg Copeland schrieb: > On Aug 21, 9:40 pm, Bikal KC <[EMAIL PROTECTED]> wrote: >> Greg Copeland wrote: >>> I'm having a brain cramp right now. I can't see to recall the name of >> Is your cramp gone now ? :P > > > I wish. If anyone can remember the name of this module I'd realy > appreciate it. http://tautology.org/software/python-modules/sendfile probably... -- http://mail.python.org/mailman/listinfo/python-list
pySerial in a daemon process
I am writing a daemon process that reads data from the serial port / dev/ttyS0. I am using pyserial & the method for setting up a daemon described in "Chris' Python Page" (http://homepage.hispeed.ch/py430/ python/) on an Ubuntu linux pc. Everything works great EXCEPT... in the daemon script, there are two lines to change the uid & gid that the script runs as: os.setegid(10) os.seteuid(1000) If I comment these out, so that the daemon runs as root, then everything works fine. I can also manually run the script that the daemon process kicks off from my own id just fine. If I put these back in and try to run the daemon, the script fails when I try to connect to the serial port, with this error: serial.serialutil.SerialException: Could not open port: [Errno 13] Permission denied: '/dev/ttyS0' In my debugging I have tried setting the uid to my own uid, and the gid to a variety of different groups that I belong to. None of them work. I could certainly run the daemon as root, but I would rather not. What really confuses me is that if I manually run the script as myself (without using the daemon script), it connects fine, but when root uses os.seteuid() to my uid, it fails. What do I need to do to get this to work? Many thanks, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: pySerial in a daemon process
On Aug 26, 5:20 pm, Bjoern Schliessmann wrote: > paul wrote: > > If I put these back in and try to run the daemon, the script fails > > when I try to connect to the serial port, with this error: > > serial.serialutil.SerialException: Could not open port: [Errno 13] > > Permission denied: '/dev/ttyS0' > > Did you check the permissions on this file? Often you have to be > member of a "dialout" group or similar to get access. > > Regards, > > Björn > > -- > BOFH excuse #172: > > pseudo-user on a pseudo-terminal THANKS! That did it, but perhaps can you explain to me why... Before I had posted this question first thing I did was to look at / dev/ttyS0, and indeed the group is dialout (gid=20), so I tried a couple of things: 1. checked my id to see if I was a member of dialout, and indeed I am. So, I edited the daemon script to use my id and set the gid to dialout (ie: os.setegid(20) & os.seteuid(1000)) and it still failed. 2. made the id I really want to use (pydaemon, uid=110) a member of dialout, and set the daemon script to use those (ie: os.setegid(20) & os.seteuid(110)) and it still failed... After reading your comment, I went and did a chgrp to set the various script file groups to dialout, and indeed it now works. What confuses me is that if the script needed that group, why doesn't the setegid or seteuid fail? Why does the script keep running okay until the connect, and fail then? Thanks! Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite3 trapping OperationalError
jim-on-linux schrieb: > pyhelp, > > I set up a table in SQLite3. > > While running other modules I want to know if a > table exists. > > SQL has a command "List Tables" but I don't think > SQLlite3 has this command. I think "list tables" is a mysqlism > > I've tried >cursor.execute("select * from debtor where key > is not null ") FROM sqlite_master SELECT name WHERE type='table'; cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Mastering Python
Paul McGuire schrieb: > What does Python have that C++ doesn't? > - The biggie: dynamic typing (sometimes called "duck typing"). > Dynamic typing is a huge simplifier for development: > . no variable declarations > . no method type signatures > . no interface definitions needed > . no templating for collections > . no method overloading by differing argument type signatures > ("Imagine there's no data types - I wonder if you can..."). What? No > static type-checking at compile time? Nope, not really. If your > method expects an object of type X, use it like an X. If it's not an > X, you may be surprised how often this is not a problem. But sometimes it is ;) Typical example: input and CGI/whatever. If one element is checked you'll get a string, if you select multiple (i.e. checkboxes) you'll get a list. Both support iteration Now if you iterate over the result: case 1, input -> "value1": for elem in input: #in real life we might validate here... print elem -> 'v' 'a' 'l' 'u' 'e' '1' case 2, input -> ["value1", "value2"] for elem in input: print elem -> "value1" "value2" cheers Paul Disclaimer: I like python and I write tests but i wish unittest had class/module level setUp()... -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete a function
gtb schrieb: > On Mar 21, 11:37 am, Steve Holden <[EMAIL PROTECTED]> wrote: >> gtb wrote: >>> After a function has been imported to a shell how may it be deleted so >>> that after editing it can reloaded anew? >> Use the built-in reload() function to reload the module that defines the >> function. > Thanks, tried that now and get nameError: with the following. > > import sys > sys.path.append("c:\maxq\testScripts") > > from CompactTest import CompactTest > from compactLogin import dvlogin > > reload(compactLogin) you haven't imported compactLogin but dvlogin from the compactLogin namespace. Try: import compactLogin ...do something with compactLogin.dvlogin... reload(compactLogin) cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: I18n issue with optik
Thorsten Kampe schrieb: [snipp] > I got the tip to set a different encoding by > sys.stdout = codecs.EncodedFile(sys.stdout, 'utf-8') > > but unfortunately this does not change the encoding of any Terminal. > So my question is: how can I set a different encoding to sys.stdout > (or why can I set it without any error but nothing changes?) AFAIK you can't. If the terminal is limited to ascii it won't be able to display anything else; it might not even have the right font, so how are you supposed to fix that? The .encode(encoding, "replace") ensures safe downgrades though. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbi Q: Recursively reverse lists but NOT strings?
Dmitri O.Kondratiev schrieb: > Gary, thanks for lots of info! > Python strings are not lists! I got it now. That's a pity, I need two > different functions: one to reverse a list and one to reverse a string: Not necessarily, you can handle both cases in one function: def reverse(xs): if xs in [[], '']: return xs return (reverse (xs[1:])) + [xs[0], [xs[0]]][isinstance(list, xs)] but this is evil(tm) and violates Rule #1, #2 of "import this" and several others. > Ok. Now regarding in-place reversal of a list: why this ? : > >>>> ls = [1,2,3].reverse() >>>> ls >>>> >>>> print [1,2,3].reverse() > None > I mean, why ls is empty after assignment? That's what "in-place" means, [].reverse() changes the list in-place and does not return the list to the caller. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: how to creating html files with python
krishnakant Mane schrieb: [snip] > so instead of I doing the concatination myself, python makes it easy. > and I will have lot of complex tables etc to do like this. > so please help me choose one. Did you actually looked for a template language as suggested here? Now to make your life easier: If you like XML, use genshi. If you plan to generate something else than HTML, use cheetah. Use google or whatever search engine you prefer to find those packages. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore DoS vulnerability
Jean-Paul Calderone schrieb: > It could ask the application. On the other hand, maybe asyncore remains in > a perfectly consistent state even after it raises this exception, and it is > already "asking" by letting this exception propagate up: if the application > is free to start the loop again after this happens, then it seems everything > is just fine; if some state becomes inconsistent, though, then asyncore should > probably do something more (assuming asyncore applications are supposed to be > able to be resistent to this kind of DoS). I second that, especially given the rather unspecific nature of "ValueError". Something like "EnvironmentError" or "OSError" would be more appropriate. Problem is: such a change would break lots of code... thanks Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: when will python 2.5 take in mainstream?
Eric CHAO schrieb: > A lot of application based on python claim that python 2.3 or 2.4 is > needed not 2.5, ie. mysqldb. I've been using python for months. I > don't care about 2.4 or 2.5. But I like the default icons of python in > 2.5. So I just use that, but some scripts can't work on that. What do you mean by "that"? I just use the 2.5 icons with 2.4 and all my scripts are happy ;) thanks Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: I need a crack for pyext1.2.5 plugin
Oliver Sosa Cano schrieb: > Sorry if this is the wrong place to make that question. It is the wrong place. > > Pyext is a plugin that acoplate with pydev, it's 'software privativo' > like said Stallman, but it's very interesting. You should ask Stallman how software developers should pay their bills and further ignore some of his drivel. > I have version 1.2.5. > I use Eclipse 'cos it's simply great!! > If somebody could tell me some alternative... The author of pydev-extension provides pydev FOR FREE!! If you want pydev-extension you should by a license. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python good for data mining?
Jens schrieb: > What about user interfaces? How easy is it to use Tkinter for > developing a user interface without an IDE? And with an IDE? (which > IDE?) Tkinter is easy but looks ugly (yeah folks, I know it doesn't matter in you mission critical flight control system). Apart from ActiveStates Komodo I'm not aware of any GUI builders. Very likely you don't need one. > > What if I were to use my Python libraries with a web site written in > PHP, Perl or Java - how do I intergrate with Python? How do you "integrate" Perl and PHP? The usual methods are calling external programs (slow) or using some IPC method (socket, xmlrpc, corba). > > I really like Python for a number of reasons, and would like to avoid > Java. Have you looked at jython? cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How to display unicode with the CGI module?
Marc 'BlackJack' Rintsch schrieb: > On Sat, 24 Nov 2007 15:58:56 -0800, coldpizza wrote: > >> The problem I am having is that I get an error while trying to display >> Unicode UTF-8 characters via a Python CGI script. >> >> The error goes like this: "UnicodeEncodeError: 'ascii' codec can't >> encode character u'\u026a' in position 12: ordinal not in range(128)". > > Unicode != UTF-8. You are not trying to send an UTF-8 encoded byte string > but an *unicode string*. Just to expand on this... It helps thinking of "unicode objects" and "strings" as seperate types (which they are). So there is no such thing like "unicode string" and you always need to think about when to encode() your unicode objects. However, this will change in py3k..., what's the new rule of thumb? cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How to display unicode with the CGI module?
greg schrieb: > paul wrote: >> However, this will change in py3k..., >> what's the new rule of thumb? [snipp] > So you won't be able to get away with ignoring encoding > issues in py3k. On the plus side, it should all be handled > in a much more consistent and less error-prone way. If > you mistakenly try to use encoded data as though it were > decoded data or vice versa, you'll get a type error. Thanks for your detailed answer. In fact, having encode() only for and decode() for will simplify things a lot. I guess implicit encode() of when using print() will stay but having utf-8 as the new default encoding will reduce the number of UnicodeError. You'll get weird characters instead ;) cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: An Object's Type
Bruno Desthuilliers schrieb: > [EMAIL PROTECTED] a écrit : >> Hi, >> >> Is it possible to find out if an object is of a certain type or of a >> type derived from this type? >> > You have the answer, thanks to Diez and Christian. Now unless you have a > *very* compelling reason to check the type of an object, *just forget > about it*. 9 times out of 10, this is fighting against the language's > type system (hint: google for "duck typing"). So I have to give up the concept that argument types are part of the interface or signature? Honestly, I don't like that. Granted; not having strict type checking makes for great flexibility but the price is you either write typchecking code or let the error propagate into the function or method. I hope type annotations in py3k will allow for something like constraints in C# where you can tell the caller right away she's doing something wrong. greetings Paul BTW: are type annotations to be backported to 2.x? -- http://mail.python.org/mailman/listinfo/python-list
Re: An Object's Type
Chris Mellon schrieb: > On Dec 6, 2007 5:52 AM, paul <[EMAIL PROTECTED]> wrote: >> function or method. I hope type annotations in py3k will allow for >> something like constraints in C# where you can tell the caller right >> away she's doing something wrong. >> [language rant snipped] > On a more pragmatic basis, there are only 2 kinds of type errors in Python: > 1: The object passed doesn't implement the correct interface, and will > raise an error when called. This will be caught by a unit test. > 2: The object passed implements something that looks like the right > interface, but implements it incorrectly. This will be caught by a > unit tests. So if I use your code I need to read all of it to understand how "file like" something for bla(filelike) needs to be to be able to write unittests? Or do your unittests magically detect all possible callers and send them email with nice warnings? > > Note that both these errors will be caught by behavior exercising unit > tests and do not rely on any sort of "typechecking code" to be > written. Explicit typechecking in Python is done only when you need to > dispatch on type, not because you feel like generating spurious > errors. Do you prefer situations like Hrvoje has descibed two post below? To reiterate: I'd like to have a TypeError: "foo called with , expected" which is concise and informative for the caller, rather than have him hunt down obscure errors in totally unrelated code like AttributeError: 'str' object has no attribute 'move'. greetings Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Terminate capability ....
[EMAIL PROTECTED] schrieb: > Hello, > > I'm new to Python. I have a small task to do. I need to be able to > find a running app (preferrably by name) and kill it. This is for the > XP environment. What is best way to do this? > Thanks, import os os.system('taskkill /IM explorer.exe') cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-XSD Processing/Creation.
xkenneth schrieb: > Hi All, > > So i'm working with the WITSML standard, which is a pretty > massive standard defined in XML for the transfer of oilfield data. > There are a ton of XSD files for defining and checking all data in the > WITSML format. I'd like to be able to easily create XML based on the > types defined by the WITSML XSD files. Is there any way to create a > basic XML object based on an XSD file and then populate it with data. > Can i create python classes based off the XSD files? What else can I > do with the XSD files? This might be worth looking at: http://www.rexx.com/~dkuhlman/#generateDS cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: SuPy - Script Sketchup with Python
greg schrieb: SuPy 1.0 SuPy is a plugin for the Sketchup 3D modelling application that lets you script it in Python. Great, will give it a try. http://www.cosc.canterbury.ac.nz/SuPy/ I think you meant to write http://www.cosc.canterbury.ac.nz/~greg/SuPy/ This is a first version and is highly experimental. Let me know if it works for you and whether you have any problems. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: AJAX Post requests
On Feb 10, 7:37 am, Tim Roberts wrote: > PJ wrote: > > >I have a simple web server using BaseHTTPServer, and the def do_POST > >(self) function works fine for regular forms that are submitted to it, > >but when I send anAJAXPOST to it it does nothing (I've tried to just > >get it to print to check it's nothing else but it doesn't even do > >that, although it does for a regular POST request. > > Are you absolutely sure yourAJAXrequest is being sent with Content-Type > multipart/form-data? Your code would explode silently if it didn't, > because "query" would not exist when you got to "print(query.get('data'))", > and your blanket "except" would hide the error. > -- > Tim Roberts, t...@probo.com > Providenza & Boekelheide, Inc. Thankyou for that - you're right - I'm new to AJAX so it's taking me a bit of time to get used to it - its an application data type being submitted -- http://mail.python.org/mailman/listinfo/python-list
BaseHttpServer
Hi, I currently have a webserver using BaseHttpServe that serves images like this: if self.path.endswith(".jpg"): print(curdir + sep + self.path) f = open(curdir + sep + self.path,"b") self.send_response(200) self.send_header('Content-type','image/jpg') self.end_headers() self.wfile.write(f.read()) f.close() return Whilst it works, it does take quite a while to load (approx 10secs for a 4mb file even though its over the local connection) - does anyone have any hints/tips for speeding it up? Thanks, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: BaseHttpServer
On Feb 15, 8:46 pm, Steve Holden wrote: > Paul wrote: > > Hi, > > I currently have a webserver using BaseHttpServe that serves images > > like this: > > if self.path.endswith(".jpg"): > > print(curdir + sep + self.path) > > f = open(curdir + sep + self.path,"b") > > self.send_response(200) > > self.send_header('Content-type', 'image/jpg') > > self.end_headers() > > self.wfile.write(f.read()) > > f.close() > > return > > Whilst it works, it does take quite a while to load (approx 10secs for > > a 4mb file even though its over the local connection) - does anyone > > have any hints/tips for speeding it up? > > You could consider reading the file in smaller blocks and writing the > output in a loop. That way the next block of the file can be read in > while the network buffers are emptying. > > Just keep reading data and writing it until the number of data bytes you > wrote is fewer than the number you tried to read. > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ Thanks for these but they seem to have made no difference - it still loads (visually) in chunks on the screen taking quite a while. Intrestingly, with the looping idea I got it to print out on each loop and some took a substantial amount of time to load compared to others (I tried using 1500 and then 10,000 size chunks,with the code being: if self.path.endswith(".jpg"): print(curdir + sep + self.path) f = open(curdir + sep + self.path,"rb") self.send_response(200) self.send_header('Content-type','image/jpg') self.end_headers() h = 1 while h==1: g = f.read(1) h = len(g) print h self.wfile.write(g) #self.wfile.write(f.read()) #shutil.copyfileobj(f,self.wfile) f.close() return I also tried loading it to memory before it was requested but that also made no difference. If anyone's got any suggestions, I would be very greatful, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Split entries from LDAP
Lars schrieb: I got all the entries in the variable "raw_res" and I now got some doubts on how to split each value up in every entry. Belove you can see one of entries printed from the loop. cn=world.dom.dk,ou=Hosts,o=Users,dc=dom,dc=dk', {'ipHostNumber': ['192.168.0.43'], 'cn': ['world.dom.dk'], 'description': ['Mail&webserver']})" I've tried different things, but don't quite know to split the tuple. search_s() returns a tuple of lenght 2. The first entry is the DN, the second entry is a dictionary with attributes as keys and lists of values as values. Possible function to handle this (untested): def print_entry(entry): print "Got Entry for DN: %s" % entry[0] print "Attributes:" for key, value in entry[1].items(): print "\tKey: %s" % key print "\tValue(s): %s" ", ".join(value) print the ", ".join(value) creates a string from a list, check the docs for dictionaries for other syntax elements. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Append a new value to dict
Pat schrieb: I know it's not "fair" to compare language features, but it seems to me (a Python newbie) that appending a new key/value to a dict in Python is awfully cumbersome. In Python, this is the best code I could come up with for adding a new key, value to a dict mytable.setdefault( k, [] ).append( v ) In Perl, the code looks like this: $h{ $key } = $value ; Whats wrong with: mytable[key] = value cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Are there any FOSS Python Single-Sign-on Servers?
Phillip B Oldham schrieb: Are there any FOSS Python Single-Sign-on Servers? [snip] I've searched around but can only seem to find OpenID servers, which will probably be too "open" for our needs. So if it is not OpenID, which protocol are you going to implement? cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: duck-type-checking?
Ben Finney schrieb: Joe Strout <[EMAIL PROTECTED]> writes: "x quacks like a basestring if it implements all the public methods of basestring, and can be used in pretty much any context that a basestring can." That is not duck typing. Rather than checking what foo does in response to prodding that, by your admission, is only designed to find out what type it is, duck typing instead advocates that you should use foo *as though it is known to be* the type of object you want. If it is not suitable, then appropriate exceptions will be raised and either caught by some code that knows how to handle them, or crash the program. Warning, rant ;) This whole theory breaks down quickly if you're writing library code. How do your unittests help the user of your library to use it correctly? How do you communicate incorrect usage of your interfaces to the user? If you are able to specify the type of the arguments as part of the interface the compiler/interpreter will help you. Types are used to describe behaviour (if thats a good thing, I don't know). While python has strong types, there could be used better (instead it gets worse, see the suddently-not-sortable-list-type diskussion and the endless repetition of the greatest of all after-the-fact theories ever "duck typing". cheers Paul BTW: Back to Java? No, not really. -- http://mail.python.org/mailman/listinfo/python-list
yaml for persistence
class User(object): def __init__(self, uid): self.uid = uid self.__dict__.update(yaml.load(str('uid')+'.yaml')) def save(self): f=open(str(self.uid)+'.yaml') yaml.dump(self.__dict__, f) is there a better way to persist using Yaml Paul http://bidegg.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A design problem I met again and again.
一首诗 schrieb: > Consolidate existing functions? > > I've thought about it. > > For example, I have two functions: > > #= > > def startXXX(id): > pass > > def startYYY(id): > pass > #= > > I could turn it into one: > > #= > def start(type, id): > if(type == "XXX"): > pass > else if(type == "YYY"): > pass > #= > > But isn't the first style more clear for my code's user? Depends ;) There are more ways to structure code than using classes. To avoid the if-elif-elif-elif-else problem you could start using a dispatch table which maps types to functions (fex using a dict) start_methods = { 'type1': startXX, 'type2': startYY, } def start(type, id): func = start_methods.get(type, None) if func: func(id) else: raise ... Or maybe look at trac's (http://trac.edgewall.com) use of Components and Interfaces. Very lightweight and modular. You can start reading here: http://trac.edgewall.org/browser/trunk/trac/core.py cheers Paul > > That's one reason why my interfaces grow fast. > > On Apr 3, 1:51 am, Carl Banks wrote: >> On Apr 2, 8:02 am, 一首诗 wrote: >> >>> You get it. Sometimes I feel that my head is trained to work in a >>> procedural way. I use a big class just as a container of functions. >>> About the "data-based" approach, what if these functions all shares a >>> little data, e.g. a socket, but nothing else? >> Then perhaps your problem is that you are too loose with the >> interface. Do you write new functions that are very similar to >> existing functions all the time? Perhaps you should consolidate, or >> think about how existing functions could do the job. >> >> Or perhaps you don't have a problem. There's nothing wrong with large >> classes per se, it's just a red flag. If you have all these functions >> that really all operate on only one piece of data, and really all do >> different things, then a large class is fine. >> >> Carl Banks > > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Computed attribute names
Dale Amon schrieb: There are a number of things which I have been used to doing in other OO languages which I have not yet figured out how to do in Python, the most important of which is passing method names as args and inserting them into method calls. Here are two cases I have been trying to figure out for a current project. The first is passing methods to dispatcher methods. In pseudocode, something like this: def dispatcher(self,methodname): self.obj1.methodname() self.obj2.methodname() I'd say you can use: method = getattr(self.obj1, 'methodname') method() It will raise AttributeError if 'methodname' is not found or the (optional) third argument to getattr() and another case is selecting behavior of an object by setting a type string, with pseudo code like this: self.IBM029 = re.compile([^acharset] self.IBM026 = re.compile([^anothercharset] self.type = "IBM029" errs = self.(self.type).findall(aCardImage) same here, or use a class/module-level dict like symbol_table = { 'IBM029': re.compile([^...]), 'IBM026': re.compile([^...]) } and symbol_table[self.type].findall(something) cheers Paul -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
__import__ function broken in 2.6
Hi It seems in 2.6 you are no longer able to use the __import__ function with different paths. Here is our code: sys.path = g.origSysPath[:] # copy, not reference sys.path.insert(0, modulePath) sys.modules = g.origSysModules.copy() if sys.modules.get(moduleName): del sys.modules[moduleName] # look for modules in subdirectories moduleName = "module_"+moduleName+"/"+moduleName module = __import__(moduleName) Unfortunately, this no longer works in 2.6. Does anyone have any idea on how to make it work with file paths? After quite a lot of searching, I was actually able to find a patch that someone made to fix this. Here is the code: sfepy.googlecode.com/issues/attachment? aid=-8587746048072650671&name=import.patch --- commit 2e92019ef957b547856e81a144db6845bf95d881 Author: Robert Cimrman Date: Thu Mar 5 09:59:59 2009 +0100 fixed load_classes() for Python 2.6 - __import__() function does not work when passing a file path as name diff --git a/sfepy/terms/__init__.py b/sfepy/terms/__init__.py index 3fab007..34a31a6 100644 --- a/sfepy/terms/__init__.py +++ b/sfepy/terms/__init__.py @@ -10,9 +10,9 @@ def load_classes( filenames, is_class ): table = {} for filename in filenames: name = os.path.splitext( filename )[0] -#print filename, name -mod = __import__( name ) -#print mod +parts = name.split( os.path.sep ) +mod, name = '.'.join( parts ), parts[-1:] +mod = __import__( mod, globals(), locals(), name ) for key, var in mod.__dict__.iteritems(): if is_class( key ): table[var.name] = var --- However, after a lot of messing around with the new __import__( mod, globals(), locals(), name ) function, I am still unable to make it work. Perhaps I am just not able to understand exactly what is going on here. Can anyone offer some assistance? Thank you, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: __import__ function broken in 2.6
We found a quick workaround to make import work with paths. We just append the folder we want to the system's path: sys.path.append( moduleFolder ) If anyone has a better solution, that would be great. Until then, this is ugly, but it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: eval(WsgiApplication)
gert schrieb: I would like to read the following from a text file Hi gert, I'm puzzled, what is wrong with using wsgi as advertised? Just import your code and insert it in the wsgi chain no? cheers Paul from json import loads from gert.db import Db def application(environ, response): v = loads(environ['wsgi.input'].read(int(environ ['CONTENT_LENGTH'])).decode('utf-8')) db = Db() db.execute('UPDATE votes SET count=count+1 WHERE vid=?',(v ['vid'],)) db.execute('SELECT * FROM votes') j = '{"rec":'+db.json()+',\n' j+= ' "des":'+db.jdes()+'}' j = j.encode('utf-8') response('200 OK', [('Content-type', 'text/ javascript;charset=utf-8'), ('Content-Length', str(len(j)))]) return [j] execute it, and wrap a new function name around it for example def wrapper(environ, response): exec(file) return application(environ, response) How do I do this in python3? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Any way to loop through object variables?
Dave Challis schrieb: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Ah thanks, vars(...) was exactly what I was after. I'd come across dir() before, but this returns more than I need. It seems vars() misses class attributes tho... cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: So you think PythonCard is old? Here's new wine in an old bottle.
Have you shown this stuff to the google AppEngine folks! Thats being touted as the thing that'll make web-2 easy but you have to write code (Python) which will turn off 99% of possible users. What made Hypercard really great (and Supercard on DOS, and the new clones like Revolution) is that it was a drag-n-drop GUI designer, it "built-in" the data storage (persistence layer is what we call it now) it was INTEGRATED, (you only had to get the one thing, not heinz-57- bloody-pieces) and it used an easily-readable interpreted programming language. App-Engine has the persistence, and the integration, its missing the others and without them it'll never be great. call those guys, they need you! I need your stuff on their infrastructure. THAT would be worth a case of champagne. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamically naming objects.
Something like this? class User: def __init__(self, name): self.name = name def __str__(self): return self.name n = 10 users = [] for i in range(n): users.append(User('user%d' % i)) print users[9] print users[4] Cheers, Paul On Sat, Jun 7, 2008 at 3:59 AM, Kalibr <[EMAIL PROTECTED]> wrote: > I've been developing a small script to fiddle with classes, and came > accross the following problem. Assuming I get some user input asking > for a number, how would I spawn 'n' objects from a class? > > i.e. I have a class class 'user' and I don't know how many of them I > want to spawn. > > Any ideas? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python XML-RPC Server with clientside Javascript
akineko schrieb: Hello everyone, I have used Python SimpleXMLRPCServer to expose several methods to be used. My Python script creates a free-standing server and not a CGI script. I have tested its exposed methods using the following Python script: import xmlrpclib s = xmlrpclib.ServerProxy('http://localhost:8765') print s.my_method() I tested all methods one by one and they are working as I intended. Now, I want to use those exposed methods from a static html file (without any web server) using client side javascript. (i.e. Open File... from the browser (or file://...) ) I found many XML-RPC examples with javascript but all of them I found assume XML-RPC services to be deliver from a web server, such as Apache, as a CGI. I'd think this has nothing to do with CGI vs. "free-standing", the client couldn't tell the difference anyway. It looks like you're running in the "same origin" javascript security restriction enforced by the browser. That is, the origin of your javascript is file://... and you're trying to access http://localhost:8765. This is not allowed. hth Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: FOSS projects exhibiting clean/good OOP?
Phillip B Oldham schrieb: Thanks all - lots to go through there! :D I'd heard previously that Trac was a nice example, or rather its core was, but I'd also heard that there were lots of problems with it and that they were redeveloping it from scratch? They continually improve parts of it, but I don't know of any severe problems whatsoever. Yes people are moaning about lack of multi-project support but that was a design decision way back. From a programming POV, I highly recommend looking at the source. The component model looks simple but is very powerful. It's also a good example how code benefits from interfaces wrt. structuring and documentation. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with displaying images in CherryPy
David Lyon schrieb: ... All I want is a sample configuration file that will allow me to display a page with a jpeg on it. This really should only take a few minutes for somebody who has done this in CherryPy before and I would certainly appreciate the assistance because it doesn't seem covered in any documentation that i could find. Whats wrong with this page? http://www.cherrypy.org/wiki/StaticContent cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Strong/weak typing
[EMAIL PROTECTED] schrieb: I'm writing Python as if it were strongly typed, never recycling a name to hold a type other than the original type. If it buys you anything? Maybe for shedskin or some future "to-native-code" compiler? Is this good software engineering practice, or am I missing something Pythonic? I'd say so. In a function/method body I do reuse generic names like data,counter,etc. but I never change say an instance variable to another type (except from None). Principle of least surprise applies here. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a python code periodically
Maryam Saeedi schrieb: > Hi, > > I was wondering if you know how can I run a python code once every five > minutes for a period of time either using python or some other program like > a bash script. See the sched module in the standard library or here: http://pypi.python.org/simple/Recur/ cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Running a python code periodically
Larry Bates schrieb: > paul wrote: >> Maryam Saeedi schrieb: >>> Hi, >>> >>> I was wondering if you know how can I run a python code once every five >>> minutes for a period of time either using python or some other program >>> like >>> a bash script. >> See the sched module in the standard library or here: >> http://pypi.python.org/simple/Recur/ >> >> cheers >> Paul >> > You could use cron also. I hate external dependencies! Whats worse is the need to fiddle with settings in different locations. All of a sudden, arcane looking crontabs are configuration files you have to care about. Better to avoid that. cheers Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: is file open in system ? - other than lsof
bvidinli schrieb: > is there a way to find out if file open in system ? - > please write if you know a way other than lsof. because lsof if slow for me. > i need a faster way. > i deal with thousands of files... so, i need a faster / python way for this. > thanks. I think you can do this with inotify. It's an event based notification mechanism for linux kernel 2.6.13 and up. It has python bindings available (google for pyinotify). You will receive events like IN_OPEN,IN_CLOSE,etc. and keep track of opened files this way. hth Paul -- http://mail.python.org/mailman/listinfo/python-list
confusing thread behavior
I have been experiencing strange thread behavior when I pass a message received via a Queue to a wx.PostEvent method (from wxPython). The relevant code in the thread is: def run(self): while self.is_running: task = self.queue.get() wx.PostEvent(self.app.handle_task, task) self.queue is a Queue.Queue instance and self.app is a wx.Window instance I have a case where two items are placed in the queue one after the other, and it appears that only the first item is passed to wx.PostEvent. If I place a time.sleep(0.1) call anywhere within the while loop, both items get passed to wx.PostEvent. It works if I put time.sleep before the self.queue.get(), in between get() and PostEvent () or after PostEvent(). So it seems like a short delay is enough to get two items handled, although it doesn't seem to matter where I place the delay within the while loop. Does someone know what might explain this behavior? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: confusing thread behavior
On Dec 3, 2:03 pm, Mike Driscoll wrote: > On Dec 3, 3:42 pm, paul wrote: > > > > > > > I have been experiencing strange thread behavior when I pass a message > > received via a Queue to a wx.PostEvent method (from wxPython). The > > relevant code in the thread is: > > > def run(self): > > while self.is_running: > > task = self.queue.get() > > wx.PostEvent(self.app.handle_task, task) > > > self.queue is a Queue.Queue instance and self.app is a wx.Window > > instance > > > I have a case where two items are placed in the queue one after the > > other, and it appears that only the first item is passed to > > wx.PostEvent. If I place a time.sleep(0.1) call anywhere within the > > while loop, both items get passed to wx.PostEvent. It works if I put > > time.sleep before the self.queue.get(), in between get() and PostEvent > > () or after PostEvent(). So it seems like a short delay is enough to > > get two items handled, although it doesn't seem to matter where I > > place the delay within the while loop. Does someone know what might > > explain this behavior? Thanks. > > [Note: I cross-posted this to wxPython where Paul had also cross- > posted] > > Not sure if this will help or not, but see the following article on > the wxPython wiki: > > http://wiki.wxpython.org/LongRunningTasks > > There's a section called "More Tips" where Queues are discussed. Robin > Dunn (creator of wxPython) seems to recommend using wx.CallAfter there > rather than PostEvent. > > --- > Mike Driscoll > > Blog: http://blog.pythonlibrary.org I apologize -- I meant to type wx.CallAfter instead of wx.PostEvent in my posting here (I've actually tried both approaches and did not see any difference...). I've looked over the LongRunningTasks wiki. I'll look at it again! -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i use lxml with win32com?
elca schrieb: Hello, Hi, following is script source which can beautifulsoup and PAMIE work together. but if i run this script source error was happened. AttributeError: PAMIE instance has no attribute 'pageText' File "C:\test12.py", line 7, in bs = BeautifulSoup(ie.pageText()) You could execute the script line by line in the python console, then after the line "ie = PAMIE(url)" look at the "ie" object with "dir(ie)" to check if it really looks like a healthy instance. ...got bored, just tried it -- looks like pageText() has been renamed to getPageText(). Try: text = PAMIE('http://www.cnn.com').getPageText() cheers Paul and following is orginal source until i was found in internet. from BeautifulSoup import BeautifulSoup from PAM30 import PAMIE url = 'http://www.cnn.com' ie = PAMIE(url) bs = BeautifulSoup(ie.pageText()) if possible i really want to make it work together with beautifulsoup or lxml with PAMIE. sorry my bad english. thanks in advance. Stefan Behnel-3 wrote: Hi, elca, 25.10.2009 02:35: hello... if anyone know..please help me ! i really want to know...i was searched in google lot of time. but can't found clear soultion. and also because of my lack of python knowledge. i want to use IE.navigate function with beautifulsoup or lxml.. if anyone know about this or sample. please help me! thanks in advance .. You wrote a message with nine lines, only one of which gives a tiny hint on what you actually want to do. What about providing an explanation of what you want to achieve instead? Try to answer questions like: Where does your data come from? Is it XML or HTML? What do you want to do with it? This might help: http://www.catb.org/~esr/faqs/smart-questions.html Stefan -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i use lxml with win32com?
elca schrieb: Hi, thanks a lot. studying alone is tough thing :) how can i improve my skill... 1. Stop top-posting. 2. Read documentation 3. Use the interactive prompt cheers Paul paul kölle wrote: elca schrieb: Hello, Hi, following is script source which can beautifulsoup and PAMIE work together. but if i run this script source error was happened. AttributeError: PAMIE instance has no attribute 'pageText' File "C:\test12.py", line 7, in bs = BeautifulSoup(ie.pageText()) You could execute the script line by line in the python console, then after the line "ie = PAMIE(url)" look at the "ie" object with "dir(ie)" to check if it really looks like a healthy instance. ...got bored, just tried it -- looks like pageText() has been renamed to getPageText(). Try: text = PAMIE('http://www.cnn.com').getPageText() cheers Paul and following is orginal source until i was found in internet. from BeautifulSoup import BeautifulSoup from PAM30 import PAMIE url = 'http://www.cnn.com' ie = PAMIE(url) bs = BeautifulSoup(ie.pageText()) if possible i really want to make it work together with beautifulsoup or lxml with PAMIE. sorry my bad english. thanks in advance. Stefan Behnel-3 wrote: Hi, elca, 25.10.2009 02:35: hello... if anyone know..please help me ! i really want to know...i was searched in google lot of time. but can't found clear soultion. and also because of my lack of python knowledge. i want to use IE.navigate function with beautifulsoup or lxml.. if anyone know about this or sample. please help me! thanks in advance .. You wrote a message with nine lines, only one of which gives a tiny hint on what you actually want to do. What about providing an explanation of what you want to achieve instead? Try to answer questions like: Where does your data come from? Is it XML or HTML? What do you want to do with it? This might help: http://www.catb.org/~esr/faqs/smart-questions.html Stefan -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Problems embedding python 2.6 in C++
Hi, I'm extending some old Visual Studio 6 code to add embedded python scripting. It works fine most of the time but some python function calls do not work as expected. The C++ code is a multithreaded MFC application. I was assuming that it was GIL issues but I have tried using the manual locking (PyEval_SaveThread & PyEval_RestoreThread) and what seems to be the current method (PyGILState_Ensure & PyGILState_Release) Here's the error I'm getting: Traceback (most recent call last): File "...scripts\receipt_parser.py", line 296, in get_giftcard_purchase_value details = extract_transaction_details_section(test) File "...scripts\receipt_parser.py", line 204, in extract_transaction_details_section for line in base_details: TypeError: expected string or Unicode object, NoneType found base_details is a list of strings (I can just define it like 'base_details=["1","2","3"...]' on the line previous) and the code runs fine when run from standard interpreter. Many other function calls work fine from the embedded app. I create and then Py_DECREF the function parameters and the return value after each function call. The module import is created at C++ object constructor and then Py_DECREF'd in the desctuctor Anyone else had issues of this kind? My next try will be to use sub-interpreters per thread. Thanks, Paul. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems embedding python 2.6 in C++
Thanks Gabriel, I've managed to get it working and so far stable... What wasn't working reliably: mycppclass mycppclass::mycppclass() m_mypymodule = PyImport_Import(pModuleName) mycppclass::~ mycppclass() Py_XDECREF(m_mypymodule) mycppclass::callpy(funcname, args...) PyTuple_SetItem * args PyCallable_Check(func) PyObject_CallObject(func) Current working version: mycppclass mycppclass::mycppclass() {} mycppclass::~ mycppclass() {} mycppclass::callpy(funcname, args...) m_mypymodule = PyImport_Import(pModuleName) pyargs = PyTuple_SetItem * args PyCallable_Check(func) PyObject_CallObject(func,pyargs) Py_XDECREF(m_mypymodule) So now the module is being imported each function call (luckily I don't have to worry about performance) I assume this means that the internal representation of the imported module is being corrupted by something. I found another person with a similar issue here: http://mail.python.org/pipermail/python-dev/2004-March/043306.html - that is a long time ago but another multi-threaded app. I'm happy to use the working method but I'd like to understand what is going on a bit more. Can anyone shed any further light? Regards, Paul. On Tue, Feb 2, 2010 at 11:59 AM, Gabriel Genellina wrote: > En Mon, 01 Feb 2010 18:21:56 -0300, Paul escribió: > > > I'm extending some old Visual Studio 6 code to add embedded python >> scripting. It works fine most of the time but some python function calls >> do >> not work as expected. >> >> The C++ code is a multithreaded MFC application. I was assuming that it >> was >> GIL issues but I have tried using the manual locking (PyEval_SaveThread & >> PyEval_RestoreThread) and what seems to be the current method >> (PyGILState_Ensure & PyGILState_Release) >> >> Here's the error I'm getting: >> >> Traceback (most recent call last): >> File "...scripts\receipt_parser.py", line 296, in >> get_giftcard_purchase_value >>details = extract_transaction_details_section(test) >> File "...scripts\receipt_parser.py", line 204, in >> extract_transaction_details_section >>for line in base_details: >> TypeError: expected string or Unicode object, NoneType found >> >> base_details is a list of strings (I can just define it like >> 'base_details=["1","2","3"...]' on the line previous) and the code runs >> fine >> when run from standard interpreter. Many other function calls work fine >> from >> the embedded app. >> I create and then Py_DECREF the function parameters and the return value >> after each function call. The module import is created at C++ object >> constructor and then Py_DECREF'd in the desctuctor >> > > Usually, errors in reference count handling prevent objects from being > destroyed (a memory leak) or generate a GPF when accessing an now-inexistent > object. In principle I'd look elsewhere. > > > Anyone else had issues of this kind? >> > > Hard to tell without more info. base_details is built in C++ code? Is it > actually a list, or a subclass defined by you? > A common error is to forget to check *every* API function call for errors, > so errors get unnoticed for a while but are reported on the next check, > which may happen in an entirely unrelated function. > > > My next try will be to use >> sub-interpreters per thread. >> > > I would not do that - I'd try to *simplify* the code to test, not make it > more complicated. > Does it work in a single-threaded application? > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Embedding Python in a C extension
I have a problem with embedding Python into a C extension in Windows Vista. I have implemented a timer routine in C as an extension, which I can import into Python 2.6.5 and run. Each timer interval, the extension calls a C CALLBACK function. I want to be able to have this CALLBACK function call a Python function, so that I can write the timer handler in Python. I can write Python functions and call them from a C extension function with no trouble in all cases EXCEPT when the function that calls the Python code is the timer's CALLBACK function. That is, if I call PyRun_SimpleString or PyRun_SimpleFile, or PyImport_ImportModule, or basically any Python-y function in the CALLBACK function, Python crashes and I get a window saying "Python has stopped working. Windows is searching for a solution to the problem." The Python code runs fine if I call it from a function in the extension that is not the CALLBACK function. And regular C code runs in the CALLBACK function properly. It only crashes if I try to run the Python code from the timer CALLBACK function (or any C function I call from the CALLBACK function). Does anybody know how to fix this? Is there a workaround of some sort? -- http://mail.python.org/mailman/listinfo/python-list
[Fwd: Re: [ANN] Pyjamas 0.5 Web Widget Set and python-to-javascript Compiler released]
The python-announce-list-ow...@python.org suggested you might have a solution to my problem. Please help if you can. Thanks, Paul Original Message Subject: Re: [ANN] Pyjamas 0.5 Web Widget Set and python-to-javascript Compiler released Date: Thu, 10 Jun 2010 17:43:48 -0500 From: Paul To: python-announce-l...@python.org, l...@lkcl.net References: Hi, PLEASE HELP I am at http://pypi.python.org/pypi/Pyjamas-Desktop/0.1 _right now_ - _I've been everywhere_. Is there any way a _complete newbie_ with Linux can get the Pyjamas-Desktop installed and running I have a box on which I very recently managed to install Ubuntu 9.10 Apache 2.2.12 MySql 5.1.3.7 PHP 5.2.10-2 JRE 1.6.0_0 & OpenJDK IcedTea6 1.6.1 Package Manager says libwebkit-1.0-2 1.1.15.2-1 is installed. python-all 2.6.4ubuntu1 python-all-dev 2.6.4ubuntu1 python-all-dbg 2.6.4ubuntu1 python 2.6.4ubuntu1 python2.4 2.4.6-1ubuntu3.2.9 python2.5 2.5.4-1ubuntu6.1 python2.5-dbg 2.5.4-1ubuntu6.1 python2.5-dev 2.5.4-1ubuntu6.1 python2.6 2.6.4-0ubuntu3 python2.6-dbg 2.6.4-0ubuntu3 python2.6-dev 2.6.4-0ubuntu3 python-dbg 2.6.4-0ubuntu1 all installed - - - plus some more Python packages - the list goes on. I am comfortable with Desktop development (mainframe client / server) and would really love to find a Desktop IDE that would generate JavaScript for me. The Pyjamas-Desktop sounds like the perfect tool -IF- I could get it up and running. Please tell me there is a single install -or- list of specific installs that I need to make things work. I need step-by-step instructions since I know practically nothing about Linux or Ubuntu. Like - if a specific directory is require for a package to work - tell me it must go in directory /be/very/specific Any reply or instructions will be very appreciated. Thanks, Paul -- http://mail.python.org/mailman/listinfo/python-list
Python/C++ timer intermittent bug
I have a problem with threading using the Python/C API. I have an extension that implements a timer, and the C++ timer callback function calls a Python function. The relevant code looks like this: static PyObject *timer_setmodname( PyObject *pSelf, PyObject *pArgs ) { char *b; PyArg_ParseTuple( pArgs, "s", &b ); mod = PyImport_ImportModule(b); if( mod == NULL ) { printf("Could not import %s\n",b); return Py_None; } modsetFlag = TRUE; return Py_None; } static PyObject *timer_setprocname( PyObject *pSelf, PyObject *pArgs ) { char *b; if( !modsetFlag )return Py_None; PyArg_ParseTuple( pArgs, "s", &b ); attr = PyObject_GetAttrString(mod,b); if( attr == NULL ) { printf("Could not import %s\n",b); return Py_None; } attrsetFlag = TRUE; return Py_None; } static void CALLBACK PeriodicTimer(UINT wTimerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2) { PyGILState_STATE pgs; pgs = PyGILState_Ensure(); if(attrsetFlag) { pres = PyObject_CallFunction(attr,NULL); if( pres == NULL )printf("CallFunction failed!\n"); } PyGILState_Release( pgs ); } The Python code that sets this up looks like this: fetimer.setmodname("Timeslice3") fetimer.setprocname("Timetester") print "\n Program Waiting for Time Slice" while True: time.sleep(0.010) and the module Timeslice3.py looks like this: #Timeslice3.py def Timetester(): pass When I run this stuff, it works fine for hundreds, often even thousands, of timer ticks (I've been testing with about thirty ticks per second, but it doesn't matter - it still crashes at ten or fewer ticks per second). Sometimes it runs for only a few seconds, sometimes for ten minutes or so. But it always eventually crashes Python. Usually it gives no error message. Sometimes, though, it does give an error message, but not always the same one. I've noted three that it has given in my testing so far: Fatal Python Error: This thread state must be current when releasing Fatal Python Error: PyThreadState_DeleteCurrent: no current tstate Fatal Python Error: PyEval_SaveThread: NULL tstate Can anybody help me make this code stable, so that it works all the time? I'm using Python 2.6.5 under Windows Vista, but it crashes under Windows XP as well. -- http://mail.python.org/mailman/listinfo/python-list