Re[2]: termios.tcgetattr(fd) error: (22, 'Invalid argument')
>>To provide some feedback: >>As Grant Edwards posted in this list, I was running my code inside of >>IDE that replaces sys.stdin with some other. While running the program >>from a shell prompt, everything goes fine. >>Petr Jakes >> >> >> SN> have you tried it with root account ? Yes, I did. The problem was the IDE. Without IDE the filedescriptor and its flags settings are working flawlessly. -- http://mail.python.org/mailman/listinfo/python-list
How to convert simple B/W graphic to the dot matrix for the LED display/sign
I would like to convert simple B/W graphic to the 432x64 pixel matrix. It is intended to display this graphic on the one color LED matrix sign/display (432 LEDs width, 64 LEDs height). I am experimenting with the PIL, but I did not find solution there. It will be really helpful If somebody here can show me the direction to go? Regards Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert simple B/W graphic to the dot matrix for the LED display/sign
> What file format is the graphic in? How big is it? > > What file format do you want it to be? > Now, I am able to create the png file with the resolution 432x64 using PIL (using draw.text method for example). I would like to get the 432x64 True/False (Black/White) lookup table from this file, so I can switch LEDs ON/OFF accordingly. -- Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert simple B/W graphic to the dot matrix for the LED display/sign
> >>> import Image > >>> im=Image.new('L', (100,100)) > >>> im=im.convert('1') > >>> px=im.load() > >>> px[0,0] Thanks, load() method works great. One more question. Finally, I would like to store array in the database. What is the best way to store arrays? Petr -- http://mail.python.org/mailman/listinfo/python-list
mmap and bit wise twiddling - Raspberry Pi
Hi, I am trying to work with HW peripherals on Raspberry Pi To achieve this, it is necessary read/write some values from/to the memory directly. I am looking for some wise way how to organize the bit twiddling. To set some specific bit, for example, it is necessary: - read 4 bytes string representation (I am using mmap) - transform it to the corresponding integer (I am using numpy) - do some bit masking over this integer - transport integer to the string representation (numpy again) - write it back to the memory In other words I mean: is there wise way to create an instrument/ machinery to define Class and then simply define all necessary objects and set the bit values over object attributes so the whole bit- twiddling remains under the hood. say: LED01 = GPIO(4) # gpio PIN number 4 is assigned to the LED01 name (attribute) LED01.on() LED01.off() or gpio = GPIO() LED01 = gpio.pin04 LED01 = 1 # led diode is shining (or gpio pin 4 is set) LED01 = 0 # led diode is off General suggestions, how to organise this work are more then welcome. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
What encoding is used when initializing sys.argv?
Hi, When solving the problem of passing the unicode directory name through command line into a script (MS Windows environment), I have discovered that I do not understand what encoding should be used to convert the sys.argv into unicode. I know about the rejected attempt to implement sys.argvu. Still, how the sys.argv is filled? What encoding is used when parsing the cmd line internally? To what encoding is it converted when non ASCII characters appear? Thanks for your time and experience, pepr -- Petr Prikryl (prikrylp at skil dot cz) -- http://mail.python.org/mailman/listinfo/python-list
Re: What encoding is used when initializing sys.argv?
Thanks, Martin v. Löwis, Neil Hodgson, and Tim Roberts. I really appreciate your valuable comments. It simply works. Thanks again, Petr "Neil Hodgson" wrote... > Petr Prikryl: > > > I do not understand what encoding should be used > > to convert the sys.argv into unicode. > > Martin mentioned CP_ACP. In Python on Windows, this > can be accessed as the "mbcs" codec. > > import sys > print repr(sys.argv[1]) > print repr(unicode(sys.argv[1], "mbcs")) > > C:\bin>python glurp.py abcß* > 'abc\xdf\x95' > u'abc\xdf\u2022' > > Neil -- http://mail.python.org/mailman/listinfo/python-list
Any 3state Check Tree Ctrl for wxPython available?
Hi, I am experimenting with wxPython on Windows box. What I need to implement is a check tree control with 3 states for each checkbox: unchecked, checked, gray checked. The status of the checkbox should reflect the status of the children. When ALL children are checked, then the status should be checked. When NO children are checked, the status should be unchecked. When SOME children are selected, the status should be checked with gray background. I have found something else that could be valuable after I start understand that: http://mitglied.lycos.de/drpython/CheckTreeCtrl.tar Anyway, is there something similar with 3 states available around? Thanks for your time and experience, pepr -- Petr Prikryl (prikrylp at skil dot cz) -- http://mail.python.org/mailman/listinfo/python-list
UART parity setting as "mark" or "space" (using Pyserial???)
Hi, I am trying to set-up communication to the coin change-giver from my Linux box using the Python code. The change giver uses MDB (Multi Drop Bus) serial protocol to communicate with the master. MDB protocol is the 9bit serial protocol: (TX, RX lines only) 9600bps, 9bits, No Parity, 1 Start, 1 Stop. I would like to control the UART "parity bit" to try to simulate 9bit communication. Using Pyserial it is possible to set the parity bit as ODD, EVEN or NONE. I have found in the following link (paragraph 21.3) http://howtos.linux.com/howtos/Serial-HOWTO-21.shtml#ss21.1 that UART hardware supports two "rarely used" parity settings as well: mark parity and space parity (these setings are also known as "sticky parity") A "mark" is a 1-bit (or logic 1) and a "space" is a 0-bit (or logic 0). For mark parity, the parity bit is always a one-bit. For space parity it's always a zero-bit. Does anybody here knows some "tricks" how to set up the mark and space parity on the UART (using pyserial???), so I can simulate 9bit communication? (I know it sounds silly, but I would like to try to re-configure the UART parity before each byte transmission). Any comment will be appreciated. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
convert string to the "escaped string"
Hi, I am trying to convert string to the "escaped string". example: from "0xf" I need "\0xf" I am able to do it like: a="0xf" escaped_a=("\%s" % a ).decode("string_escape") But it looks a little bit complicated in this beautiful language to me Regards Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string to the "escaped string"
small mistake in my previous posting, sorry from "0xf" I need "\xf" of course and mentioned code gives me "\0xf" of course. Thanks for your postings Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: convert string to the "escaped string"
Fredrik, thanks for your posting. I really appretiate your reply and your way how you kindly answer even stupid newbie's questions on this mailing list. I was trying: int("0xf") but I did not have idea about the optional "base" parameter for the int function. Thanks a lot. Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: UART parity setting as "mark" or "space" (using Pyserial???)
To provide feedback: I have found the way how to control serial port parity bit on the Linux (how to set the parity bit to the "mark" or "space" parity) within Python using termios module. With the help of: http://www.lothosoft.ch/thomas/libmip/markspaceparity.php === import serial import termios import TERMIOS ser=serial.Serial('/dev/ttyS0', 9600, 8, "N", timeout=1) iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(ser) cflag |= PARENB | CMSPAR # To select SPACE parity cflag &= ~PARODD cflag |= PARENB | CMSPAR | PARODD # to select MARK parity termios.tcsetattr(ser, termios.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]) === Using above mentioned it is possible to establish 9bit serial communication according to the given protocol specifics. It is necessary to control parity bit setting before sending each communication byte. Regards Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
termios.tcgetattr(fd) error: (22, 'Invalid argument')
On my box (Fedora Core4, Python 2.4.1) I am getting following error: >>> import termios, sys >>> fd = sys.stdin.fileno() >>> oldSettings = termios.tcgetattr(fd) Traceback (innermost last): File "", line 1, in ? error: (22, 'Invalid argument') Thanks for your comments. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: termios.tcgetattr(fd) error: (22, 'Invalid argument')
To provide some feedback: As Grant Edwards posted in this list, I was running my code inside of IDE that replaces sys.stdin with some other. While running the program from a shell prompt, everything goes fine. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Bug in Python 2.4 raw_input(u'xyz') Win/command line?
Hi, Could you test the following example for your non-English language with accented characters? I have observed a problem when running Python 2.4, Windows version (python-2.4.msi) and using raw_input() with unicode prompt string in a console program (ran in the DOS window). I do use the following sitecustomize file to set the default encoding: sitecustomize.py = import sys sys.setdefaultencoding('cp1250') = test.py = # -*- coding: cp1250 -*- s = u'string with accented letters' print s # OK val = raw_input(s)# s displayed differently (wrong) = ... when run in a DOS window. See the attached test.png. The "type test.py" displays the string definition also wrong, because the DOS window uses different encoding than cp1250. The print command prints the string correctly, converting the internal unicode string to the encoding that the is defined by the output environment. However, the raw_input() probably does convert the unicode string to the cp1250 and does not do the same (more clever) thing that the print does. Could you confirm the bug? Is it known? Should this be posted into some bug-report list? Petr python test.py I have observed t -- Petr Prikryl (prikrylp at skil dot cz) test.py Description: test.py <>-- http://mail.python.org/mailman/listinfo/python-list
Re: list item's position
> On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: > > [...] how to find an element's numeric value (0,1,2,3...) > > in the list. Here's an example of what I'm doing: > > > > for bar in bars: > > if 'str_1' in bar and 'str_2' in bar: > >print bar > > > > This finds the right bar, but not its list position. The reason I need > > to find its value is so I can remove every element in the list before it > > so that the bar I found somewhere in the list becomes element 0... does > > that make sense? I have borrowed the bars list example from "Bill Mill"s solutions and here are the two solutions... bars = ['str', 'foobaz', 'barbaz', 'foobar'] # Solution 1: The enumerate(). for idx, bar in enumerate(bars): if 'bar' in bar and 'baz' in bar: break bars_sliced = bars[idx:] print bars_sliced # Solution 2: Low level approach, testing and removing combined. In situ. while bars: # some prefer len(bars) > 0, which is less magical, IMHO bar = bars.pop(0) # get and remove the first element if 'bar' in bar and 'baz' in bar: bars.insert(0, bar) # insert the tested back break # and finish print bars The result is ['barbaz', 'foobar'] in both cases. Petr -- Petr Prikryl (prikrylp at skil dot cz) -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Good C++ book for a Python programmer
Try also the Bruce Eckel's "Thinking in C++". It is also available on-line for free at http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html I like the book because it explains the things very clearly. After reading it, one will stop to think and say that C++ is "only C with strange OO things on the top". Petr "Paul Rubin" wrote in message news:<[EMAIL PROTECTED]>... > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > > I was wondering whether anyone could recommend a good C++ book, with > > "good" being defined from the perspective of a Python programmer. I > > realize that there isn't a book titled "C++ for Python Programmers", > > but has anyone found one that they think goes particularly well with > > the Python way? > > I think it's not possible to really grok C++ without having worked on > large multi-person C projects and understood what problems C++ tried > to solve. The only good book I know about C++ is by Stroustrup, "The > C++ Programming Language" or something like that; it's not an easy > book though. -- http://mail.python.org/mailman/listinfo/python-list
Simpler transition to PEP 3000 "Unicode only strings"?
Hi all, My question is: How do you tackle with mixing Unicode and non-Unicode parts of your application? Context: The PEP 3000 says "Make all strings be Unicode, and have a separate bytes() type." Until then, I am forced to write # -*- coding: cp123456 -*- (see 2.1.4 Encoding declarations) and use... myString = u'text with funny letters' This leads to a source polution that will be difficult to remove later. The idea: = What do you think about the following proposal that goes the half way If the Python source file is stored in UTF-8 (or other recognised Unicode file format), then the encoding declaration must reflect the format or can be omitted entirely. In such case, all simple string literals will be treated as unicode string literals. Would this break any existing code? Thanks for your time and experience, pepr -- Petr Prikryl (prikrylp at skil dot cz) -- http://mail.python.org/mailman/listinfo/python-list
Suggestion for "syntax error": ++i, --i
Hi, Summary: In my opinion, the C-like prefix increment and decrement operators (++i and --i) should be marked as "syntax error". Current situation: try... (Python 2.4 (#60, ...)) >>> i = 1 >>> i 1 >>> i++ File "", line 1 i++ ^ SyntaxError: invalid syntax >>> ++i 1 >>> --i 1 >>> Reason for how ++i and --i behaves in Python is that it is probably treated as (-(-i)) and (+(+i)) respectively. Rationale: My guess is that many Python users do use other languages at the same time. The C-family languages do use the prefix increment and decrement operators. When used in Python no warning appears -- the code simply does not work as expected. In the same time, there is probably no reason to use the increment and decrement prefix operators. On the other hand, the newcommer or the programmer that "types ++i automatically because of brain synapses say he/she should..." is not warned until something does not work. Con: The situation must be recognized by the parser (i.e. someone have to implement it). Pro: No runtime overhead except of the detection of the situation. As Python is a good candidate to be used as the language for teaching, the "syntax error" would be the pedagogical plus. Personal experience: Many things in Python work intuitively. My C++ experience "forced me" to use ++i as described above. I use iteration more these days and I know about the ++i problem invisibility in Python. But I had to learn by mistake. The ++i behaviour is not intuitive for me. Your opinion? -- Petr Prikryl (prikrylp at skil dot cz) -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestion for "syntax error": ++i, --i
Hi Christian, The suggestion is to mark PREFIX version ++i as syntax error. It is not related to the postfix version of the ++ operator. For prefix in/decrement, there is no extra variable behind. But again, it is not related to the suggestion. The postfix version is already marked as "syntax error". The suggestion is to do the same with the prefix version of the operators that are not used in Python. Petr "Christian Ergh" wrote... > Hmm, i never liked the i++ syntax, because there is a value asignment > behind it and it does not show - except the case you are already used to it. > > >>> i = 1 > >>> i +=1 > >>> i > 2 > > I like this one better, because you see the assignment at once, it is > easy to read and inuitive usability is given - in my opinion. > Chris > > > > > Petr Prikryl wrote: > > Hi, > > > > Summary: In my opinion, the C-like prefix > > increment and decrement operators (++i and --i) > > should be marked as "syntax error". > > > > > > Current situation: try... (Python 2.4 (#60, ...)) > > > >>>>i = 1 > >>>>i > > > > 1 > > > >>>>i++ > > > > File "", line 1 > > i++ > > ^ > > SyntaxError: invalid syntax > > > >>>>++i > > > > 1 > > > >>>>--i > > > > 1 > > > > > > Reason for how ++i and --i behaves in Python is > > that it is probably treated as (-(-i)) and (+(+i)) > > respectively. > > > > Rationale: My guess is that many Python users > > do use other languages at the same time. > > The C-family languages do use the prefix increment > > and decrement operators. When used in Python > > no warning appears -- the code simply does not work > > as expected. In the same time, there is probably no > > reason to use the increment and decrement > > prefix operators. On the other hand, the newcommer > > or the programmer that "types ++i automatically > > because of brain synapses say he/she should..." > > is not warned until something does not work. > > > > Con: The situation must be recognized by the parser > > (i.e. someone have to implement it). > > > > Pro: No runtime overhead except of the detection > > of the situation. As Python is a good candidate > > to be used as the language for teaching, the "syntax > > error" would be the pedagogical plus. > > > > Personal experience: Many things in Python work > > intuitively. My C++ experience "forced me" to use > > ++i as described above. I use iteration more these > > days and I know about the ++i problem invisibility > > in Python. But I had to learn by mistake. The ++i > > behaviour is not intuitive for me. > > > > Your opinion? > > > > -- http://mail.python.org/mailman/listinfo/python-list
Replacing lambda() examples... (Re: Lambda going out of fashion)
Hi, I suggest to post here simplified examples that use the lambda to be replaced by non-lambda Pythonic solutions. The ideal result would be the set of rules, how lambdas can be replaced by in future when they become deprecated. Less ideal but valuable may be short examples and counter-examples of using or not using the lambdas. While following the thread "Lambda going out of fashion" I have read cries for not throwing lambdas away and also the opposite opinions. I believe that the theme requires more examples to convince. I personally incline towards the experience of Craig Ringer (see other notices below): "Craig Ringer" wrote in message news:<[EMAIL PROTECTED]>... > [...] > I also make signficant use of Lambda functions, but less than I used to. > I've recently realised that they don't fit too well with Python's > indentation-is-significant syntax, and that in many cases my code is > much more readable through the use of a local def rather than a lambda. > > In other words, I increasingly find that I prefer: > > def myfunction(x): > return x**4 > def mysecondfuntion(x): > return (x * 4 + x**2) / x > make_some_call(myfunction, mysecondfunction) > > to: > > make_some_call( lambda x: x**4, lambda x: (x * 4 + x**2) / x) > > finding the former more readable. The function names are after all just > temporary local bindings of the function object to the name - no big > deal. Both the temporary function and the lambda can be used as > closures, have no impact outside the local function's scope, etc. I'd be > interested to know if there's anything more to it than this (with the > side note that just don't care if my temporary functions are anonymous > or not). > [...] I believe that GvR has a lot of experience and he proved to be very pragmatic. If he thinks that lambdas bring more problems than they solve, it may be some truth in it. I also believe that lamda-trained programmers think a bit differently which does not automatically mean that they think the best way in all cases. Waiting for interesting discussion, Petr -- Petr Prikryl (prikrylp at skil dot cz) --- Odchozí zpráva neobsahuje viry. Zkontrolováno antivirovým systémem AVG (http://www.grisoft.cz). Verze: 6.0.821 / Virová báze: 559 - datum vydání: 21.12. 2004 -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Python 2.x and 3.x use survey, 2014 edition
Also keep in mind that not all Python libraries are on PyPI. For non-Python projects with Python bindings (think video players, OpenCV, systemd, Samba), distribution via PyPI doesn't make much sense. And since the Python bindings are usually second-class citizens, the porting doesn't have a high priority. If anyone is wondering why their favorite Linux distribution is stuck with Python 2 – well, I can only speak for Fedora, but nowadays most of what's left are CPython bindings. No pylint --py3k or 2to3 will help there... On Fri, Dec 12, 2014 at 7:24 PM, Mark Roberts wrote: > So, I'm more than aware of how to write Python 2/3 compatible code. I've > ported 10-20 libraries to Python 3 and write Python 2/3 compatible code at > work. I'm also aware of how much writing 2/3 compatible code makes me hate > Python as a language. It'll be a happy day when one of the two languages > dies so that I never have to write code like that again. However, my point > was that just because the core libraries by usage are *starting* to roll out > Python 3 support doesn't mean that things are "easy" or "convenient" yet. > There are too many libraries in the long tail which fulfill semi-common > purposes and haven't been moved over yet. Yeah, sure, they haven't been > updated in years... but neither has the language they're built on. > > I suppose what I'm saying is that the long tail of libraries is far more > valuable than it seems the Python3 zealots are giving it credit for. Please > don't claim it's "easy" to move over just because merely most of the top 20 > libraries have been moved over. :-/ > > -Mark > > On Thu, Dec 11, 2014 at 12:14 PM, Dan Stromberg wrote: >> >> On Thu, Dec 11, 2014 at 11:35 AM, Mark Roberts wrote: >> > I disagree. I know there's a huge focus on The Big Libraries (and >> > wholesale >> > migration is all but impossible without them), but the long tail of >> > libraries is still incredibly important. It's like saying that migrating >> > the >> > top 10 Perl libraries to Perl 6 would allow people to completely ignore >> > all >> > of CPAN. It just doesn't make sense. >> >> Things in the Python 2.x vs 3.x world aren't that bad. >> >> See: >> https://python3wos.appspot.com/ and >> https://wiki.python.org/moin/PortingPythonToPy3k >> http://stromberg.dnsalias.org/~strombrg/Intro-to-Python/ (writing code >> to run on 2.x and 3.x) >> >> I believe just about everything I've written over the last few years >> either ran on 2.x and 3.x unmodified, or ran on 3.x alone. If you go >> the former route, you don't need to wait for your libraries to be >> updated. >> >> I usually run pylint twice for my projects (after each change, prior >> to checkin), once with a 2.x interpreter, and once with a 3.x >> interpreter (using >> http://stromberg.dnsalias.org/svn/this-pylint/trunk/this-pylint) , but >> I gather pylint has the option of running on a 2.x interpreter and >> warning about anything that wouldn't work on 3.x. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Python 2.x and 3.x use survey, 2014 edition
On Sun, Dec 14, 2014 at 1:14 AM, Nick Coghlan wrote: [...] > Barry, Petr, any of the other folks working on distro level C extension > ports, perhaps one of you would be willing to consider an update to the C > extension porting guide to be more in line with Brett's latest version of > the Python level porting guide? I can make it a 20%-time project starting in January, if no-one beats me to it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Linux users: please run gui tests
On Fri, Aug 7, 2015 at 4:07 AM, Terry Reedy wrote: > Python has an extensive test suite run after each 'batch' of commits on a > variety of buildbots. However, the Linux buildbots all (AFAIK) run > 'headless', with gui's disabled. Hence the following > test_tk test_ttk_guionly test_idle > (and on 3.5, test_tix, but not important) > are skipped either in whole or in part. > > We are planning on adding the use of tkinter.ttk to Idle after the 3.5.0 > release, but a couple of other core developers have expressed concern about > the reliability of tkinter.ttk on Linux. > > There is also an unresolved issue where test_ttk hung on Ubuntu Unity 3 > years ago. https://bugs.python.org/issue14799 > > I would appreciate it if some people could run the linux version of > py -3.4 -m test -ugui test_tk test_ttk_guionly test_idle > (or 3.5). I guess this means 'python3 for the executable. > > and report here python version, linux system, and result. > Alteration of environment and locale is a known issue, skip that. On Fedora 21, the tests pass (Python 3.4.1 and latest dev version). On Fedora 23, I see: $ python3 -V Python 3.4.3 $ python3 -m test -ugui test_tk test_ttk_guionly test_idle [1/3] test_tk [2/3] test_ttk_guionly [3/3] test_idle All 3 tests OK. $ ./python -V Python 3.6.0a0 $ ./python -m test -ugui test_tk test_ttk_guionly test_idle [1/3] test_tk [2/3] test_ttk_guionly [3/3] test_idle test test_idle failed -- Traceback (most recent call last): File "/home/pviktori/dev/cpython/Lib/idlelib/idle_test/test_configdialog.py", line 27, in test_dialog d=ConfigDialog(self.root, 'Test', _utest=True) File "/home/pviktori/dev/cpython/Lib/idlelib/configDialog.py", line 71, in __init__ self.LoadConfigs() File "/home/pviktori/dev/cpython/Lib/idlelib/configDialog.py", line 1078, in LoadConfigs self.LoadFontCfg() File "/home/pviktori/dev/cpython/Lib/idlelib/configDialog.py", line 980, in LoadFontCfg self.SetFontSample() File "/home/pviktori/dev/cpython/Lib/idlelib/configDialog.py", line 858, in SetFontSample self.labelFontSample.config(font=newFont) File "/home/pviktori/dev/cpython/Lib/tkinter/__init__.py", line 1330, in configure return self._configure('configure', cnf, kw) File "/home/pviktori/dev/cpython/Lib/tkinter/__init__.py", line 1321, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) _tkinter.TclError: expected integer but got "" 2 tests OK. 1 test failed: test_idle Tk version: 8.6.4 -- https://mail.python.org/mailman/listinfo/python-list
Python code written in 1998, how to improve/change it?
Hello, I am trying to study/understand OOP principles using Python. I have found following code http://tinyurl.com/a4zkn about FSM (finite state machine) on this list, which looks quite useful for my purposes. As this code was posted long time ago (November 1998) I would like to ask if the principles used in this code are still valid in the "modern" Python and if/how it can be improved (revrited) using futures of current version of Python. Thanks for your comments for a "newbie" and for your patience. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Python code written in 1998, how to improve/change it?
Thanks for your comments, The mentioned "8 years old" code actually works somehow. I am trying to solve very similar problem about FSM as the code in the example does and I do not want to be overburden by the if/elif stuff or by declaring state functions (which IMHO is very similar approach as if/elif). Because of above mentioned, something like FSM-generator looks as a way to go for me (if I can judge with my poor skills). I am using Steve's book "Python Web Programming" which is actually the best I have found about OOP, classes etc. but as a newbie I am just lost with subclass and mapping attributes etc. while trying to study the code in the example (http://tinyurl.com/a4zkn). All I wanted to know, if, thanks to the improvements in the Python functionality over the years, it is possible to simplify somhow the old code. Otherwise I have to dig through :) Petr Jakes PS: I agree and I do understand the reasons why NOT to use GOTO statements in the code (aka spaghetti code). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for Embedded Systems?
J> Is there a Python packaging that is specifically for J> embedded systems? ie, very small and configurable so the J> user gets to select what modules to install? J> For Linux-based embedded systems in particular? J> I'm thinking of running it on the Linksys's Linux-based open J> source router WRT54G. It has 4MB flash and 16MB RAM. I think J> another model has 16MB flash. Any possibilities of running J> Python on these systems? You can run Python on the NSLU2 (Slug) http://www.nslu2-linux.org/ sw packages: http://www.nslu2-linux.org/wiki/Unslung/Packages the best (IMHO) firmware: http://www.nslu2-linux.org/wiki/DebianSlug/HomePage -- http://mail.python.org/mailman/listinfo/python-list
technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation)
I have a standard 12-key mobile phone keypad connected to my Linux machine as a I2C peripheral. I would like to write a code which allows the text entry to the computer using this keypad (something like T9 on the mobile phones) According to the http://www.yorku.ca/mack/uist01.html dictionary-based disambiguation is coming in the mind. With dictionary-based disambiguation, each key is pressed only once. For example, to enter the, the user enters 8-4-3-0. The 0 key, for SPACE, delimits words and terminates disambiguation of the preceding keys. The key sequence 8-4-3 has 3 × 3 × 3 = 27 possible renderings (see Figure 1). The system compares the possibilities to a dictionary of words to guess the intended word. I would like to ask some guru here to give me the direction which technique (Python functionality) or which strategy to use to solve this riddle. Thanks for your advices and comments Regards Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: technique to enter text using a mobile phone keypad (T9 dictionary-based disambiguation)
Thanks a lot. It works flawlessly and I have learned few new Python "tricks" as well. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
what is the reasonable (best?) Exception handling strategy?
I am a little bit confused by all possibilities for exceptions handling in Python (probably because I am not skilled enough??) I did try to search trough this list and reading Python tutorial about Errors and Exceptions but didn't find some "general" answer about exception handling policy (strategy). In the following example each row can IMHO raise an exception (if the Firebird service is not running for example, if the database is corrupted etc.). Do I have to write "try/except" clause on each row? Or to write try/except block (function) where to handle (on one place) all exceptions expected in the program code is a good idea? Or do I have to write own "exception hook"? What about unexpected exceptions? :( def databasExample(h,d,u,p): import kinterbasdb; kinterbasdb.init(type_conv=200) con = kinterbasdb.connect(host=h, database=d,user=u, password=p) cur = con.cursor() insertStatement = cur.prep("some SQL statement..") cur.executemany(insertStatement, ListOfValues) con.commit() cur.close() Generally I am trying to find some general advices or suggestions about exception handling more than the specific answers to the above mentioned code example. Regards Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: what are you using python language for?
hacker1017 wrote: > im just asking out of curiosity. a vending machine controlled from the PC (peripherals connected using I2C bus (SMBus) and the MDB coin change-giver and the bill acceptor connected to the serial port). Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Most elegant way to generate 3-char sequence
sam wrote: > I have found that the more elegant the code is, the harder it is for me > to understand what it is trying to accomplish. It is my opinion that > "Keep It Simple" wins over elegance. When I have had the urge to get > elegant, I make sure I comment the elegance so my less elegant > co-workers can figure out what I was trying to accomplish. > > Sam Schulenburg +1 Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple Char-I/O Dialogs for Win32 and DOS
Mr Roboto wrote: > Folks: > > I've already searched the group and have determined there *are* > char I/O based input systems, ala NCURSES, that are > Python-compatible (ie. PyNCurses, UrWid, etc.) What I *need* is > something that does simple dialogs under char-I/O Win32 and DOS > w/ very little fuss or muss. At most, I need one or two dialog > boxes to boot my little app/util *AND* hope upon hope I don't > need port something (which would take more days than I have > *and* would also require a non-trivial support effort from a > one-man show: *me*) and can simply grab something (open-source) > off-the-shelf. I don't need a dialog/forms designer, no > database access, just a basic dialog box to get input from a > couple of text boxes, check boxes, etc. > > Does such an animal exist and can someone offer a link to the > kit ? TIAMR You can try: Dialog http://invisible-island.net/dialog/ HTH Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: break the loop in one object and then return
It smells like many student are trying to do their homework last few days here ... Can we now the name of your school? :) AFAIK this group does not solve homeworks here :) Just few points: at the beginning try to test the input value you can use "in range" or using "0 < yournum < 101" you should test if the input is an integer as well.. http://tinyurl.com/j468c Other suggested here which way to go. Good luck :) Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: break the loop in one object and then return
Alex Pavluck wrote: > Peter, Why do you make such claims without any reason to do so? This > is my own thing. So, I guess I am a student but just a student of my > own accord. So, please don't reply if you don't have anything to > contribute. First: This is not "YOUR OWN THING". This group really can help, but this group AFAIK does not write homeworks. It is nothing wrong you are just a student, we are all students somehow :) Second: Few other posters were posting similar requests to this group last few days (maybe your classmates :)) so the chance it just a coincidence is very low. If I am wrong, sorry about that. Third: This group can help, but some effort (study, googling this group etc.) on your side is necessary as well. Other posters suggested you the way, where to go, but you didn't try to change your code a bit. Please read the following as well: http://www.albion.com/netiquette/corerules.html To your code: > > As for the - mynum I guess that could happen but I am just doing this > so that they will never match on first try. I guess I should just > hardcode it. > > This is what happens if I step though: > > mynum = 93***1*** use # sign for your comments in the code followed by the comment text. All the stuff after the # is ignored when the code is executed. Nobody can execute (examine) your code whit your comments like ***1*** To hardcode "mynum" value is IMHO very bad idea and your code will be useless if the value will be "discovered". Other suggested how to generate random number at the beginning of the code. > yournum = input("I am thinking of a number between 1 and 100.\n Guess > which number: ") ***2*** > > def strt(): ***3******6*** > if yournum == mynum: ***7*** > print "Wow! You got it!" > elif yournum < mynum: ***8*** > print "Nope. Too low" ***9*** > again()***10*** ***15*** > elif yournum > mynum: > print "Oh, your too high" > > def again(): ***4*** ***11*** > global yournum ***12*** > yournum = input("guess again: ") ***13*** > strt() ***14*** > > strt() ***5*** > > > ***15*** is the problem. It doesn't start at the top but rather where > is leaves the loop. print statement can help to solve your problem, put it (with some text that will navigate you) on the rows where you are not sure the program is not running properly. Print out the values of the mynum and yournum as well. This will be just for your "debugging" purposes. Finally you will remove it. For example you can put: print "starting the strt function", "mynum = ", mynum, "yournum =", yournum on the first row of your strt function, so you will see the code is going through there. Finally: Try to thing what will happen if the person will input character rather than integer. Again: good luck in your effort Petr Jakes > > > > > > Petr Jakes wrote: > > It smells like many student are trying to do their homework last few > > days here ... Can we now the name of your school? :) > > > > AFAIK this group does not solve homeworks here :) > > > > Just few points: > > > > at the beginning try to test the input value > > you can use "in range" or using "0 < yournum < 101" > > > > you should test if the input is an integer as well.. > > http://tinyurl.com/j468c > > > > Other suggested here which way to go. > > > > Good luck :) > > > > Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
small inaccuracy in the logging module documentation (Python Library Reference)
Hi, I have found some inaccuracy in the Python Library Reference 6.29.5.4 TimedRotatingFileHandler (http://docs.python.org/lib/node349.html) 1) it is not really obvious from the documentation the "when" value has to be in the format "w0", "w1" ... "w6" if "Type of interval" is defined as a "week day" 2) next the documentation says: "If backupCount is non-zero, the system will save old log files by appending the extensions ".1", ".2" etc., to the filename" This is not really true, in this case. The extension is (depending on the "when" value): "timestamp" or "date+hour+minutes" or "date+hours" or "date". Regards Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
finding the last file created in a directory
Hello everyone, I have a repeatedly running process, which always creates a new logfile with an ending n+1. What I need is to find the last file, the one with highest number at the end. The problem is, that the max() method gives me a wrong answer. I tried to convert the items in my list into integers using int(), but that ends up with an error ValueError: invalid literal for int(): My code currently looks like this: def get_logfile(dir, file_name): new_file_name = file_name[:-3] + 'log' listing = glob.glob(dir + new_file_name + '*') numbers = [] for i in range(len(listing)): item = listing[i] numbers.append(item[len(dir) + len(new_file_name) + 1:]) return new_file_name + '.' + max(numbers) cheers Petr -- http://mail.python.org/mailman/listinfo/python-list
Re[2]: delete first line in a file
JH> this helps me! JH> thank you very much! JH> greetings, juergen I am happy to see my postings (which I sent by accident to you only, not to the list, see below) helped. But: Its a pity we can not see your solution (your code) here :( It helps to others as well to see, how to solve some "problems" Petr Jakes JH>> that documentation i have already read, but it wouldn`t help me for my JH>> problem! JH>> i know, how i can read the first line an print them on the screen! JH>> but...how can i say python, delete the first line?! JH>> thats my problem! PJ> as Fredrik told you, you can not delete the first line directly!!! JH>> in the entry of my posting i wrote, that i am a newbie and so please JH>> understand me, that i ask so questions?! :-) PJ> We are trying to understand that, but it is expected some effort on PJ> your side as well :) PJ> You didn't read the documentation properly! PJ> try to experiment with the code by yourself as well! PJ> Try: PJ> 1) open your file PJ> 2) use readlines() method PJ> which returns the list of ALL rows from the file and store them to some PJ> variable. PJ> it can be done for example like: PJ> all_lines = f.readlines() PJ> (if you do not know, what the list is, start here: PJ> http://docs.python.org/tut/node5.html#SECTION00514) PJ> 4) save the list members without its first member to the file PJ> for example: PJ> for line in all_lines[1:]: PJ> f.write(line) PJ> 5) close the file JH> Good luck JH> Petr Jakes JH>> thanks for your help! -- http://mail.python.org/mailman/listinfo/python-list
Re: I have 100 servers which need a new backup server added to a text file, and then the backup agent restarted.
g> This seems easy but I have been asking tcl and python IRC chat all day g> and no one gave an answer. g> I have 100 servers which need a new backup server added to a text file, g> and then the backup agent restarted. g> If I have a list of the servers, all with same root password, and the g> connection is ssh. g> How do I connect to the server, cat the line to the config file, stop g> adn start the agent, and then do same to next server in list and g> iterate through the 100 servers. g> What script would allow this? Maybe webmin could help. http://www.webmin.com/ You can manage cluster of servers at once. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re[2]: Can I do it using python?? about xterm and telnet
v> Thanks, v> But I need to to do complicated job in the xterm consoles for servers. what does it mean, complicated job? Can you be more specific, please? v> So I need v> to open many xterm consoles and I just want to save my time from v> telneting...usr/pwd... v> Network Ninja wrote: >> valpa wrote: >> > I'm a net admin for about 20 unix servers, and I need to frequently >> > telnet on to them and configure them. >> > It is a tiring job to open a xterm and telnet, username, password to -- http://mail.python.org/mailman/listinfo/python-list
Re: a question about "return"
"yaru22" wrote in message news:[EMAIL PROTECTED] > In one of the examples in the book I'm reading, it says: > > def __init__(self): > ... > return > > It has nothing after "return". I expected it to have some number like 0 > or 1. What does it mean to have nothing after return? Yes, it has some special value. The value is said to be None. Better to say -- the doc says: "None This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don't explicitly return anything. Its truth value is false. > Why do we even include "return" if we are not putting any value after? If you do not use return in your function, it is the same as if you used return without an argument at the end of the body. It will return None. If you use return, the function returns immediately to the caller. It need not to be the last command. You may want to return earlier. pepr -- http://mail.python.org/mailman/listinfo/python-list
Re: [noob question] References and copying
"zefciu" wrote in message news:[EMAIL PROTECTED] > Where can I find a good explanation when does an interpreter copy the > value, and when does it create the reference. I thought I understand > it, but I have just typed in following commands: > > >>> a=[[1,2],[3,4]] > >>> b=a[1] > >>> b=[5,6] > >>> a > [[1, 2], [3, 4]] > >>> b > [5, 6] > > And I don't understand it. I thought, that b will be a reference to a, > so changing b should change a as well. What do I do wrong. The assignment always copy the reference, never the value. After b=a[1] the b refers to the list object [3,4]. After b=[5,6] the earlier binding is forgotten, the new list with values [5,6] is created and the b is bound to the new list. But if you did b[0] = 5 b[1] = 6 then you would get the expected result. The reason is that b[0] is bound to 3 inside the big list refered by a, and it is rebound to 5. The suggested b[:] = [5, 6] is a shortcut for that (in fact, it is slighly more magical and powerful). > And a second question - can I create a reference to element of a list of > floating points and use this reference to change that element? No. Because the trivial types and also the string type are immutable (i.e. constant). The list would contain references to the constants. You cannot change the value of any constant. You have to replace the reference. Another possibility is to create your own class that will represent one floating point value but will be mutable. In other words, the object of your class will be a container (refered from the list) and its internal state--the floating number--will be changed using the method of the container. pepr -- http://mail.python.org/mailman/listinfo/python-list
import gtk RuntimeError: could not open display
Hi my script is working well when I am running it from the terminal window. While I am trying to start it as a Cron job, I am getting an Error described bellow: My configuration: Pentium III, Python 2.4.1, Fedora Core4 Thanks for your comments. Petr Jakes File "/root/eric/analyza_dat_TPC/htmlgenerator.py", line 7, in ? from pylab import * File "/usr/lib/python2.4/site-packages/pylab.py", line 1, in ? from matplotlib.pylab import * File "/usr/lib/python2.4/site-packages/matplotlib/pylab.py", line 219, in ? new_figure_manager, draw_if_interactive, show = pylab_setup() File "/usr/lib/python2.4/site-packages/matplotlib/backends/__init__.py", line 23, in pylab_setup globals(),locals(),[backend_name]) File "/usr/lib/python2.4/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in ? from backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\ File "/usr/lib/python2.4/site-packages/matplotlib/backends/backend_gtk.py", line 7, in ? import gtk; gdk = gtk.gdk File "/usr/lib/python2.4/__init__.py", line 37, in ? RuntimeError: could not open display -- http://mail.python.org/mailman/listinfo/python-list
unicode mystery/problem
Hi, I am using Python 2.4.3 on Fedora Core4 and "Eric3" Python IDE . Below mentioned code works fine in the Eric3 environment. While trying to start it from the command line, it returns: Traceback (most recent call last): File "pokus_1.py", line 5, in ? print str(a) UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in position 6: ordinal not in range(128) == 8< = #!/usr/bin python # -*- Encoding: utf_8 -*- a= u'DISKOV\xc1 POLE' print a print str(a) == 8< = Even it looks strange, I have to use str(a) syntax even I know the "a" variable is a string. I am trying to use ChartDirector for Python (charts for Python) and the method "layer.addDataSet()" needs above mentioned syntax otherwise it returns an Error. layer.addDataSet(data, colour, str(dataName)) Thanks for your comments Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re[2]: unicode mystery/problem
John, thanks for your extensive answer. >> Hi, >> I am using Python 2.4.3 on Fedora Core4 and "Eric3" Python IDE >> . >> Below mentioned code works fine in the Eric3 environment. While trying >> to start it from the command line, it returns: >> >> Traceback (most recent call last): >> File "pokus_1.py", line 5, in ? >> print str(a) >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xc1' in >> position 6: ordinal not in range(128) JM> So print a works, but print str(a) crashes. JM> Instead, insert this: JM>import sys JM>print "default", sys.getdefaultencoding() JM>print "stdout", sys.stdout.encoding JM> and run your script at the command line. It should print: JM> default ascii JM> stdout x in the command line it prints: * default ascii stdout UTF-8 JM> here, and crash at the later use of str(a). JM> Step 2: run your script under Eric3. It will print: JM> default y JM> stdout z in the Eric3 it prints: if the # -*- Eencoding: utf_8 -*- is set than: default utf_8 stdout unhandled AttributeError, "AsyncFile instance has no attribute 'encoding' " if the encoding is not set than it prints: DeprecationWarning: Non-ASCII character '\xc3' in file /root/eric/analyza_dat_TPC/pokus_1.py on line 26, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details execfile(sys.argv[0], self.debugMod.__dict__) default latin-1 stdout unhandled AttributeError, "AsyncFile instance has no attribute 'encoding' " JM> and then should work properly. It is probable that x == y == z == JM> 'utf-8' JM> Step 3: see below. >> >> == 8< = >> #!/usr/bin python >> # -*- Encoding: utf_8 -*- JM> There is no UTF8-encoded text in this short test script. Is the above JM> encoding comment merely a carry-over from your real script, or do you JM> believe it is necessary or useful in this test script? Generally, I am working with string like u'DISKOV\xc1 POLE' (I am getting it from the database) My intention to use >> # -*- Encoding: utf_8 -*- was to suppress DeprecationWarnings if I use utf_8 in the code (like u'DISKOV\xc1 POLE') >> >> a= u'DISKOV\xc1 POLE' >> print a >> print str(a) >> == 8< = >> >> Even it looks strange, I have to use str(a) syntax even I know the "a" >> variable is a string. JM> Some concepts you need to understand: JM> (a) "a" is not a string, it is a reference to a string. JM> (b) It is a reference to a unicode object (an implementation of a JM> conceptual Unicode string) ... JM> (c) which must be distinguished from a str object, which represents a JM> conceptual string of bytes. JM> (d) str(a) is trying to produce a str object from a unicode object. Not JM> being told what encoding to use, it uses the default encoding JM> (typically ascii) and naturally this will crash if there are non-ascii JM> characters in the unicode object. >> I am trying to use ChartDirector for Python (charts for Python) and the >> method "layer.addDataSet()" needs above mentioned syntax otherwise it >> returns an Error. JM> Care to tell us which error??? you can see the Error description and author comments here: http://tinyurl.com/ezohe >> >> layer.addDataSet(data, colour, str(dataName)) I have try to experiment with the code a bit. the simplest code where I can demonstrate my problems: #!/usr/bin python import sys print "default", sys.getdefaultencoding() print "stdout", sys.stdout.encoding a=['P\xc5\x99\xc3\xad','Petr Jake\xc5\xa1'] b="my nice try %s" % ''.join(a).encode("utf-8") print b When I run it from the command line i am getting: sys:1: DeprecationWarning: Non-ASCII character '\xc3' in file pokus_1.py on line 26, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details default ascii stdout UTF-8 Traceback (most recent call last): File "pokus_1.py", line 8, in ? b="my nice try %s" % ''.join(a).encode("utf-8") UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 1: ordinal not in range(128) JM> The method presumably expects a str object (8-bit string). What does JM> its documentation say? Again, what error message do you get if you feed JM> it a unicode object with non-ascii characters? JM> [Step 3] For foo in set(['x', 'y', 'z']): JM> Change str(dataName) to dataName.encode(foo). Change any debugging JM> display to use repr(a) instead of str(a). Test it with both Eric3 and JM> the command line. JM> [Aside: it's entirely possible that your problem will go away if you JM> remove the letter u from the line a= u'DISKOV\xc1 POLE' -- however if JM> you want to understand what is happening generally, I suggest you don't JM> do that] JM> HTH, JM> John -- http://mail.python.org/mailman/listinfo/python-list
Python language extension mechanism for Python 3000... Worth for PEP?
Do you think that the following could became PEP (pre PEP). Please, read it, comment it, reformulate it,... Abstract Introduction of the mechanism for language extensions via modules written using other languages. Extensions of Python could be done via special interpreter extensions. From Python sources, the special modules would look like other modules, with the Python API (the key feature from the Python interpreter's point of view). Inside the special modules, special language features could be implemented and would possibly be interpreted by a different interpreter (the key feature to please those who want to use some special extensions). The goal could be summarized as extension of the idea of writing modules in Python or in C languages. Other kind of modules could be introduced. Then Python would work not only as a glue for modules and utilities, but could also be the glue for different interpreters. Motivation Note: The idea emerged when looking at the video http://video.google.com/videoplay?docid=-6459339159268485356 and when thinking about it. The sequences from it will be referenced like [video 2:10 - 2:30]. I do not want to be the one of the group of the "everybody is the language designer" [video 25:47]. The goal is rather to bypas the problem mentioned in [video 25:35 - 27:50]. There are doubts whether some features should be added to Python 3000 or whether some features are to be removed. The goal is to get rid of the obsolete features but the contradictory goal is not to break the backward compatibility. [video 7:00 - 7:30 - 8:10 - 8:45] There are some group of users of Python with special interests or with some special tastes for programming styles. For example, some users like functional programming (lambda, reduce, map,...). They have expressed so eloquently their wishes that the Python 3000 is not to remove lambda. On the other hand, only the (current) simple form of lambda expressions will remain. [video 41:38 - 43:34] Possibly, the unpleased "functional" people would be pleased if they could write some modules with more powerful lambda that would be interpreted by some special extension of the Python language interpreter. The new, requested special features used only by minority of programmers (but not by the unimportant minority) could be implemented outside the core of the Python interpreter. Rationale To keep the (Python) language clean, it is a good idea to simplify the syntax as much as possible -- if it does not lead to the loss of the power. Some languages are better for some tasks. There will always be people that want to extend the core of the language to support their wishes. The extension of the language via special kinds of modules would not upset the pure Pythonistas and will please "the pure functional-languages followers", for example. There already is something similar available inside the Python interpreter: some modules are implemented in the C language. The key idea is that they offer the same kind of interface that the modules written in Python do. In some sense, Python interpreter is not interested in how the results from the function call are obtained (whether the content of the module must be processed by the Python interpreter or whether the binary code will do it). In some sense, the module written in C can be seen as using "no-interpreter extension". The idea of the module implementation language could be extended (generalized) from "Python or C" to "Python or C or Python-extension". The "Python extension" would be implemented and maintained separately and would not spoil the development of the core. Technically, the goal is to separate the core of the Python language from extensions that will be known in future. In some sense, the mechanism is the adapter to the something else to give it Python interface. The C/C++ would not be the only alternative to implement a module used from a Python script. If modules can be viewed as prefabricated building blocks for writing the Python programs, the interpreter extensions could be viewed as building blocks for the interpreter functionality. As modules, some interpreter extensions could be standard, some could even be considered built-in, some could be from third parties. Some interpreter extensions could be used as a testbed for adding new features: For example, pure UTF-16 sources could be preprocessed by some "experimental" interpreter extension to the form that could be consumed by the core interpreter. And one day, the UTF-8 or 8-bit with explicitly stated encoding can be transformed to the only modern UTF-16 representation that new sources should use. The designers of the core language may freely decide to change the internals if they provide the adapter via the extension.
writing serial port data to the gzip file
I am trying to save data it is comming from the serial port continually for some period. (expect reading from serial port is 100% not a problem) Following is an example of the code I am trying to write. It works, but it produce an empty gz file (0kB size) even I am sure I am getting data from the serial port. It looks like g.close() does not close the gz file. I was reading in the doc: Calling a GzipFile object's close() method does not close fileobj, since you might wish to append more material after the compressed data... so I am completely lost now... thanks for your comments. Petr Jakes snippet of the code def dataOnSerialPort(): data=s.readLine() if data: return data else: return 0 while 1: g=gzip.GzipFile("/root/foofile.gz","w") while dataOnSerialPort(): g.write(data) else: g.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: writing serial port data to the gzip file
Maybe I am missing something. Expect data is comming continually to the serial port for the period say 10min. (say form the GPS), than it stops for 1 minute and so on over and over. I would like to log such a data to the different gzip files. My example was written just for the simplicity (I was trying to demonstrate the problem, it was not the real code and I was really tired trying to solve it by myself, sorry for the bugy example) the better way how to write such a infinite loop can be probably: = 8< = g=0 x=0 while 1: if not g: x+=1 g=gzip.GzipFile("/root/foofile%s.gz" % x,"w") data=dataOnSerialPort() while data: myFlag=1 g.write(data) data=dataOnSerialPort(): else: if myFlag: g.close() pring g myFlag=0 But it looks like g.close() method does not close the file (while trying to print the g object, it still exists) > Your while loop is discarding result of dataOnSerialPort, so you're > probably writing empty string to the file many times. Typically this > kind of loop are implemented using iterators. Check if your s object > (is it from external library?) already implements iterator. If it does > then > > for data in s: > g.write(data) > > is all you need. If it doesn't, you can use iter to create iterator for > you: > > for data in iter(s.readLine, ''): > g.write(data) > > -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: writing serial port data to the gzip file
Hi Dennis, thanks for your reply. Dennis Lee Bieber napsal: > > def dataOnSerialPort(): > > data=s.readLine() > > Unless you are using a custom serial port module, that should be > s.readline() sorry for the typo > > > if data: > > return data > > else: > > return 0 > > This if statement is meaningless -- if "data" evaluates to false, > return a numeric value that evaluates to false. I see, it is OK just to return data (or an empty string "") > > > > > while 1: > > g=gzip.GzipFile("/root/foofile.gz","w") > > while dataOnSerialPort(): > > g.write(data) > > "data" is an uninitialized value here > > else: g.close() > > And what is the purpose of closing the file if you immediately turn > around and create it again (assuming gzip.GzipFile() behaves as open() > does, a mode of "w" means delete the old file and create a new one. > There is NO exit from the above. > > Since I can't read your mind with regards to some of your looping... > > s = ... #somewhere you had to open the serial port > > g = gzip.GzipFile("/root/foofile.gz", "w") > while True: > data = s.readline() > if not data: break > g.write(data) > g.close() what I am trying to say is g.close() does not close the g file (try to add the line "print g" after g.close()) Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: Python code written in 1998, how to improve/change it?
Sorry, I can't get in. Can you please show me, how to use your approach on the simple push/push ON/OFF button for example please? PS: seriously it is not a homework :) and I feel it like a shame I am asking such a simple questions :( States: ON, OFF Transition event: "push", "lift" transition diagram: = ___ lift | | _V___|__ ,->| ON|__ | || | lift | | push | | '--| OFF |<-' || ^ | |___|push -- http://mail.python.org/mailman/listinfo/python-list
Re: Python code written in 1998, how to improve/change it?
Sorry for the typo in my previous posting. Of course it has to be: simple liftt/push ON/OFF button -- http://mail.python.org/mailman/listinfo/python-list
Re: Python code written in 1998, how to improve/change it?
To provide some feedback I vould like to show the code which works fine for me as a FSM machine. As speed is not the crucial issue for my application, I have decided to use an approach showed in the Skip Montanaro's code. http://orca.mojam.com/~skip/python/fsm.py (it is using dictionary to store state/transition dependencies). Tanks to all for your previous postings. Petr Jakes State machine example, for the pull/push button mentioned earlier in this discussion thread class FSM: '''the "states" dictionary contains user defined "state/transition table" in the format: {'start_state': {'event': {'guard': ('action', 'end_state')}}, according to the actual "start_state", "event" and "guard" combination, the "execute" method reads the relevant "action" and "end_state" from the "states" dictionary, then executes "action" and setup "end_state" ''' def __init__(self): self.states = {} def add(self,start_state, event_trigger,event_guard, action,newstate): """add a new "state/transition" information to the state machine dictionary""" if self.states.has_key(start_state)== False : self.states[start_state]={} if self.states[start_state].has_key(event_trigger)== False : self.states[start_state][event_trigger]={} if self.states[start_state][event_trigger].has_key(event_guard)== False : self.states[start_state][event_trigger][event_guard]={} self.states[start_state][event_trigger][event_guard]=(action, newstate) def start(self, state): """set the start state""" self.state = state def execute(self, event,guard=None): '''according to the actual "start_state", "event" and "guard" combination read the relevant "action" and "end_state from the "states" dictionary, then execute "action" and setup "end_state" ''' action, end_state = self.states[self.state][event][guard] if action is not None: apply(action, (self.state, event)) self.state = end_state return '''actions they has to be executed while the event occurs''' def motor_off(state, input): print "pushing the switch to the OFF position" def motor_on(state, input): print "lifting the switch to the ON position" fsm = FSM() '''we have to define "state/transition table" first, wher state transitions are defined as: ('start_state', 'event', 'guard', 'action', 'end_state)''' fsm.add("ON","lift",None,None,"ON") fsm.add("ON","push",None,motor_off,"OFF") fsm.add("OFF","push",None,None,"OFF") fsm.add("OFF","lift",None,motor_on,"ON") fsm.start("ON") print "start state is", fsm.state events=("push","push","push","lift","lift","push","lift","push","lift","lift","lift","push","lift") for event in (events): fsm.execute(event) print "switch is ", fsm.state -- http://mail.python.org/mailman/listinfo/python-list
how to parse structured text file?
I have a file which contains data in the format shown in the sample bellow. How can I parse it to get following: (14,trigger,guard,do_action,15) Thanks a lot for your postings Petr Jakes type: 4 bgrColor: 255 255 255 fgrColor: 0 0 0 objId: 16 Num.Pts: 2 177 104 350 134 objStartId: 14 objEndId: 15 eventName: trigger eventCond: guard eventAction: do_action -- http://mail.python.org/mailman/listinfo/python-list
Re: how to parse structured text file?
Sorry I was not precise enough in my description. In the file, there is of course more sections starting with the keyword type: I would like to only analyze sections which start with the sequence: type: 4 Petr jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky regular expressions
try to google for "finit state machine" OR "state machine" OR FSM titles =["USELESS DATA","Request : Play", "USELESS DATA","Title: Beethoven's 5th", "USELESS DATA","Request : next","USELESS DATA", "Title: song# 2 ","USELESS DATA","Request : Play", "USELESS DATA","Title: Beethoven's 5th", "USELESS DATA","Request : next","USELESS DATA", "Title: song# 3 ","USELESS DATA","Request : Play"] for title in range(len(titles)): if titles[title][:6] =="Title:": x=1 try: while titles[title+x]!="Request : Play" and titles[title+x]!="Request : next": x+=1 pass print titles[title], titles[title+x] except IndexError: pass HTH Petr Jakes PS: just wonder why are you asking the same question in two different topics -- http://mail.python.org/mailman/listinfo/python-list
Re: What editor shall I use?
http://www.pspad.com/en/ Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
how to get function names from the file
I have got names of functions stored in the file. For the simplicity expect one row only with two function names: printFoo, printFOO In my code I would like to define functions and then to read function names from the file, so the functions can be executed in the order the function names are stored in a file. While trying to read the names from the file I am getting always "strings" and I am not able to execute them. I would like to write my code so it will look something like: def printFoo(): print "foo" def printFOO(): print "FOO" # here I would like to read the file with the function names sequences # and to create tuple which will contain the function names. # After that I would like to call functions from the tuple: functions=(printFoo, printFOO) for function in functions: function() Thanks for your postings Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: editor for Python on Linux
Endless stories about IDEs (try to browse through this discussion group first). Of course it depends about users personal needs and taste. So install them and try them (I know, it's really time consuming). I thing there is not the other way to decide which one is the best for YOU. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: how to break a for loop?
zero_list=[0,0,0,0,0,1,2,3,4] for x in range(len(zero_list)): if zero_list[x]!=0: break nonzero_list=zero_list[x:] print nonzero_list but some more "pythonic" solutions will be posted from other users I guess :) HTH Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyserial never read
Well, I think it is better to start with some simple code first. Try to read serial port and print it out. something like this could work: import serial s = serial.Serial(port=2,baudrate=38400, timeout=20) while 1: print s.readline() Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: pyserial
Few notes from the Python beginner :) HTH. I do not understand what do you mean by the expression: " I can read data without try and try again." Can you be more specific please. I do not understand what do you exactly mean. AFIK the pyserial is waiting while the data occur on the serial port (so called blocking read) so it is not necessary to do some "polling" (checking the serial port periodically) . Following snippets of code is running in infinitive loop, but it is not necessary too be worried about processor utilization because the readline waits for the data on the serial port and the code continues to run when data occurs or when timeout passes. import serial s = serial.Serial(port=0,baudrate=4800, timeout=20) while 1: line = s.readline() # byte = s.read(1) # or you can read No. of bytes according your needs Alternatively you can monitor buffer of the serial port and while data in it, you can read it. while fd.inWaiting() != 0: s.read(1) you can find plenty of examples about pyserial here http://tinyurl.com/p8tt5 What I am not able to figure out is why are you trying to print out input and output buffers (print self.ser.flushInput()) Does it print out something? Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: pyserial
I can recommend you to read pyserial documentation and look to the examples. Browsing through this discussion group can help you a lot as well. Generally if the timeout is set to 0 (zero) the code will wait and wait and wait till the data will arrive to the serial port (if there is not data on the serial port, you can wait "forever" and you can think your code is "frozen" :) ) Because of that, you can set the timeout, so after some time of waiting for the data (when the data do not arrive) the code continues on the next line. Try to experiment a little bit with some simple and short code first, so you will be able to understand how to communicate with the serial port. HTH Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Indentation Problems
Eric3 works great with spaces, tabs and even when imported code indentation is "mixed". I have got problems trying to import "mixed) code from other people. Settings > Preferences > Editor > General Tab width 8 Indentation width 4 (reasons why 8 and 4 are mentioned in previous postings in this thread) Than you can set the checkboxes: - Use tabs for indentation - Convert tabs upon open - Tab key indents - Auto indentation - Show Indentation Guides You can also see the different marks for tabs and for spaces in Eric3 (if set), so you will see, where is the problem in you code. My favorite options (I am trying to use spaces for indentation strictly) are: = - "Use tabs for indentation" - unchecked - "Convert tabs upon open" - checked = Because of that I am not getting to the troubles with indentation anymore. HTH Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: spliting on ":"
> I think you're getting caught by the classic and/or trap in Python, > trying to avoid using a simple if statement. What do you mean by "the classic and/or trap"? Can you give an example please? Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyserial again
Grant and Steve, I am wowed and amazed how supportive and helpful you (and other people in this group as well of course) are. Thanks. (sorry for OT) Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Graphing Utilities.
> A pslatex backend certainly would be interesting. A Gnuplot backend > would probably not be feasible. Does it expose its raw drawing operations? There is a patch [ 1027032 ] Connect gnuplot_x11 to exterior application window http://sourceforge.net/tracker/index.php?func=detail&aid=1027032&group_id=2055&atid=302055 which allows to "Connect gnuplot_x11 to exterior application window...". If you test it, please write a note there and the patch can go to cvs. --- PM -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and GUI
[EMAIL PROTECTED] wrote: > Just wondering on what peoples opinions are of the GUIs avaiable for > Python? > > All I am doing is prompting users for some data (listbox, radio > buttons, text box, ect...). Then I will have some text output, maybe > a scrolling text message as things are happening. > > I have some minor things I need to do, for example, if Checkbutton X > is clicked, I need to disable TextBox Y, and I would like to display > the scrolling text (output) > > Ultimately, is it worth downloading and learning some of the packages > avaiable for Python, or should I just stick to the Tkinter stuff that > is included. > > More specifically, has anyone used the Qt stuff for python, easy to > use? > There's PyQt thingy, imho very good and easy to learn/use, but still powerful. I've used it for a small gui-oriented project with almost no problems and it worked like a charm. However, sometimes I had troubles finding useful documentation for it. I've also tried to play with PyGTK, it's quite nice and easy (and you have the advantage of Glade), but I don't like GTK way of creating GUI. I haven't used Tkinter a lot, only looked at it. And I didn't like it much. I would really suggest PyQt. (with a big IMHO :) Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with PySMS
Maybe you can try python binding for gammu, which works great for me. HTH Petr Jakes http://cihar.com/gammu/python/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Catching a key press
On 23 ec, 14:23, westymatt <[EMAIL PROTECTED]> wrote: > linux primarily still a little lost in how to implementent this, > however I understand what you are saying. maybe you can use this: http://tinyurl.com/2zyfmw HTH Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
how to analyse music stream
On the local radio station here in the Czech they announced simple contest: If listeners will hear Elton John's Sacrifice followed immediately by Madonna's Frozen they have to call to the broadcasting. First caller will get some price. I am just thinking about the concept how to analyse music stream form the PC radio card to get the signal: "first tones of Frozen were played after Sacrifice, call to the studio" :-) Of course, the calling can be made by PC as well, but this is the easiest part of the task :) Thanks for your tips and comments Petr Jakes PS: both, Linux or Windows tips are welcome :-)) -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime.time() class - How to pass it a time string?
On 24 ec, 19:11, Robert Dailey <[EMAIL PROTECTED]> wrote: > Hi, > > I have a string in the following format: > > "00:00:25.886411" > > I would like to pass this string into the datetime.time() class and > have it parse the string and use the values. However, the __init__() > method only takes integers (which means I'd be forced to parse the > string myself). Does anyone know of a way I can make it use the > string? Thanks. http://pleac.sourceforge.net/pleac_python/datesandtimes.html the part "http://pleac.sourceforge.net/pleac_python/ datesandtimes.html" HTH Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: From D
On Jul 24, 10:10 am, Stargaming <[EMAIL PROTECTED]> wrote: > On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > > There are various things I like about the D language that I think Python > > too may enjoy. Here are few bits (mostly syntactical ones): > > > 1) (we have discussed part of this in the past) You can put underscores > > inside number literals, like 1_000_000, the compiler doesn't enforce the > > position of such underscores, so you can also put them like this: > > 1_00_000. You can put them in literals of decimals, binary, hex, etc. I > > think it's quite useful, because when in Python code I have a line like: > > for i in xrange(100): > > I need some time to count the zeros, because the lower levels of my > > visual systems can't count/group them quickly (perceptually). While in a > > syntax like: > > for i in xrange(1_000_000): > > my eyes help me group them at once. > > Sounds like a good thing to be but the arbitrary positioning doesnt make > any sense. Additionally, I'd suggest 10**n in such cases (eg. 10**6). > http://blogs.msdn.com/oldnewthing/archive/2006/04/17/577483.aspx Digits are grouped in 2s in India and in 4s in China and Japan. Regards, Leons Petrazickis http://lpetr.org/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Q: Cteni unicode retezcu ze souboru UTF-8 s BOM?
Ahoj všeci, Tak nějak prakticky poprvé se dostávám k tomu, jak přečíst unicode řetězce ze souboru, který je uložen ve formátu UTF-8 se signaturou na začátku (BOM). Nějak se mi nedaří. Mám takovýto soubor.txt v UTF-8 s BOM = První řádek. Druhý řádek. Třetí řádek. Příšerně žluťoučký kůň úpěl ďábelské ódy. = ... a pustím skript = import codecs f = codecs.open('soubor.txt', 'r', 'utf-8') for line in f: print repr(line) print line[1:] f.close() = Výsledek vypadá takto = C:\tmp>python a.py u'\ufeffPrvn\xed \u0159\xe1dek.\r\n' První řádek. u'Druh\xfd \u0159\xe1dek.\r\n' ruhý řádek. u'T\u0159et\xed \u0159\xe1dek.\r\n' řetí řádek. u'P\u0159\xed\u0161ern\u011b \u017elu\u0165ou\u010dk\xfd k\u016f\u0148 \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy.\r\n' říšerně žluťoučký kůň úpěl ďábelské ódy. = Všimněte si, že na prvním řádku je \ufeff, což je Byte Order Mark, který se tam vůbec nemá objevit. Jeví se mi to jako chyba. Na všech řádcích záměrně nevypisuji printem první znak, protože u toho prvního řádku to krachne (což je pochopitelné). Řešil někdo něco podobného? Musí se BOM ukousávat ve vlastní režii? Díky, pepr -- http://mail.python.org/mailman/listinfo/python-list
Sorry (was Re: Cteni unicode retezcu ze souboru UTF-8 s BOM?)
Sorry for the mess, The message should have been sent to the Czech Python mailing list. My fault. pepr "Petr Prikryl" wrote... > Ahoj všeci, > Tak nějak prakticky poprvé se dostávám k tomu, > jak přečíst unicode řetězce ze souboru, který > je uložen ve formátu UTF-8 se signaturou > na začátku (BOM). Nějak se mi nedaří. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with str()
"Alex Martelli" wrote > Steve Holden wrote: >... > > >> Get yourself a stuffed bear, and next time you have this kind of problem > > >> spend a few minutes explaining to the bear exactly how your program > > >> can't possibly be wrong. Works like a charm. > > > > > > A rubber ducky works much better for that, btw -- more easily washable > > > than a stuffed bear, for example. > > > > > But stuffed bears are so much more knowledgeable about the minutiae of > > software design. > > And yet, the key to Python's strength is duck typing -- if you can teach > the duck to type, you've got it made. ... and then (gradually) rather unrealistic communication dream called "Babylonian fish" can be replaced by slighly more realistic programmers dream called "Python language with natural language processing when programming" (buzzword DuckPython). -- http://mail.python.org/mailman/listinfo/python-list
Re: difference between class and static methods?
"John Salerno" wrote... [...] > So a class method is specifically for using the class name itself as an > object in the method? If that's the case, then it makes some sense now. > I guess the reason I didn't get it before is that this is a feature of > dynamic languages, right? And something that couldn't have been done in > C# anyway? Yes, almost. You can think about a class method as about something that can be called even if no object of that class was created. It can be called through the class name. But it can also be called through the instance (the object). On the other hand, the normal method can be called only through the object. It does not belong to the class -- see below. The class method has access to the class variables, but not to the instance variables (no instance may exists) -- not shown here. Try the following script (I have stored it as a.py) --- class C: def __init__(self): print 'Instance of the class C was created.' @classmethod def myClassMethod(cls): print 'myClassMethod called' def myMethod(self): print 'myMethod (i.e. the normal one) was called.' C.myClassMethod() obj = C() obj.myClassMethod() obj.myMethod() C.myMethod() # cannot be done, error. --- And run it C:\tmp>python a.py myClassMethod called Instance of the class C was created. myClassMethod called myMethod (i.e. the normal one) was called. Traceback (most recent call last): File "a.py", line 18, in ? C.myMethod() TypeError: unbound method myMethod() must be called with C instance as first argument (got nothing instead) pepr -- http://mail.python.org/mailman/listinfo/python-list
Re: BIOCHIP --->>> NO GOOD !!
rainbow.cougar wrote in message > okay wrote: > > To Archbishop Christodoulos Paraskevaides of the Greek Orthodox Church > > in Athens and Greece Archbishop, > > I talked with a Greek Orthodox believer in Australia and he told me two > > I'm thinking a list comprehension... Possibly some filter(map()) for the really orthodox believers... -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused by Python and nested scoping (2.4.3)
I have added some spaces guessing how the original was formatted. See the simplified example and the explanation below... "Sean Givan" wrote... > Hi. I'm new to Python [...] something strange. > This code: > > def outer(): > val = 10 > def inner(): > print val > inner() > outer() > > ..prints out the value '10', which is what I was expecting. > > But this code.. > def outer(): > val = 10 > def inner(): > print val > val = 20 > inner() > print val > outer() > > ..I expected to print '10', then '20', but instead got an error: > >print val > UnboundLocalError: local variable 'val' referenced before assignment. > > I'm thinking this is some bug where the interpreter is getting ahead of > itself, spotting the 'val = 20' line and warning me about something that > doesn't need warning. Or am I doing something wrong? The simplified example of both cases can be script a.py - val = 10 def myFunction(): print val myFunction() - In this case the val is not defined inside myFunction(); therefore, it is searched in the "upper level", above the function body. Such variable is called free variable. script b.py - val = 10 def myFunction(): print val val = 20 myFunction() - In this case the val is assigned inside the myFunction() and it is not marked to be global. In this case Python decides that it will be the local variable (cannot be free variable anymore). Python insists on fact that in one block the variable can be or free or locally bound, but not both. This is decided during the compilation of the module and it does not depend on whether val = 20 assignment precedes the print val command or not. It is decided that it will be local inside myFunction and then the print wants to use the variable that was not assingned yet. pepr P.S. I have just noticed that Terry Jan Reedy answered similarly. Never mind... Repeat, repeat, repeat until you know ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to append to a list twice?
"Fredrik Lundh" wrote: > Alex Martelli wrote: > > > > But of course that only does it once, and I don't want to have to copy > > > and paste the append line. Perhaps there's a better way than this. > > > > def makeseries(N): > > series = [N] > > append = series.append > > for tailer in xrange(N-1, -1, -1): > > append(tailer) > > append(tailer) > > But Now You've Violated The DRY Principle!!! Do you mean the "three times -1" in the xrange arguments? :-) pepr -- http://mail.python.org/mailman/listinfo/python-list
Re: Coming from delphi - looking for an IDE - willing to spend money
Eric3 is great IMHO. http://www.die-offenbachs.de/detlev/eric3.html -- http://mail.python.org/mailman/listinfo/python-list
Using Databases in Python
I would like to know if anybody can point me to the site, where it is possible to find the tutorial "Using Databases in Python" which is mentioned by Steve Holden here: http://tinyurl.com/ectj8 Thanks Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Databases in Python
I have got Steven's book of course (it is excellent IMHO). I was just thinking some new approaches can be found in the tutorial. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Databases in Python
Thank you very much, Steve. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
milliseconds are not stored in the timestamp KInterbasDB + Firebird
I am trying to insert "timestamp" to the Firebird database using standard library datetime module example given in the "KInterbasDB Usage Guide" http://tinyurl.com/mplo4 , section "Example Programs DATE/TIME/TIMESTAMP" Even timestamp has the correct format before inserting to the database (2006-26-2 17:25:34.940279 for example), milliseconds are not stored and the database returns (2006,26,2,17,25,34). I have made some Googling the whole afternoon to find if it is possible to configure Firebird or KInterbasDB, but no success. My environment: Fedora Core4, Firebird CS 1.5, Python 2.4.1, KInterbasDB 3.2b1 Thanks for your advices. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Polling from keyboard
I am using following code which I have found on http://www.ibiblio.org/obp/py4fun/ few months ago. It works well for my purposes. Another way is to use Curses library. HTH Petr Jakes #!/usr/local/bin/python # # t t y L i n u x . p y # # getLookAhead reads lookahead chars from the keyboard without # echoing them. It still honors ^C etc # import termios, sys, time if sys.version > "2.1" : TERMIOS = termios else : import TERMIOS def setSpecial () : "set keyboard to read single chars lookahead only" global oldSettings fd = sys.stdin.fileno() oldSettings = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~TERMIOS.ECHO# lflags new[3] = new[3] & ~TERMIOS.ICANON # lflags new[6][6] = '\000'# Set VMIN to zero for lookahead only termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new) def setNormal () : "restore previous keyboard settings" global oldSettings fd = sys.stdin.fileno() termios.tcsetattr(fd, TERMIOS.TCSADRAIN, oldSettings) def readLookAhead () : "read max 1 chars (arrow escape seq) from look ahead" return sys.stdin.read(1) -- http://mail.python.org/mailman/listinfo/python-list
Re: milliseconds are not stored in the timestamp KInterbasDB + Firebird
to provide feedback: David Rushby (the autor of the KInterbasDB) has solved the problem applying such a future in the code. Thank you David. snapshots: http://kinterbasdb.sourceforge.net/snapshots/3.2/kinterbasdb-3.2_pre_20060503.src.tar.gz http://kinterbasdb.sourceforge.net/snapshots/3.2/kinterbasdb-3.2_pre_20060503.win32-FB-2.0-py2.4.exe Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use python for this .. ??
Why using Python? What about? 1. Open Power Options in Control Panel. (Click Start, click Control Panel, and then double-click Power Options.) 2.Click the Hibernate tab, select the Enable hibernate support check box, and then click Apply. (If the Hibernate tab is unavailable, your computer does not support this feature.) then: 1: Click Start and Shut Down, 2: Point the standby button and maintain the shift key pushed, 3: A new hibernation button appears: click it while still holding the shift key: voila your PC will hibernate (it mens computer will save your current setting and will switch off). Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: eric3 3.9.0 released
I think you can get the answer on http://www.die-offenbachs.de/detlev/eric3-mailinglist.html rather then here. HTH Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
do "some action" once a minute
I would like to do "some action" once a minute. My code (below) works, I just wonder if there is some more pythonic approach or some "trick" how to do it differently. minutes=time.localtime()[4] while 1: min, sec = time.localtime()[4:6] if sec==0 and minutes!=min: # first occur of sec==0 only!! polling 10x a second minutes=min print "Eureca" time.sleep(0.1) Regards Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: do "some action" once a minute
Thanks for your comment. It is mainly English issue (I am not native English speaker). OK, to be more specific, I would like to run the code, when the value of seconds in the timestamp become say "00". The whole code will run in the infinitive loop and other actions will be executed as well, so it can not "sleep" for 60 seconds :). Regards Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
"Alex Martelli" wrote... > Joe Marshall wrote: >... > > If you language allows unnamed integers, unnamed strings, unnamed > > characters, unnamed arrays or aggregates, unnamed floats, unnamed > > expressions, unnamed statements, unnamed argument lists, etc. why > > *require* a name for trivial functions? Event the trivial function can have a name. Does it make the trivial function more understandable if I do not give a name? I understand what lambda means, but it is clearer for me to see something like (with more meaningful name than shown here): >>> def fn(x): ... return x + 5 and to use it like... >>> fn(3) 8 Still, I can anonymize it later, if I really need >>> a = [fn] or I can give it another name >>> z = fn In my opinion, the cry for lambda in Python comes from people used to functional languages, because they are not used to the procedural style and it does not fit them at the beginning. Frankly, functional style seems "more strange" to me (i.e. the counter example). Still, I do not say it is bad. But it never came to my mind to say "Please, rewrite the LISP so that it looked more like Pascal. I do not like the lambda." Also, Python is compiled (to bytecode), imperative language, and the form of definition of the chunks of code is more natural to the compiler and to the customs how the procedural program is written and how its parts are referenced and put together to form bigger chunks of code. > I think it's reasonable to make a name a part of functions, classes and > modules because they may often be involved in tracebacks (in case of > uncaught errors): to me, it makes sense to let an error-diagnosing > tracebacks display packages, modules, classes and functions/methods > involved in the chain of calls leading to the point of error _by name_. I agree with Alex here. I USUALLY do not need debugger, but sometimes it is exremely handy to discover what happens (through debugger or few print commands, its a matter of taste). And Python is very fine here: >>> dir(fn) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> fn.__name__ 'fn' and even the anonymized function still knows its original name and type >>> a[0].__name__ 'fn' >>> type(a[0]) If lambda functions in Python are tweaked internally into normal Python functions... >>> z = lambda x: x * 3 >>> dir(z) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> z.__name__ '' >>> type(z) ... what makes them better, than the named function? If I do not loose anything by simplification, I want to have it simpler. pepr -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
"Chris Uppal" wrote... > Alex Martelli wrote: > > > I think it's reasonable to make a name a part of functions, classes and > > modules because they may often be involved in tracebacks (in case of > > uncaught errors): to me, it makes sense to let an error-diagnosing > > tracebacks display packages, modules, classes and functions/methods > > involved in the chain of calls leading to the point of error _by name_. [...] > E.g. consider the Smalltalk code (assumed to be the body of a method): > > aCollection > do: [:each | > each > 0 ifTrue: [^ true]]. > ^ false. > > which iterates over a collection checking to see if any element is > 0. If so > then the method answers true ("^" -- spelled "return" in Java), otherwise it > answers false. In that code, > [^ true] > is syntactically and semantically an anonymous function, which is only invoked > if the antecedent is true (in point of fact the compiler inlines that function > away but I don't think that's relevant here). The passage beginning > [:each | ... > and reaching to the matching ] is also an anonymous function with one parameter > (each) which is applied to each element of the collection in turn. (In this > case it really is an anonymous function, even at the implementation level.) > What "name" would you give to either of them ? I don't believe that /any/ name > is possible, and certainly that no name is desirable. for element in aCollection: if element > 0: return True return False And adding "def test(aCollection):" does not make it more complex, in my opinion. And possibly, the chunk of code may be written in some other way, more Pythonically. Maybe the attempt to rewrite programs from other languages into Python and the effort to use the same "tricks" like in the original program, causes the cry for preserving lambda in future Python. pepr -- http://mail.python.org/mailman/listinfo/python-list
Re: A critic of Guido's blog on Python's lambda
"Chris Uppal" wrote: > Petr Prikryl wrote: > > > for element in aCollection: > > if element > 0: > > return True > > return False > > [I'm not sure whether this is supposed to be an example of some specific > language (Python ?) or just a generic illustration. I'll take it as the > latter, since it makes my point easier to express. I'll also exaggerate, just > a little...] Sorry, I do not know Smalltalk, but this was meant as the transcription of your... | E.g. consider the Smalltalk code (assumed to be the body of a method): | | aCollection | do: [:each | | each > 0 ifTrue: [^ true]]. | ^ false. into Python > But now, in order to hack around the absence of a sensible and useful > feature -- /only/ in order to do so -- you have added two horrible new > complications to your language. You have introduced a special syntax to > express conditionals, and (worse!) a special syntax to express looping. Not > only does that add a huge burden of complexity to the syntax, and semantics, of > the language (and, to a lesser extent, its implementation), but it also throws > out any semblance of uniformity. I guess that it is not me who is confused here. The subject clearly says that the thread is related to Python and to lambda supported by Python. It was only crossposted to other groups and I did not want to remove them -- other people may want to read the thread in the other newsgroups. So, I did not introduced any horible syntax, nor looping construct that would look strange to people used to classical procedural languages. The lambda syntax in Python is the thing that could be viewed as a complication, not the "for" loop or the "if" construction. If you take any English speaking human (even the non-programmer), I could bet that the Python transcription will be more understandable than your Smalltalk example. > E.g. in Java there's an unresolved, and irresolvable, tension between whether a > failing operation should return an error condition or throw an exception [...]. It is more a design problem than the language problem. And it is also the implementation problem (i.e. what is the price of exceptions in comparison with the other code). In Python, the exceptions are intesively used. > E.g. can you add three-way comparisons (less-than, same-as, greater-than to, > say, Python with corresponding three-way conditional control structures to > supplement "if" etc ? Are they on a semantic and syntactic par with the > existing ones ? In Smalltalk that is trivial (too trivial to be particularly > interesting, even), and I presume the same must be true of Lisp (though I > suspect you might be forced to use macros). Such built-in function already is in Python. But you could add it by hand if it were not: def cmp(x, y): if x < y: return -1 if x == y: return 0 return 1 and the "if" supplement (the "switch" or "case" command) could be replaced easily in Python using the hash-table (dictionary) structure. > I should say that if your example /is/ in fact Python, then I believe that > language allows fairly deep hooks into the execution mechanism, so that at > least the "for" bit can be mediated by the collection itself -- which is better > than nothing, but nowhere near what I would call "good". It is a dual point of view. Should the collection be passive data, or not? I believe that the "pure" object oriented view (there are no functions, only the object methods) is not very practical and does not reflect well the big part of the reality that is simulated by programs. Python and C++, for example, allow mixing functions and objects. You should try Python. The "for" construct iterates through a sequence or through all values of the generator, thus making the for loop much more generic than for example in C or other languages. Every language forms the way of thinking. Every language has its strong and weak points. Every language has its followers and haters. Not every language is practical enough to fly around the Earth in the space ship. pepr (Sorry for my broken English.) -- http://mail.python.org/mailman/listinfo/python-list
do something in time interval
I have infinitive loop running script and I would like to check something periodically after 5 seconds (minutes, hours...) time period (I do not mean time.sleep(5) ). Till now, I have following script, but I think there must be something more elegant. eventFlag = False while 1: time.sleep(0.01) seconds = time.time() if not int(seconds % (5)): if eventFlag: print "5 seconds, hurray" eventFlag = False else: eventFlag = True Best regards Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: do something in time interval
> > I am not an expert, but why not to use time.sleep(5)? > If you are using wxPython, you may also try wx.Timer, in which you could > set its interval. > > Thanks for your reply. During the 5s period my script has to do some stuff instead of sleeping. Thats why it runs in the loop and once in 5s period it has to trigger some other stuff(function, method, action) to do. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
fputs in tp_print crashes under Win32
Hello, my C++ extension crashes under Win32 when the tp_print is called. It crashes with both Python 2.5.2 and 2.6. The crash occurs in system32\ntdll.dll, with exception code 0xc005. I found out that this works fine: int ulonghandle_print(RtiULongHandleObject *v, FILE *fp, int flags) { fputc('c', stdout); return 0; } But this causes the error: int ulonghandle_print(RtiULongHandleObject *v, FILE *fp, int flags) { fputc('c', fp); // <-- "fp" instead of "stdout" return 0; } It occurs under Windows (XP SP2) only. Under Linux everything works fine. Do you have any idea what could be wrong? Thanks, Petr -- http://mail.python.org/mailman/listinfo/python-list
xml input sanitizing method in standard lib?
Hi, Is there some method provided in python standard library to sanitize strings used as input to xml documents? (=remove form-feeds and whatever else). I've searched docs and google, found only 4Suite project. I cannot rely on something not in standard lib, so I'm wondering if I've just overlooked something in the docs to this (imo) important task... Petr -- http://mail.python.org/mailman/listinfo/python-list
Re: xml input sanitizing method in standard lib?
Hi, > > Is there some method provided in python standard library to sanitize > > strings used as input to xml documents? (=remove form-feeds and whatever > > else). I've searched docs and google, found only 4Suite project. I > > cannot rely on something not in standard lib, so I'm wondering if I've > > just overlooked something in the docs to this (imo) important task... > > What do you mean by "sanitize strings used as input to xml > documents"? > Do you have a string that you're going to parse as an XML document? Either > it is valid XML, or not. I would not "sanitize" it, you risk changing the > data inside. Thanks for response and sorry for I wasn't clear first time. I have a heap of data (logs), from which I build a XML document using xml.dom.minidom. In this data, some xml invalid characters may occur - form feed (\x0c) character is one example. I don't know what else is illegal in xml, so I've searched if there's some method how to prepare strings for insertion to a xml doc before I start research on a xml spec and write such function on my own. Petr -- http://mail.python.org/mailman/listinfo/python-list
Socket and cycle problem
Hello, I am beginner but so I need help. I have small script for receive data from port 3883, but it print only once. import socket HOST = 'localhost' PORT = 3883 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) data = s.recv(2048) s.close() print 'receive data from server:', `data` So I try to write cycle to this script, like this: import socket HOST = 'localhost' PORT = 3883 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while 1: s.connect((HOST, PORT)) data = s.recv(2048) s.close() print 'receive data from server:', `data` But Python reporting: Traceback (most recent call last): File "C:\Documents and Settings\poupa\Plocha\TCP3.py", line 7, in s.connect((HOST, PORT)) File "", line 1, in connect File "C:\Python25\lib\socket.py", line 141, in _dummy raise error(EBADF, 'Bad file descriptor') error: (9, 'Bad file descriptor') Where is the mistake? I dont know. thaks for help Petr -- http://mail.python.org/mailman/listinfo/python-list