how to debug when "Segmentation fault"
Hello, my programm sometime gives "Segmentation fault" message (no matter how long the programm had run (1 day or 2 weeks). And there is nothing in log-files that can points the problem. My question is how it possible to find out where is the problem in the code? Thanks for any help. Python 2.2.3 FreeBSD -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
there are a lot of packeges under suspicion: cPickle, select, threading, logging, socket, struct Michael Ekstrand wrote: > On Tuesday 04 October 2005 11:13, Maksim Kasimov wrote: > >>my programm sometime gives "Segmentation fault" message (no matter >>how long the programm had run (1 day or 2 weeks). And there is >>nothing in log-files that can points the problem. My question is how >>it possible to find out where is the problem in the code? Thanks for >>any help. > > > What extension modules are you using? > > I've never seen "stock" Python (stable release w/ only included modules) > segfault, but did see a segfault with an extension module I was using > the other week (lxml IIRC, but I'm not sure). > > - Michael -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
yes, to generete core dump is the best way, but the command "$ ulimit -c 50" don't make python to generete core dump in the time of crush. I would like to know how to run python script so if it crushes than core dump will be genereted. Thanks Pierre Barbier de Reuille wrote: > Maksim Kasimov a écrit : > >>Hello, >> >>my programm sometime gives "Segmentation fault" message (no matter how >>long the programm had run (1 day or 2 weeks). And there is nothing in >>log-files that can points the problem. >>My question is how it possible to find out where is the problem in the >>code? Thanks for any help. >> >>Python 2.2.3 >>FreeBSD >> > > > Well, your best bet is to generate a core file ! > To do so, in the shell launching the program, you need to accept core > files. The command is : > > $ ulimit -c > > For example: > $ ulimit -c 50 > > For a 500MB max file. > > Then, if your program crash, you should see a file named "core." > where is the PID of the process. You can know exactly where the > program crashed using gbd : > > $ gdb --core=core. > > Then, depending on the debug information you have in your executables > you may (or may not) be able to know what happened :) > > Pierre -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to prevent logging warning?
may be this you will find usefull: def getLog(logName, fileName = None): if fileName: hdl = logging.FileHandler(fileName) else: hdl = logging.StreamHandler() fmt = logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s") hdl.setFormatter(fmt) log = logging.getLogger(logName) log.addHandler(hdl) return log Thomas Heller wrote: > I'm about to add some logging calls to a library I have. How can I > prevent that the script that uses the library prints > 'No handlers could be found for logger "comtypes.client"' when the > script runs? > > I would like to setup the logging so that there is no logging when > nothing is configured, and no warning messages are printed. > > Thomas -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
[EMAIL PROTECTED] wrote: > I've rewritten your middle example to be clearer. > $ python2.4 > Python 2.4.1 (#1, May 16 2005, 15:15:14) > [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>type("Y", (type,), {"mro": lambda x: [float]})("X", (), {}) on my machines: >>> type("Y", (type,), {"mro": lambda x: [float]})("X", (), {}) > > > and here's another one for you to enjoy: > >>>>import marshal >>>>f = lambda: None >>>>code = >>>>marshal.loads(marshal.dumps(f.func_code).replace('d\0\0S','d\xff\xffS')) >>>>f.func_code = code >>>>f() just no any output >>> dir(code) ['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__repr__', '__setattr__', '__str__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames'] Python 2.2.3 (#1, Oct 22 2004, 03:10:44) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
looks sad :( ok, until the decision not found, i've run my script (if someone have the same problem) using sh-script like this: #!/bin/sh while true do myscript.py echo "scrip was fault" | mail -s "run.sh" [EMAIL PROTECTED] done ... still works ;) Franz Steinhaeusler wrote: > Tamer, thanks for your tip. > > I tried Jeff's code: > > import marshal > f = lambda: None > code = > marshal.loads(marshal.dumps(f.func_code).replace('d\0\0S','d\xff\xffS')) > f.func_code = code > f() > > saved it as foo.py, than > > C:\Python24\Lib>gdb python > GNU gdb 5.1.1 (mingw experimental) > Copyright 2002 Free Software Foundation, Inc. > GDB is free software, covered by the GNU General Public License, and you > are > welcome to change it and/or distribute copies of it under certain > conditions. > Type "show copying" to see the conditions. > There is absolutely no warranty for GDB. Type "show warranty" for > details. > This GDB was configured as "mingw32"...(no debugging symbols found)... > (gdb) r foo.py > Starting program: C:\Python24/python.exe foo.py > > Program received signal SIGSEGV, Segmentation fault. > 0x1e027b23 in ?? () > (gdb) bt > #0 0x1e027b23 in ?? () > #1 0x00977240 in ?? () > #2 0x1e1a82b8 in ?? () > Cannot access memory at address 0x7 > (gdb) > > How can I interpret this results? ;) > > Am I right, that I need a debug build of python built with mingw or > cygwin in Windows? -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: can we save print msg into a file when script running ?
black wrote: > hi all~ > > in my .py file there are a few print to trace out some message and i > wonder if we can save it into a specified file when that script get > running. if so, i may just check that file to c how the script is > running. can anyone show me a right direction ? > > one million tks~ > script.py >> script.log 2>&1 -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select() on windows
you have to use non-block readining. http://docs.python.org/lib/module-select.html: A time-out value of zero specifies a poll and never blocks. jas wrote: > I am currently using subprocess to execute a command. Then I read from > it's stdout...however, this is hanging on a read..waiting for more > bytes. So what I would like is to timeout...and select.selec() seems > to be what I need. Except I don't have a socket, i have stdout. > > Any suggestions on how to do a timeout like select.select with stdout? > > Thanks > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle to source code
As far i know, in pickle-file there are only attributes values of a pickled object, but not an object itself. It is possible to unpickle object only if you have the sourse of the class that object you have pickled. So, if you have class code and attribute values of the class instance, there is no problem to produce a textual representation of the object. Isn't it? (sorry for my English) Gabriel Genellina wrote: > Hello > > I want to convert from pickle format to python source code. That is, > given an existing pickle, I want to produce a textual representation > which, when evaluated, yields the original object (as if I had > unpickled the pickle). > I know of some transformations pickle/xml (Zope comes with one such > tool, gnosis xml is another) so I believe I could build something based > on them. > But I dont want to reinvent the wheel, I wonder if anyone knows of a > library which could do what I want? > > Thanks, > Gabriel Genellina > Softlab SRL > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: select.select() on windows
yes, i missed, sorry Dennis Lee Bieber wrote: > On Wed, 26 Oct 2005 11:29:17 +0300, Maksim Kasimov > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > >>you have to use non-block readining. >> >>http://docs.python.org/lib/module-select.html: >>A time-out value of zero specifies a poll and never blocks. >> > > Did you miss the subject line... "... on windows"? select() only > works with sockets on windows, not on regular file streams. -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting a string into groups of three characters
import re str = '123456789983qw' re.findall("(.{3})", str)+[str[-(len(str) % 3):]] [EMAIL PROTECTED] wrote: > Hi, > > Is there a function that split a string into groups, containing an "x" > amount of characters? > > Ex. > TheFunction("Hello World",3) > > Returns: > > ['Hell','o W','orl','d'] > > > Any reply would be truly appreciated. > > Thank You, > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
don't understand instanse creation
Hello, i have a class, such as below. when i try to make instances of the class, fields __data1 and __data2 gets different values: __data1 behaves like private field, __data2 - like static which is the thing i've missed? thanks for help. import time class my: __data1 = [] __data2 = [] def __init__(self): print "__data1: ", self.__data1 print "__data2: ", self.__data2 for i in time.localtime(): self.__data2.append(i) self.__data1 = self.__data2[:] print "__data1: ", self.__data1 print "__data2: ", self.__data2 Python 2.2.3 FreeBSD >>> m1 = my.my() __data1: [] __data2: [] __data1: [2005, 8, 9, 16, 25, 18, 1, 221, 1] __data2: [2005, 8, 9, 16, 25, 18, 1, 221, 1] >>> >>> >>> m2 = my.my() __data1: [] __data2: [2005, 8, 9, 16, 25, 18, 1, 221, 1] __data1: [2005, 8, 9, 16, 25, 18, 1, 221, 1, 2005, 8, 9, 16, 25, 25, 1, 221, 1] __data2: [2005, 8, 9, 16, 25, 18, 1, 221, 1, 2005, 8, 9, 16, 25, 25, 1, 221, 1] -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: don't understand instanse creation
i see, thaks you very match! Dan Sommers wrote: > On Tue, 09 Aug 2005 16:39:51 +0300, > Maksim Kasimov <[EMAIL PROTECTED]> wrote: > > >>Hello, > > >>i have a class, such as below. >>when i try to make instances of the class, >>fields __data1 and __data2 gets different values: __data1 behaves like >>private field, __data2 - like static >>which is the thing i've missed? > > >>thanks for help. > > >> > > > >>import time >>class my: > > >> __data1 = [] >> __data2 = [] > > >> def __init__(self): > > >> print "__data1: ", self.__data1 >> print "__data2: ", self.__data2 > > >> for i in time.localtime(): >> self.__data2.append(i) > > > The above line changes the existing class attribute __data2, which is > shared by all instances of this class. > > >> self.__data1 = self.__data2[:] > > > The above line creates a new instance attribute __data1, and binds it to > a copy of __data2. > > >> print "__data1: ", self.__data1 >> print "__data2: ", self.__data2 > > > [ example snipped ] > > HTH, > Dan > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
logging into one file problem
hello in my modules, I'm using logging module, doing thus (there is a few modules): in module1.py: hdl = logging.StreamHandler() fmt = logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s") hdl.setFormatter(fmt) log = logging.getLogger('module1') log.addHandler(hdl) In script, which is uses these modules, I'm doing in a similar way: in script.py: hdl = logging.StreamHandler() fmt = logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s") hdl.setFormatter(fmt) log = logging.getLogger('script') log.addHandler(hdl) Than, to direct all output into one log-file I'm doing like this: script.py >> script.log 2>&1 All works as expected - all output in one file (script.log), but only until syslog will rotate script.log, than output to log-file stops. How to avoid this situation? i can't using something like this: hdl = logging.FileHandler('script.log') because modules are used in other scripts, and log output of each application must be in different files. and doing in script.py like this: module.hdl = hdl module.log = log will works, but it is very inconvenient, because in main script, i'm not importing all the modules (some modules imported by other modules). thanks for help. Python 2.2.3 FreeBSD -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
signal.SIGHUP handling
hi, please help to find out where is the problem: i'm trying to hadle signal.SIGHUP (in unix prompt: kill -HUP ) first of all, i'm trying to do: signal.signal(signal.SIGHUP, signal.SIG_IGN) - it works fine (signal ignored) but if use my handler, than it raises "Interrupted system call": # all i need to do it is reopen log-file. # It was opened at the time of pragramm start def myHandler(signum, frame): sys.stdout = sys.stderr = open("mylog.log", "a+") signal.signal(signal.SIGHUP, myHandler) -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
python equivalent of php implode
in php-scripts, to insert data to database, i'm doing like this: ... $query_param = array( 'field0' => 1, 'field1' => 3, 'field2' => $var2, 'field3' => $var3, ); ... $sql = "INSERT INTO $table (".implode(", ", array_keys($query_param)).") VALUES ('".implode("','", $query_param)."')"; how it can be done, using python (elegantly, without cycles)? -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: python equivalent of php implode
... but not in the case when integers are in a dictionary (please, try to execute your example by yourself first) "Ola Natvig" <[EMAIL PROTECTED]> wrote: news:[EMAIL PROTECTED] > Maksim Kasimov wrote: > > > > in php-scripts, to insert data to database, i'm doing like this: > > > > ... > > $query_param = array( > > 'field0' => 1, > > 'field1' => 3, > > 'field2' => $var2, > > 'field3' => $var3, > > ); > > ... > > > > $sql = "INSERT INTO $table (".implode(", ", > > array_keys($query_param)).") VALUES ('".implode("','", $query_param)."')"; > > > > how it can be done, using python (elegantly, without cycles)? > > > > > > sql = "INSERT INTO %s (%s) VALUES (%s)" % (table, ','.params.keys()), > ','.join(param.values())) > > should do the trick. > > > -- > -- > Ola Natvig <[EMAIL PROTECTED]> > infoSense AS / development -- http://mail.python.org/mailman/listinfo/python-list
Re: python equivalent of php implode
done. thanks Try another paramstyle (see http://python.org/peps/pep-0249.html), e. g. ",".join(["%s"] * len(keys)) ... instead of ",".join(["?"] * len(keys)) ... Peter -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Can .py be complied?
"Maurice LING" <[EMAIL PROTECTED]> wrote: news:[EMAIL PROTECTED] > If your application does not use any C modules, you can try to use > Jython instead. Program in python but use jythonc to convert it into > Java source files and package it into Java JAR files, then you will only > need to release the JAR files without needing to release your codes. using Jython will not helps to hide your sources - jar-files are also easy to decompile and to receive the source code (it will even looks like original). To avoid releasing your java-code (as far as it possible), the jar-files are also necessary for processing by obfuscators -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: interactive web graphics
java are also wide-spread browser plugin with interactive and multimedia capabilities, and java-applets can be written with python (jython) "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: news:[EMAIL PROTECTED] > you are after _might_ be done using macromedia flash - as that is a > wide-spread browser plugin with interactive and multimedia capabilities. > But how to do it in flash I've no idea - after all I'm a pythoneer. > > Alternatively, SVG might be an option - but I'm not sure if its mature and > powerful enough. > > -- > Regards, > > Diez B. Roggisch -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: large dictionary creation takes a LOT of time.
Kent Johnson wrote: Here is a little cleaner version. It takes about a second to run on my PC. What hardware are you running on? path = 'DonQuixote.txt' frequency = {} for line in open(path): for word in line.split(): if frequency.has_key(word): frequency[word] += 1 else: frequency[word] = 1 print len(frequency), 'words' Kent > for line in open(path): the line of your example raise another question: opened file will be read at once time, as method readlines() do, or it will be read line by line as method readline() do. as far i know, it is depends on implementation of method "__iter__" of the object that "open()" returns, so another question: where i can find such an information (about how does such a functions works)? -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: large dictionary creation takes a LOT of time.
sorry for my question, but i've read the documentation, and can't find where is the explanation of how it is exactly works (but of course i do believe you). If it is buit in function, can i see the source code of the method to find it out? Kent Johnson wrote: Maksim Kasimov wrote: Kent Johnson wrote: > for line in open(path): the line of your example raise another question: opened file will be read at once time, as method readlines() do, or it will be read line by line as method readline() do. It will be read line by line as readline() does. as far i know, it is depends on implementation of method "__iter__" of the object that "open()" returns, so another question: where i can find such an information (about how does such a functions works)? http://docs.python.org/lib/built-in-funcs.html http://docs.python.org/lib/bltin-file-objects.html Kent -- Best regards, Maxim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclassing socket
you have to agregate socket and the object must have "fileno" method, thats gives a possibility to use instanses of your class with "select.select" function class mySocket: def __init__(self, ...): self.__socket = None ... def fileno(self): return self.__socket.fileno() def connect(self, __host, __port): try: self.close() self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__socket.connect((__host, __port)) ... def close(self): try: if self.__socket is not None: self.__socket.close() finally: self.__socket = None ... [EMAIL PROTECTED] wrote: > socket objects have a little quirk. If you try to receive 0 bytes on a > blocking socket, they block. That is, if I call recv(0), it blocks > (until some data arrives). > > I think that's wrong, but I don't want to argue that. I would like to > create a subclass of socket that fixes the problem. Ideally, something > like: > > class new_socket(socket): > def recv( self, bufsize, flags=0 ): > if bufsize == 0: > return "" > else: > return socket.recv( bufsize, flags ) > > They only problem is, sockets return socket objects via the accept > call. And the socket returned is of type socket, of course, not > new_socket, as I would like. I could override accept() to return a > new_socket, but I don't know how to convert the old socket to a new > socket. That is, I'd like to add a method to the class above something > like: > > def accept( self ): > conn, addr = socket.accept() > > return ( conn, addr ) > > Does anyone have any suggestions on how to do the above? > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
BaseHTTPRequestHandler: how to read/write until diconnected
Hi, I'm trying to write an server-application, using BaseHTTPServer/BaseHTTPRequestHandler. When application is running, some client-application can post data to the server, and BaseHTTPRequestHandler reads all headers and posted raw data from "rfile", sends back response, than client/server session, than session closed - that works just fine. how to check whether some data posted again by the client in the session, and send response again in one session (and do such iterations util client stops to post data) ? something like this: class ServerChannel( BaseHTTPServer.BaseHTTPRequestHandler ): def do_POST(self): while needReadMessage: ... msg_count += 1 log.info( "message number %d arrived" % msg_count ) raw_post_data = self.rfile.read( contentLength ) ... self.wfile.write( respContent ) many thanks for help. -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
How set the source IP adress
Hi, how to set source ip-address when do __socket.connect((host, port)) on a machine that have a several ip-adresses? many thanks for advice. __socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) __socket.connect((host, port)) -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterating over several lists at once
Hi, if you "needs to iterate over 3 lists at the same" and according your example > for (x1,x2,x3) in (l1,l2,l3): > print "do something with", x1, x2, x3 i has guessed that you need this (may be i was wrong): a = (1,2,3, 1) b = (4,5,6) c = (7,8,9, 2, 3) for x, y, z in zip(a, b, c): print x, y, z or this for x, y, z in map(None, a, b, c): print x,y,z Try both examples with tuples that have various length, they have difference Gal Diskin wrote: > Hi, > I am writing a code that needs to iterate over 3 lists at the same > time, i.e something like this: > > for x1 in l1: > for x2 in l2: > for x3 in l3: > print "do something with", x1, x2, x3 > > What I need to do is go over all n-tuples where the first argument is > from the first list, the second from the second list, and so on... > > > I was wondering if one could write this more easily in some manner > using only 1 for loop. > What I mean is something like this: > > for (x1,x2,x3) in (l1,l2,l3): > print "do something with", x1, x2, x3 > > Or maybe like this: > > for x1 in l1, x2 in l2, x3 in l3: > print "do something with", x1, x2, x3 > > However, this code obviously doesn't work... > > > I'd be very happy to receive ideas about how to do this in one loop and > with minimal initialization (if at all required). > > Thanks in advance, > Gal > -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: How to manage two (different) sockets without using threads?
Hi, i don't know how to do it with asyncore/asynchat, but it is possible to handle different sockets in one process by using "select" standard module: for_reading, for_writing, where_errors =\ select.select( ( ), ( ), (), 0) you can find all necessary information in python documentation: http://www.python.org/doc/2.4/lib/module-select.html btw: "asyncore" use "select" for socket handling, take a look in asyncore.py hope it helps billie wrote: > Hi all. > I'm (re)writing an FTP server application by using asyncore/asynchat > modules. > FTP tipically got two different channels: command and data. > I'm succesfully managing command channel through asynchat framework, > but I'm not sure about how to manage data channel without using a > thread/subprocess. > Is there an optimal to do that? > Can anyone point me in the right direction? > -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: Non greedy regex
> print re.sub( 'a.*?b', '', 'ababc' ) > > gives: 'c' you've forgot "^" at the begging of the pattern (there is another 'ab' before 'c') print re.sub( '^a.*?b', '', 'ababc' ) [EMAIL PROTECTED] wrote: > Can someone please explain why these expressions both produce the same > result? Surely this means that non-greedy regex does not work? > > print re.sub( 'a.*b', '', 'ababc' ) > > gives: 'c' > > Understandable. But > > print re.sub( 'a.*?b', '', 'ababc' ) > > gives: 'c' > > NOT, understandable. Surely the answer should be: 'abc' > -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ possible loop
[EMAIL PROTECTED] wrote: > I have tried this, with Psyco it segfaults, and with Python 2.5 (on > Win) hangs the interpreter, is it possible to improve the situation? > > class T(object): > def __getattr__(self, x): dir(self) > #import psyco > #psyco.full() > T().method() > > (Probably dir calls __getattr__). > > Bye, > bearophile > how to improve the situation depends on what do you expect to get by calling "T().method()" dir calls __getattr__ with the value '__members__', for example you can write: def __getattr__(self, x): if x == '__members__': return ('method1', 'field1', ) -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ possible loop
[EMAIL PROTECTED] wrote: > Maksim Kasimov: >> how to improve the situation depends on what do you expect to get by calling >> "T().method()" > > You are right, sorry for being cryptic. I think that's a kind of bug of > Python (produced maybe by an infinite loop), so an improvement can be a > traceback or some automatic breaking of that loop. Note that my problem > comes from using Psyco that segfaults in that situation (if you have > Psyco installed you can decomment two lines to see that). I think that > using normal code Python+Psyco don't have to segfault, but I know this > is tricky situation, so if no simple "solutions" can be found, then > it's not a important thing and it can be ignored. > > Bye, > bearophile > it is neither a bug of python neither it comes from using Psyco, the problem is here: def __getattr__(self, x): dir(self) the "__getattr__" method calls "dir", but then "dir" calls "__getattr__" method of the object (self) - it makes endless loop (see the code in my previous message) -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ possible loop
Chris Mellon wrote: > > Nothing so clever. dir() eats and ignores all exceptions, so when you > hit the recursion limit it eats the RecursionLimitExceeded exception > and continues merrily along the way. This is probably not good > behavior... > > class Foo: >def __getattr__(self, attr): >raise SystemExit, "Don't call me, again, ever" > > f = Foo() > f.method() #dies correctly > dir(f) #continues happily can't understand - what kind of problem you tried to fix in that way? if __getattr__ just raise some exception, it needless to define it at all. -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: Manipulating mailboxes
change header information, insert messages into a database, delete/add messages, should not store passwords for all users, ... and any things else you wish to do - if your OS is UNIX - just forward mail messages of some users to your python script (you don't need to write a daemon for this) All you need is to place file ".forward" in users home directory, and write like this: |/path/myscript.py and chmod the script: chmod 777 /path/myscript.py Laszlo Zsolt Nagy wrote: > > Hi All, > > I need to create a daemon that sits on a server and forwards some > e-mails. (Well not only that, it needs to change header information > before forwarding and also insert messages into a database). The mailbox > module is fine but I do not see a way to delete/add messages - it is > ready only. The other possiblity is IMAP4 but it is bad because my > program should not store passwords for all users. I can only see one > solution right now: > > 1. Make a copy of the mailbox > 2. Truncate the mailbox > 3. Process the messages in the copy and forward the e-mails by sending > out real e-mails. > > But this looks so clumsy. Is there a way to delete/add messages to > mailboxes of different users, directly? > > Thanks, > > Laci 2.0 > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how to import a module from a arbitraty path?
Andy Leszczynski wrote: > I have a program which is going to dynamicly load components from some > arbitrary defined paths. How to do that? > > A. import sys sys.path.append('/yourpath/libs') -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
date and time range checking
there are few of a time periods, for example: 2005-06-08 12:30 -> 2005-06-10 15:30, 2005-06-12 12:30 -> 2005-06-14 15:30 and there is some date and time value: 2005-06-11 12:30 what is the "pythonic" way to check is the date/time value in the given periods range? something like xrange: >>> a = xrange(1,5) >>> b = 3 >>> if b in a: ... print "OK" thanks -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
different time tuple format
hi all, sorry if i'm reposting why time.strptime and time.localtime returns tuple with different DST (9 item of the tuple)? is there some of setting to fix the problem? Python 2.2.3 (#1, May 31 2005, 11:33:52) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.strptime("2005-06-07 21:00:00", "%Y-%m-%d %H:%M:%S") (2005, 6, 7, 21, 0, 0, 6, 1, 0) >>> time.localtime() (2005, 6, 7, 21, 2, 39, 1, 158, 1) >>> -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: different time tuple format
Rick Holbert wrote: > Like the last poster said, use %Z. On my Mandriva Linux system I get the > following results: > > >>>>time.localtime() > > (2005, 6, 7, 15, 7, 12, 1, 158, 1) > >>>>time.strptime("2005-06-07 15:07:12 EDT", "%Y-%m-%d %H:%M:%S %Z") > (2005, 6, 7, 15, 7, 12, 1, 158, 1) does not work at all: "ValueError: format mismatch" i've check the value of time.tzname: ('EET', 'EEST') and get the following (again): >>> time.strptime("2005-06-07 15:07:12 EET", "%Y-%m-%d %H:%M:%S %Z") (2005, 6, 7, 15, 7, 12, 6, 1, 0) -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: different time tuple format
seems like it is not a platform specific, i think to solve the problem i need put settings in order (in php it is php.ini file) thus i'll have a portable code. i've check the following code on my various servers, and it gives me different results: import time time.tzname time.daylight time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") time.strptime("2005-06-07 15:07:12 EEST", "%Y-%m-%d %H:%M:%S %Z") Python 2.3.3 (#1, Feb 28 2004, 20:35:22) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('EET', 'EEST') >>> time.daylight 1 >>> time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") (2005, 6, 7, 15, 7, 12, 1, 158, -1) >>> time.strptime("2005-06-07 15:07:12 EEST", "%Y-%m-%d %H:%M:%S %Z") (2005, 6, 7, 15, 7, 12, 1, 158, 1) Python 2.2.3 (#1, Oct 22 2004, 03:10:44) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('EET', 'EEST') >>> time.daylight 1 >>> time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") (2005, 6, 7, 15, 7, 12, 6, 1, 0) >>> time.strptime("2005-06-07 15:07:12 EEST", "%Y-%m-%d %H:%M:%S %Z") (2005, 6, 7, 15, 7, 12, 6, 1, 1) [EMAIL PROTECTED] wrote: > In your case it is the EEST, as this is the DST timezone (see again: > http://docs.python.org/lib/module-time.html) > > ** [EMAIL PROTECTED]:~ $ python > ** Python 2.4.1 (#2, Mar 30 2005, 21:51:10) > ** [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 > ** Type "help", "copyright", "credits" or "license" for more > information. > ** >>> import time > ** >>> print time.tzname > ** ('CET', 'CEST') > ** >>> time.strptime("2005-06-07 15:07:12 CET", "%Y-%m-%d %H:%M:%S %Z") > ** (2005, 6, 7, 15, 7, 12, 1, 158, 0) > ** >>> time.strptime("2005-06-07 15:07:12 CEST", "%Y-%m-%d %H:%M:%S > %Z") > ** (2005, 6, 7, 15, 7, 12, 1, 158, 1) > ** >>> > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: different time tuple format
yes, i agree, on my WinXP it gives another values. but my question is how to setup the python (or OS) to make it gives the same results when i call time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") on various servers (and maybe with various OS)? for now, i can't get it even with the same OS. and i would like to set time string exactly as "2005-06-07 15:07:12", without "CEST", "EEST" and so on, because as you've notice before, it is different on a variuos systems [EMAIL PROTECTED] wrote: > The names are at least platform specific, see below the names of the > timezones on my Windows NT 4 box > > *** Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit > (Intel)] on win32 > *** Type "help", "copyright", "credits" or "license" for more > information. > *** >>> import time > *** >>> print time.tzname > *** ('W. Europe Standard Time', 'W. Europe Daylight Time') > *** >>> > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: different time tuple format
maybe you are right, i've searched in google groups - such a question was posted to comp.lang.python many times and i has not found (yet) the answer on "how to tune up the output of time.strptime()?" [EMAIL PROTECTED] wrote: > It is probably the best to calculate back to UTC. > > Assume "2005-06-07 15:07:12" the local time, then convert it as > follows to UTC. Use the UTC time to store/manipulate/whatever you want > to do. > > import time > t = time.mktime(time.strptime("2005-06-07 15:07:12", "%Y-%m-%d > %H:%M:%S")) > > print time.ctime(t) > > offset = time.timezone > if time.daylight: > offset = time.altzone > t += offset > print time.ctime(t) > -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: just a bug
Carsten Haese: > On Fri, 2007-05-25 at 04:03 -0700, sim.sim wrote: > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 176-177: > invalid data >>>> iMessage[176:178] > '\xd1]' > > And that's your problem. In general you can't just truncate a utf-8 > encoded string anywhere and expect the result to be valid utf-8. The > \xd1 at the very end of your CDATA section is the first byte of a > two-byte sequence that represents some unicode code-point between \u0440 > and \u047f, but it's missing the second byte that says which one. in previous message i've explain already that the situation widely appears with memory limited devices, such as mobile terminals of Nokia, SonyEriccson, Siemens and so on. and i've notice you that it is a part of a splited string. Splited content it is a _standard_ in mobile world, and well described at http://www.openmobilealliance.org and is _not_ contradicts xml-spec. the problem is that pyexpat works _unproperly_. > > Whatever you're using to generate this data needs to be smarter about > splitting the unicode string. Rather than encoding and then splitting, > it needs to split first and then encode, or take some other measures to > make sure that it doesn't leave incomplete multibyte sequences at the > end. > > HTH, > -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: just a bug
[EMAIL PROTECTED] : > You need to explicitly convert the string of UTF8 encoded bytes to a > Unicode string before parsing e.g. > unicodestring = unicode(encodedbytes, 'utf8') it is only a part of a string - not hole string, i've wrote it before. That meens that the content can not be converted to unicode until reciever program will get all parts of the utf-string from sender. the xml in iMessage is absolutely correct. Please read my previous posts. thanks. -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: just a bug
Richard Brodie пишет: > "Neil Cerutti" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >> Web browsers are in the very business of reasonably rendering >> ill-formed mark-up. It's one of the things that makes >> implementing a browser take forever. ;) > > For HTML, yes. it accepts all sorts of garbage, like most > browsers; I've never, before now, seen it accept an invalid > XML document though. > > I do not think, that will be constructive to discuss correctness of work Mozilla insted to notice me on a contradiction in my message. Isn't it. Try to browse any file with garbage with "xml" extension. If you do, then you will see error message of XML-parser. I insist - my message is correct and not contradicts no any point of w3.org xml-specification. -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: just a bug
Jarek Zgoda: > > No, it is not a part of string. It's a part of byte stream, split in a > middle of multibyte-encoded character. > > You cann't get only dot from small letter "i" and ask the parser to > treat it as a complete "i". > ... i know it :)) can you propose something to solve it? ;) -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: just a bug (done)
Carsten Haese: > If you want to convey an arbitrary sequence of bytes as if they were > characters, you need to pick a character encoding that can handle an > arbitrary sequence of bytes. utf-8 can not do that. ISO-8859-1 can, but > you need to specify the encoding explicitly. Observe what happens if I > take your example and insert an encoding specification: > >>>> iMessage = '\n\n > \n\n\n' >>>> minidom.parseString(iMessage) > > > Of course, when you extract your CDATA, it will come out as a unicode > string which you'll have to encode with ISO-8859-1 to turn it into a > sequence of bytes. Then you add the sequence of bytes from the next > message, and in the end that should yield a valid utf-8-encoded string > once you've collected and assembled all fragments. > > Hope this helps, > Hi Carsten! Thanks for your suggestion - it is possible to fix the problem in that way. BTW: i've found an "xmlproc" and use to try to parse with commandline tool xpcmd.py it gives me "Parse complete, 0 error(s) and 0 warning(s)" I did not pick a character encoding "ISO-8859-1" (but using the lib it is another problem: to recode/retest/redoc/re* a lot of things) the project homepage: http://www.garshol.priv.no/download/software/xmlproc/ and another thing: I've open my xml-message in Mozilla again, in pop-up menu select "Page info" item, it shows me: Content-Type: text/xml Encoding: UTF-8 Many thank for your attention and patience! -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
is it bug or feature in xml.dom.minidom?
Hi, i'm faced with such a problem when i use xml.dom.minidom: to append all child nodes from "doc" in "_requ" to "doc" in "_resp", i do the following: _requ = minidom.parseString("OneTwo") _resp = minidom.parseString("") iSourseTag = _requ.getElementsByTagName('doc')[0] iTargetTag = _resp.getElementsByTagName('doc')[0] # it prints me that there are two child nodes for iChild in iSourseTag.childNodes: print iChild.toxml() # when i walk elements, only first iteration was made # and iSourseTag.childNodes now have only one element instead of two for iChild in iSourseTag.childNodes: iTargetTag.appendChild(iChild) # it prints me that there is only one child node for iChild in iSourseTag.childNodes: print iChild.toxml() i'm not sure, whether i append child nodes in properly way, but IMHO it looks like a bug. My question is how to avoid the "iSourseTag" changes while iterate its nodes? And, of course, how to append all child nodes to "iTargetTag"? Thank for any help. -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
__getattr__ equivalent for a module
Hi, in any python class it is possible to define __getattr__ method so that if we try to get some value of not actually exists instance attribute, we can get some default value. For example: class MyClass: def __getattr__(self, attname): if attname.startswith('a'): return "*" i = MyClass() ... i.aValue # it gives "*" if "i.aValue" will not be set before this call i need to define the same behavior for a module: import mymodule mymodule.anyattribute or from mymodule import anyattribute "anyattribute" is not actually defined in the module, but gives some attribute of the module so my question is: how to tune up a module get default attribute if we try to get access to not actually exists attribute of a module? (python 2.4 or 2.2) many thanks for help. -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list
Re: __getattr__ equivalent for a module
Hi Leif, many thanks - it works Leif K-Brooks wrote: > Maksim Kasimov wrote: >> so my question is: how to tune up a module get default attribute if we >> try to get access to not actually exists attribute of a module? > > You could wrap it in an object, but that's a bit of a hack. > > import sys > > class Foo(object): > def __init__(self, wrapped): > self.wrapped = wrapped > > def __getattr__(self, name): > try: > return getattr(self.wrapped, name) > except AttributeError: > return 'default' > > sys.modules[__name__] = Foo(sys.modules[__name__]) -- Maksim Kasimov -- http://mail.python.org/mailman/listinfo/python-list