which is more 'pythonic' / 'better' ?
hi, there are 2 versions of a simple code. which is preferred? === if len(line) >= (n+1): text = line[n] else: text = 'nothing' === === try: text = line[n] except IndexError: text = 'nothing' === which is the one you would use? thanks, gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: which is more 'pythonic' / 'better' ?
Terry Reedy wrote:
> "Will McGugan" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>
>>You may be right. I always use plural nouns for collections.
>
>
> ditto
>
>>To me 'line' would suggest there was just one of them,
>>so I assumed it was string.
>
>
> I did too.
>
i'm sorry ;) it was a list of strings...
the code was something like:
for line in open('x.y'):
line = line.split('\t')
a better naming would be better it seems :)
gabor
--
http://mail.python.org/mailman/listinfo/python-list
new-style classes, __hash__. is the documentation wrong?
hi, if you have a new-style class, it will have a __hash__ method, even if you don't define it, because it inherits from object(). and, if you implement __eq__, then that default-hash-value will be probably wrong. i understand that this is a bug, and described here: http://www.python.org/sf/660098 but please look at the documentation about __hash__ here: http://docs.python.org/ref/customization.html it says: If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since the dictionary implementation requires that a key's hash value is immutable (if the object's hash value changes, it will be in the wrong hash bucket). now, with new style classes, the class will have __hash__, whatever i do. (well, i assume i could play with __getattribute__...). so is that part of the documentation currently wrong? because from what i see (the bug will not be fixed), it's still much safer to define a __hash__ even for mutable objects (when the object also defines __eq__). gabor -- http://mail.python.org/mailman/listinfo/python-list
os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
hi,
from the documentation (http://docs.python.org/lib/os-file-dir.html) for
os.listdir:
"On Windows NT/2k/XP and Unix, if path is a Unicode object, the result
will be a list of Unicode objects."
i'm on Unix. (linux, ubuntu edgy)
so it seems that it does not always return unicode filenames.
it seems that it tries to interpret the filenames using the filesystem's
encoding, and if that fails, it simply returns the filename as byte-string.
so you get back let's say an array of 21 filenames, from which 3 are
byte-strings, and the rest unicode strings.
after digging around, i found this in the source code:
> #ifdef Py_USING_UNICODE
> if (arg_is_unicode) {
> PyObject *w;
>
> w = PyUnicode_FromEncodedObject(v,
> Py_FileSystemDefaultEncoding,
> "strict");
> if (w != NULL) {
> Py_DECREF(v);
> v = w;
> }
> else {
> /* fall back to the original byte string, as
>discussed in patch #683592 */
> PyErr_Clear();
> }
> }
> #endif
so if the to-unicode-conversion fails, it falls back to the original
byte-string. i went and have read the patch-discussion.
and now i'm not sure what to do.
i know that:
1. the documentation is completely wrong. it does not always return
unicode filenames
2. it's true that the documentation does not specify what happens if the
filename is not in the filesystem-encoding, but i simply expected that i
get an Unicode-exception, as everywhere else. you see, exceptions are
ok, i can deal with them. but this is just plain wrong. from now on,
EVERYWHERE where i use os.listdir, i will have to go through all the
filenames in it, and check if they are unicode-strings or not.
so basically i'd like to ask here: am i reading something incorrectly?
or am i using os.listdir the "wrong way"? how do other people deal with
this?
p.s: one additional note. if you code expects os.listdir to return
unicode, that usually means that all your code uses unicode strings.
which in turn means, that those filenames will somehow later interact
with unicode strings. which means that that byte-string-filename will
probably get auto-converted to unicode at a later point, and that
auto-conversion will VERY probably fail, because the auto-convert only
happens using 'ascii' as the encoding, and if it was not possible to
decode the filename inside listdir, it's quite probable that it also
will not work using 'ascii' as the charset.
gabor
--
http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Martin v. Löwis wrote:
> gabor schrieb:
>
>> or am i using os.listdir the "wrong way"? how do other people deal with
>> this?
>
> You didn't say why the behavior causes a problem for you - you only
> explained what the behavior is.
>
> Most people use os.listdir in a way like this:
>
> for name in os.listdir(path):
> full = os.path.join(path, name)
> attrib = os.stat(full)
> if some-condition:
> f = open(full)
> ...
>
> All this code will typically work just fine with the current behavior,
> so people typically don't see any problem.
>
i am sorry, but it will not work. actually this is exactly what i did,
and it did not work. it dies in the os.path.join call, where file_name
is converted into unicode. and python uses 'ascii' as the charset in
such cases. but, because listdir already failed to decode the file_name
with the filesystem-encoding, it usually also fails when tried with 'ascii'.
example:
>>> dir_name = u'something'
>>> unicode_file_name = u'\u732b.txt' # the japanese cat-symbol
>>> bytestring_file_name = unicode_file_name.encode('utf-8')
>>>
>>>
>>> import os.path
>>>
>>> os.path.join(dir_name,unicode_file_name)
u'something/\u732b.txt'
>>>
>>>
>>> os.path.join(dir_name,bytestring_file_name)
Traceback (most recent call last):
File "", line 1, in ?
File "/usr/lib/python2.4/posixpath.py", line 65, in join
path += '/' + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1:
ordinal not in range(128)
>>>
gabor
--
http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Jean-Paul Calderone wrote: > On Fri, 17 Nov 2006 00:31:06 +0100, "\"Martin v. Löwis\"" > <[EMAIL PROTECTED]> wrote: >> gabor schrieb: >>>> All this code will typically work just fine with the current behavior, >>>> so people typically don't see any problem. >>>> >>> >>> i am sorry, but it will not work. actually this is exactly what i did, >>> and it did not work. it dies in the os.path.join call, where file_name >>> is converted into unicode. and python uses 'ascii' as the charset in >>> such cases. but, because listdir already failed to decode the file_name >>> with the filesystem-encoding, it usually also fails when tried with >>> 'ascii'. >> >> Ah, right. So yes, it will typically fail immediately - just as you >> wanted it to do, anyway; the advantage with this failure is that you >> can also find out what specific file name is causing the problem >> (whereas when listdir failed completely, you could not easily find >> out the cause of the failure). >> >> How would you propose listdir should behave? > > Umm, just a wild guess, but how about raising an exception which includes > the name of the file which could not be decoded? > i also recommend this approach. also, raising an exception goes well with the principle of the least surprise imho. gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Laurent Pointal wrote: Laurent Pointal wrote: > gabor a écrit : >> hi, >> >> from the documentation (http://docs.python.org/lib/os-file-dir.html) for >> os.listdir: >> >> "On Windows NT/2k/XP and Unix, if path is a Unicode object, the result >> will be a list of Unicode objects." > > Maybe, for each filename, you can test if it is an unicode string, and > if not, convert it to unicode using the encoding indicated by > sys.getfilesystemencoding(). > > Have a try. > > A+ > > Laurent. > gabor a écrit : >> hi, >> >> from the documentation (http://docs.python.org/lib/os-file-dir.html) for >> os.listdir: >> >> "On Windows NT/2k/XP and Unix, if path is a Unicode object, the result >> will be a list of Unicode objects." > > Maybe, for each filename, you can test if it is an unicode string, and > if not, convert it to unicode using the encoding indicated by > sys.getfilesystemencoding(). > i don't think it would work. because os.listdir already tried, and failed (that's why we got a byte-string and not an unicode-string) gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Marc 'BlackJack' Rintsch wrote: > In <[EMAIL PROTECTED]>, Jean-Paul > Calderone wrote: > >>> How would you propose listdir should behave? >> Umm, just a wild guess, but how about raising an exception which includes >> the name of the file which could not be decoded? > > Suppose you have a directory with just some files having a name that can't > be decoded with the file system encoding. So `listdir()` fails at this > point and raises an exception. How would you get the names then? Even the > ones that *can* be decoded? This doesn't look very nice: > > path = u'some path' > try: > files = os.listdir(path) > except UnicodeError, e: > files = os.listdir(path.encode(sys.getfilesystemencoding())) > # Decode and filter the list "manually" here. i agree that it does not look very nice. but does this look nicer? :) path = u'some path' files = os.listdir(path) def check_and_fix_wrong_filename(file): if isinstance(file,unicode): return file else: #somehow convert it to unicode, and return it files = [check_and_fix_wrong_filename(f) for f in files] in other words, your opinion is that the proposed solution is not optimal, or that the current behavior is fine? gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Fredrik Lundh wrote:
> gabor wrote:
>
>> get an Unicode-exception, as everywhere else. you see, exceptions are
>> ok, i can deal with them.
>
>> p.s: one additional note. if you code expects os.listdir to return
>> unicode, that usually means that all your code uses unicode strings.
>> which in turn means, that those filenames will somehow later interact
>> with unicode strings. which means that that byte-string-filename will
>> probably get auto-converted to unicode at a later point, and that
>> auto-conversion will VERY probably fail
>
> it will raise an exception, most likely. didn't you just say that
> exceptions were ok?
yes, but it's raised at the wrong place imho :)
(just to clarify: simply pointing out this behavior in the documentation
is also one of the possible solutions)
for me the current behavior seems as if file-reading would work like this:
a = open('foo.txt')
data = a.read()
a.close()
print data
>>> TheFileFromWhichYouHaveReadDidNotExistException
gabor
--
http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Martin v. Löwis wrote: > gabor schrieb: >> i also recommend this approach. >> >> also, raising an exception goes well with the principle of the least >> surprise imho. > > Are you saying you wouldn't have been surprised if that had been > the behavior? yes, i would not have been surprised. because it's kind-of expected when dealing with input, that malformed input raises an unicode-exception. and i would also expect, that if os.listdir completed without raising an exception, then the returned data is correct. > How would you deal with that exception in your code? depends on the application. in the one where it happened i would just display an error message, and tell the admins to check the filesystem-encoding. (in other ones, where it's not critical to get the correct name, i would probably just convert the text to unicode using the "replace" behavior) what about using flags similar to how unicode() works? strict, ignore, replace and maybe keep-as-bytestring. like: os.listdir(dirname,'strict') i know it's not the most elegant, but it would solve most of the use-cases imho (at least my use-cases). gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: Python v PHP for web, and restarting Apache?
walterbyrd wrote: > I think I have read somewhere that using Python to develop > web-applications requires some restarting of the Apache server, whereas > PHP does not. > first thing... there are many many ways how to run a python-apache web application.. - mod_python - cgi - fastcgi - sci - proxy also the same way, for php: - mod_php - fastcgi - cgi - (maybe something more, i'm not much experienced with php) so first you should tell us which python-solution would you like to compare to which php-solution.. gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: What do I look for in a shared Python host?
Gregor Horvath wrote: > walterbyrd schrieb: >> What other "gotchas" would I look for? >> > > Maybe this is helpfull for you: > > http://docs.turbogears.org/1.0/Hosting > and this: http://code.djangoproject.com/wiki/DjangoFriendlyWebHosts gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Martin v. Löwis wrote: > gabor schrieb: >> depends on the application. in the one where it happened i would just >> display an error message, and tell the admins to check the >> filesystem-encoding. >> >> (in other ones, where it's not critical to get the correct name, i would >> probably just convert the text to unicode using the "replace" behavior) >> >> what about using flags similar to how unicode() works? strict, ignore, >> replace and maybe keep-as-bytestring. >> >> like: >> os.listdir(dirname,'strict') >> >> i know it's not the most elegant, but it would solve most of the >> use-cases imho (at least my use-cases). > > Of course, it's possible to implement this on top of the existing > listdir operation. > > def failing_listdir(dirname, mode): > result = os.listdir(dirname) > if mode != 'strict': return result > for r in result: > if isinstance(r, str): > raise UnicodeDecodeError > return result > yes, sure... but then.. it's possible to implement it also on top of an raise-when-error version :) so, what do you think, how should this issue be solved? currently i see 2 ways: 1. simply fix the documentation, and state that if the file-name cannot be decoded into unicode, then it's returned as byte-string. but that also means, that the typical usage of: [os.path.join(path,n) for n in os.listdir(path)] will not work. 2. add support for some unicode-decoding flags, like i wrote before 3. some solution. ? gaobr -- http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Fredrik Lundh wrote:
> gabor wrote:
>
>> yes, sure... but then.. it's possible to implement it also on top of
>> an raise-when-error version :)
>
> not necessarily if raise-when-error means raise-error-in-os-listdir.
>
could you please clarify?
currently i see 2 approaches how to do it on the raise-when-error version:
1.
dirname = u'something'
try:
files = os.listdir(dirname)
except UnicodeError:
byte_files = os.listdir(dirname.encode('encoding))
#do something with it
2.
dirname = u'something'
byte_files = os.listdir(dirname.encode('encoding'))
for byte_file in byte_files:
try:
file = byte_file.decode(sys.getfsenc())
except UnicodeError:
#do something else
#do something
the byte-string version of os.listdir remains. so all the other versions
can be implemented on the top of it. imho the question is:
which should be the 'default' behavior, offered by the python standard
library.
gabor
--
http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Martin v. Löwis wrote: > gabor schrieb: >> 1. simply fix the documentation, and state that if the file-name cannot >> be decoded into unicode, then it's returned as byte-string. > > For 2.5, this should be done. Contributions are welcome. > > [...then] >> [os.path.join(path,n) for n in os.listdir(path)] >> >> will not work. >> >> 2. add support for some unicode-decoding flags, like i wrote before > > I may have missed something, but did you present a solution that would > make the case above work? if we use the same decoding flags as binary-string.decode(), then we could do: [os.path.join(path,n) for n in os.listdir(path,'ignore')] or [os.path.join(path,n) for n in os.listdir(path,'replace')] it's not an elegant solution, but it would solve i think most of the problems. > >> 3. some solution. > > One approach I had been considering is to always make the decoding > succeed, by using the private-use-area of Unicode to represent bytes > that don't decode correctly. > hmm..an interesting idea.. and what happens with such texts, when they are encoded into let's say utf-8? are the in-private-use-area characters ignored? gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: os.lisdir, gets unicode, returns unicode... USUALLY?!?!?
Martin v. Löwis wrote:
> gabor schrieb:
>>> I may have missed something, but did you present a solution that would
>>> make the case above work?
>> if we use the same decoding flags as binary-string.decode(),
>> then we could do:
>>
>> [os.path.join(path,n) for n in os.listdir(path,'ignore')]
>
> That wouldn't work. The characters in the file name that didn't
> decode would be dropped, so the resulting file names would be
> invalid. Trying to do os.stat() on such a file name would raise
> an exception that the file doesn't exist.
>
>> [os.path.join(path,n) for n in os.listdir(path,'replace')]
>
> Likewise. The characters would get replaced with REPLACEMENT
> CHARACTER; passing that to os.stat would give an encoding
> error.
>
>> it's not an elegant solution, but it would solve i think most of the
>> problems.
>
> No, it wouldn't. This idea is as bad or worse than just dropping
> these file names from the directory listing.
i think that depends on the point of view.
if you need to do something later with the content of files, then you're
right.
but if all you need is to display them for example...
>
>>> One approach I had been considering is to always make the decoding
>>> succeed, by using the private-use-area of Unicode to represent bytes
>>> that don't decode correctly.
>>>
>> hmm..an interesting idea..
>>
>> and what happens with such texts, when they are encoded into let's say
>> utf-8? are the in-private-use-area characters ignored?
>
> UTF-8 supports encoding of all Unicode characters, including the PUA
> blocks.
>
> py> u"\ue020".encode("utf-8")
> '\xee\x80\xa0'
so basically you'd like to be able to "round-trip"?
so that:
listdir returns an array of filenames, the un-representable bytes will
be represented in the PUA.
all the other file-handling functions (stat, open, etc..) recognize such
strings, and handle them correctly.
?
gabor
--
http://mail.python.org/mailman/listinfo/python-list
write to the same file from multiple processes at the same time?
hi, what i want to achieve: i have a cgi file, that writes an entry to a text-file.. like a log entry (when was it invoked, when did his worke end). it's one line of text. the problem is: what happens if 2 users invoke the cgi at the same time? and it will happen, because i am trying now to stress test it, so i will start 5-10 requests in parallel and so on. so, how does one synchronizes several processes in python? first idea was that the cgi will create a new temp file every time, and at the end of the stress-test, i'll collect the content of all those files. but that seems as a stupid way to do it :( another idea was to use a simple database (sqlite?) which probably has this problem solved already... any better ideas? thanks, gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: write to the same file from multiple processes at the same time?
Jp Calderone wrote: > To briefly re-summarize, when you > want to acquire a lock, attempt to create a directory with a well-known > name. When you are done with it, delete the directory. This works > across all platforms and filesystems likely to be encountered by a > Python program. thanks... but the problem now is that the cgi will have to wait for that directory to be gone, when he is invoked.. and i do not want to code that :) i'm too lazy.. so basically i want the code to TRY to write to the file, and WAIT if it is opened for write right now... something like a mutex-synchronized block of the code... gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: write to the same file from multiple processes at the same time?
jean-marc wrote: > Sorry, why is the temp file solution 'stupid'?, (not > aesthetic-pythonistic???) - it looks OK: simple and direct, and > certainly less 'heavy' than any db stuff (even embedded) > > And collating in a 'official log file' can be done periodically by > another process, on a time-scale that is 'useful' if not > instantaneous... > > Just trying to understand here... > actually this is what i implemented after asking the question, and works fine :) i just thought that maybe there is a solution where i don't have to deal with 4000 files in the temp folder :) gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: write to the same file from multiple processes at the same time?
gabor wrote: > Jp Calderone wrote: > >> To briefly re-summarize, when you want to acquire a lock, attempt to >> create a directory with a well-known name. When you are done with it, >> delete the directory. This works across all platforms and filesystems >> likely to be encountered by a Python program. > > > thanks... > > but the problem now is that the cgi will have to wait for that directory > to be gone, when he is invoked.. and i do not want to code that :) > i'm too lazy.. > > so basically i want the code to TRY to write to the file, and WAIT if it > is opened for write right now... > > something like a mutex-synchronized block of the code... > ok, i ended up with the following code: def syncLog(filename,text): f = os.open(filename,os.O_WRONLY | os.O_APPEND) fcntl.flock(f,fcntl.LOCK_EX) os.write(f,text) #FIXME: what about releasing the lock? os.close(f) it seems to do what i need ( the flock() call waits until he can get access).. i just don't know if i have to unlock() the file before i close it.. gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: write to the same file from multiple processes at the same time?
Mike Meyer wrote: > gabor <[EMAIL PROTECTED]> writes: > > >>ok, i ended up with the following code: >> >>def syncLog(filename,text): >> f = os.open(filename,os.O_WRONLY | os.O_APPEND) >> fcntl.flock(f,fcntl.LOCK_EX) >> os.write(f,text) >> #FIXME: what about releasing the lock? >> os.close(f) >> >>it seems to do what i need ( the flock() call waits until he can get >>access).. i just don't know if i have to unlock() the file before i >>close it.. > > > The lock should free when you close the file descriptor. Personally, > I'm a great believer in doing things explicitly rather than > implicitly, > and would add the extra fcntl.flock(f, fcntl.LOCK_UN) call > before closing the file. done :) gabor -- http://mail.python.org/mailman/listinfo/python-list
multi-CPU, GIL, threading on linux
hi, as i understand, on linux, python uses the operating systems threads (so python is not simulating threads by himself). that means that on a multi-CPU computer, the different threads may get executed on different CPUs. i am working with zope, and i was referenced to this page: http://www.zope.org/Members/glpb/solaris/report_ps it's rather old (2002), but it claims the following: > I do *not* recommend running Zope on multiprocessor machines without an > ability to restrict Zope to execution on a single CPU. > > The reason for this is that the Python Global Interpreter Lock is shared > inside a Zope process. However, threads in Python are backed by > underlying OS threads. Thus, Zope will create multiple threads, and > each thread is likely to be assigned to a different CPU by the OS > scheduler. However, all CPUs but one which are dispatching any given > Zope process will have to then wait and attempt to acquire the GIL; this > process introduces significant latency into Python and thus into Zope. now, i know about tools that allow me to bind a python process to a specific cpu, but i wonder.. is the performance soo bad when i am running a python process, and the threads are running on different cpus? i understand that because of the GIL i cannot make my application faster. but slower? thanks, gabor -- http://mail.python.org/mailman/listinfo/python-list
datetime: the date of the day one month ago...how?
hi, i'm trying to get the date of the day one month ago. for example: today = 12.apr.2006 one-month-ago = 12.mar.2006 so: one-month-ago(12.apr.2006) = 12.mar.2006 of course sometimes it gets more complicated, like: one-month-ago(31.mar.2006) or one-month-ago(1.jan.2006) the datetime.timedelta objects only work with hours or days or weeks, not month (i understand why)... but is there a way to calculate this in python? i really don't want to calculate it by myself :-)) thanks, gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime: the date of the day one month ago...how?
Max M wrote: > gabor wrote: >> hi, >> >> i'm trying to get the date of the day one month ago. >> >> for example: >> >> today = 12.apr.2006 >> one-month-ago = 12.mar.2006 >> >> so: >> >> one-month-ago(12.apr.2006) = 12.mar.2006 >> >> of course sometimes it gets more complicated, like: >> >> one-month-ago(31.mar.2006) >> >> or >> >> one-month-ago(1.jan.2006) >> >> the datetime.timedelta objects only work with hours or days or weeks, >> not month (i understand why)... >> >> but is there a way to calculate this in python? >> >> i really don't want to calculate it by myself :-)) > > > It is application specific. So how *do* you want > one-month-ago(31.mar.2006) or one-month-ago(28.feb.2006) to work? No one > can know but you. > > well, give me a solution for ANY behaviour :) or, let's specify it then: i want the day that you get by intutively saying "one month ago". means usually picking the same day in the previous month. if that day does not exist, i want the nearest day that exist and was BEFORE the nonexistent day. one-month-ago(31.mar.2006) = 28.feb.2006 one-month-ago(28.feb.2006) = 28.jan.2006 so, now that we have a spec, is there a way to achieve this in python without writing the algorithm by myself? thanks, gabor -- http://mail.python.org/mailman/listinfo/python-list
Repository of non-standard modules.
Hi, I am to start a new free-time project in the next couple of weeks. I am ready to use open accessible Python modules not wanting to reinvent the weel :-) Is there any repository where I can find Python modules not being part of the standard distribution? I have some hits by Google but that seems to be far from complete. Thanks in advance, Gabor Urban -- Urbán Gábor Linux is like a wigwam: no Gates, no Windows and an Apache inside. -- http://mail.python.org/mailman/listinfo/python-list
Testing list sequence question
Hi guys, I have a strange problem that I do not understand. I am testing function which returns a dictionary. The code should ensure that the keys of the dictionary are generated in a given order. I am testing the function with the standard unittest module and use the assertListEqual statement to verify the sequence. Sometimes this test fails, sometimes passes without any change neither in the code, nor in the testcase. I am using "list(myDict.keys())" to create the list of the keys of the dictionary. I am running Python 3.3 on MS Windows. Any idea why is this? Thx, Gabor -- Urbán Gábor Linux is like a wigwam: no Gates, no Windows and an Apache inside. -- https://mail.python.org/mailman/listinfo/python-list
Testing list sequence question -- thanks for the info
Hi guys, Thank you very much for the accurate answer. Upgrading our Python to 3.7 seems to be out of question at the moment. I will check the requirement specification if the order of the keys is important at all. It could be a wish only. -- Urbán Gábor Linux is like a wigwam: no Gates, no Windows and an Apache inside. -- https://mail.python.org/mailman/listinfo/python-list
Module import question
Hi guys, I have a quite simple question but I could not find the correct answer. I have twoo modules A and B. A imports B. If I import A in a script, Will be B imported automatically? I guess not, but fő not know exactly. Thanks for your answer ín advance, Gábor -- https://mail.python.org/mailman/listinfo/python-list
Re: Module import question
Hi guys, Thanks for the answers. IT is clear Noé. Gábor -- https://mail.python.org/mailman/listinfo/python-list
A problem with opening a file
Hi, I am facing an issue I was not able to solve yet. I have a class saving messages to a file. The relevant code is: import OS import sys class MxClass: def __init__(self, fName, fMode,): self.fileName = fName self.fileMode = fMode def writeMethod(self, message): data = open(self.fileName, self.fileMode) Tests reveal: the class is instantiated correctly, other methods work perfect. The writeMethod raises a NameError opening the file "name 'open' is not defined " I am stuck here. -- Urbán Gábor Linux is like a wigwam: no Gates, no Windows and an Apache inside. -- https://mail.python.org/mailman/listinfo/python-list
A problem with opening a file -- again
Hi guys,
I tried to solve the problem once again. I have inserted some print
statements the check the variables.
The actual code (naplo.py) is copy-pasted here:
class Naplo:
def __init__(self, pNeve, pMeret, pMode = 'a'):
self.logNev = pNeve
self.meret = pMeret
self.startMode = pMode
self.mode = 'a'
self.sor = 0
self.puffer = []
self.start = True
def __del__(self):
print(' .. sor = %d'%self.sor)
print(' .. startMode = %s'%self.startMode)
print(' .. mode = %s'%self.mode)
print(' .. logName = %s'%self.logNev)
print(self.puffer)
if self.sor != 0:
if self.start:
trc = open(self.logNev,self.startMode)
else:
trc = open(self.logNev,self.mode)
for idx in xrange(self.meret):
trc.write(self.puffer[idx])
trc.close()
def Kiir(self, txt):
msg = '%s\n'%txt
self.puffer.append(msg)
self.sor += 1
print(' .. sor = %d'%self.sor)
print(' .. startMode = %s'%self.startMode)
print(' .. mode = %s'%self.mode)
print(' .. logName = %s'%self.logNev)
print(self.puffer)
print('.. ' + self.logNev)
if self.sor == self.meret:
if self.start:
trc = open(self.logNev,self.startMode)
else:
trc = open(self.logNev,self.mode)
for idx in xrange(self.meret):
trc.write(self.puffer[idx])
trc.close()
self.start = False
self.puffer = []
self.sor = 0
lf = Naplo('nap1.log', 6)
lf.Kiir('Ez az elso.')
I am using a Windows version:
python
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit
(AMD64)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> ^Z
python naplo.py
.. sor = 1
.. startMode = a
.. mode = a
.. logName = nap1.log
['Ez az elso.\n']
.. nap1.log
.. sor = 1
.. startMode = a
.. mode = a
.. logName = nap1.log
['Ez az elso.\n']
Exception ignored in: >
Traceback (most recent call last):
File "naplo.py", line 20, in __del__
NameError: name 'open' is not defined
--
Urbán Gábor
Linux is like a wigwam: no Gates, no Windows and an Apache inside.
--
https://mail.python.org/mailman/listinfo/python-list
Python 2.3 and ODBC
Hi guys, I am using Python 2.3 on an XP box at my company. (I know it is quite outdated, but we could not make the management to upgrade.) I have started a pilot project the last week to show the possibility of processing incoming XML files and extracting data into Oracle tables. Now I am almost ready, but need to use an ODBC module with Python. What do you suggest? BTW if my demo will be good, we hope to have an aproval to change to Python 3.3 Thanks in advance -- Urbán Gábor Linux is like a wigwam: no Gates, no Windows and an Apache inside. -- https://mail.python.org/mailman/listinfo/python-list
Teaching Python
Hi, my 11 years old son and his classmate told me, that they would like to learn Python. They did some programming in Logo and turtle graphics, bat not too much. Doesn anybody has an idea how to start? -- Urbán Gábor Linux is like a wigwam: no Gates, no Windows and an Apache inside. -- https://mail.python.org/mailman/listinfo/python-list
Set initial size in TKinter
Hi,
I am quite newbie with Tkinter and I could not find the way to set the
size of the application. (I could find the method to make it
resizeable, though :-)) ) Any ideas, suggestions or links to
references are wellcome.
Here is my code:
from Tkinter import *
class Application(Frame):
def say_hi(self):
self.db += 1
print 'hi there, -->> UG everyone! db = %d'%self.db
## TODO: meretezhetoseg
def createWidgets(self):
top = self.winfo_toplevel()
top.rowconfigure(0,weight = 1)
top.columnconfigure(0,weight = 1)
self.rowconfigure(0,weight = 1)
self.columnconfigure(0,weight = 1)
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "left"})
self.hi_there = Button(self)
self.hi_there["text"] = "Hello",
self.hi_there["command"] = self.say_hi
self.hi_there.pack({"side": "left"})
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
self.db = 0
app = Application()
app.master.title('UG test')
app.mainloop()
Thx in advance...
Gabor
--
Linux is like a wigwam: no Gates, no Windows and an Apache inside.
--
http://mail.python.org/mailman/listinfo/python-list
www.pythonchallange.com
www.pythonchallange.com -- http://mail.python.org/mailman/listinfo/python-list
Re: www.pythonchallange.com
Gabor Farkas wrote: > www.pythonchallange.com sorry, wanted to send it to someone else.. (too tired...) ;( gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs
Hi guys... This topic is not relevant in this mailing list. Though some info from an other mailing list. Emacs (and xemacs) runs perfectly well on non-gui environments as well. So keyboard commands are the only efficient way to work with. It is true, Emacs may be a bit antiquated, but it honed to an edge GUI tools are very far from. It is like a Formule-1 race car. You do not need automatic gears to drive it faster, do you? Learning Emacs is not easy but you can start with amazingly little knowledge. Skills come with usage. I know, I started it 10 years ago, well in the GUI era. Yes, vim. Very fine and powerfull tool, as good as Emacs. It is a quiestion of taste. I use both these times -- http://mail.python.org/mailman/listinfo/python-list
Emacs topic
Hi guys, I kindly ask you to stop this topic. Though I see the importance to have a good editor for programming, this is outside of the focus of a Python mailing list. The open source world offers a lot of very good tools to edit source files, even for cross-platform development. Emacs is one of them, and IMHO could be set as an efficiency/proficiency standard. But if it does not fit to your fingers or working style, do not use it. I am open to personal debate outside of this list, Gabor -- http://mail.python.org/mailman/listinfo/python-list
Emacs topic should be stopped....
Hi guys, I was going through most of this topic, but I find this not relevant on THIS mailing list... A short summary: there are some people who are not disturbed by proven facts. They are mostly attackers of emacs/Xemacs or vim... Or even linux and open source. Quite funny, since this is a mailing list of an open source programming language. :- Arguments and logic are not working, it's been a 'religious' flame topic. I am open to discuss this issue further in private.. Gabor -- http://mail.python.org/mailman/listinfo/python-list
Dynamic method
Hi guys. I have an issue I think Python could handle. But I do not have the knowledge to do it. Suppose I have a class 'myClass' and instance 'var'. There is function 'myFunc(..)'. I have to add (or bind) somehow the function to the class, or the instance. Any help, info or point of reference is wellcome Thx in advance, G -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs: terminology buffer and
Hullo, I was just wondering if this thread was whithering out.. I gues not for a good time. A short summary in the hope for the last posting in this topic. Some provocative posting caused or Twister brother to send a large amount of doubtful info. It seems, he had some very bad experience with an undefined version of so called 'emacs'. Or he was not able to win against his prejudice. On the other hand most of the users of the true, standard and canonical Emacs (and Xemacs as well) were able to point out his factual errors and misconceptions. (BTW Xemacs is not for X11... just eXtended.. :-)) ) But, for God's sake this is Python list. Would like to stick to it? Back to Python... which version is to be used in production environment? Sincerely yours, gabaux -- http://mail.python.org/mailman/listinfo/python-list
RE: unittest dependencies
Hullo! I have several questions about this problem. Do you have more test scripts using the unittest framework? My blind idea would be the following: run test b first, and go forward when no errors are found. To do this you could change the TestRunner component. The official documentation is good enough. Good luck, Gabor Urban NMC - ART -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of urielka Sent: 2007. május 2. 23:10 To: [email protected] Subject: unittest dependencies i am using unittest to test a project,and one thing i really want is a way to say that test a depends on test b,so it need to run before it and be successful in order to run this test. i just wanted to know if anyone have done it before(i searched for it but didn`t find something useful),i think it can be done easily using a decorator that will run the test which is depend on and mark it as successful,the only problem will be detecting circular test dependencies,but that can be fixed by keeping all the functions that the decorator have seen. what do you guys think? did someone did it before? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Newbie Suggestions
Stephen wrote: " For a newbie any material referenced should be current and include what is available in Python 2.5." I disagree. A newbie should learn Python and and Python programming . Not the latest should be the best choice.... Gabor Urban NMC - ART -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questions
Jay wrote: " 1. What are your views about Python vs Perl? Do you see one as better than the other?" They are different languages. Perl is very powerfull if you use it knowing potential problems. Python is definitely much easier to learn and use. "2. Is there a good book to start with while learning Python? I'm currently reading 'Python Essential Reference' by David M. Beazley. So far it looks like a pretty good book, but would like more tutorials to work with (I've also been reading through the tutorials at 'python.org' which has some excellent stuff!)." I would suggest you to read Dive into Python. Very deep descriptions. 3. I vote for Emacs :-)) Gabor Urban NMC - ART -- http://mail.python.org/mailman/listinfo/python-list
Simple question about logging module.
Hullo,
I have started to use Python's logging, and got a problem. I have created
some loggers and wrote some lines in the log. The problem is, that most of
the lines appear doubled in the log, and some lines do not appear at all.
Any ideas or comments are wellcome,
Gabor
Here is the code:
import sys
import logging
l = logging.getLogger('XmlTester')
handler = logging.StreamHandler(sys.stderr)
l.addHandler(handler)
formatter = logging.Formatter("%(name)s %(asctime)s %(filename)s %(lineno)d
%(levelname)s %(message)s")
handler.setFormatter(formatter)
la = logging.getLogger('XmlTester.XmlParser')
handler = logging.StreamHandler(sys.stderr)
la.addHandler(handler)
handler.setFormatter(formatter)
lb = logging.getLogger('XmlTester.TestExecutor')
handler = logging.StreamHandler(sys.stderr)
lb.addHandler(handler)
handler.setFormatter(formatter)
l.setLevel(logging.DEBUG)
la.setLevel(logging.DEBUG)
lb.setLevel(logging.DEBUG)
l.debug("Start")
la.debug("Start la")
lb.debug("This debug")
lb.info("This started.")
l.info("Info written")
l.warning("This is a warning")
l.error("Error occured")
test = "Info.pck"
la.info("Hi there!")
la.critical("No file named '%s'"%test)
l.critical("End of all")
Here is the output:
XmlTester.XmlParser 2007-07-31 10:34:12,303 plogtest.py 21 DEBUG Start la
XmlTester.XmlParser 2007-07-31 10:34:12,303 plogtest.py 21 DEBUG Start la
XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 22 DEBUG This
debug
XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 22 DEBUG This
debug
XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 23 INFO This
started.
XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 23 INFO This
started.
XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 28 INFO Hi there!
XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 28 INFO Hi there!
XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 29 CRITICAL No file
named 'Info.pck'
XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 29 CRITICAL No file
named 'Info.pck'
XmlTester 2007-07-31 10:34:12,319 plogtest.py 30 CRITICAL End of all
--
http://mail.python.org/mailman/listinfo/python-list
Re: Simple question about logging module.
Thx guys You gave me good ideas. At the moment I do not have time for it, but I would like to write a summary. Have fun -- http://mail.python.org/mailman/listinfo/python-list
Re: XML Parsing
HI, I could suggest you to use the minidom xml parser from xml module. Your XML schema does not seem to complocated. You will find detailed descriptions, and working code in the book: Dive ino Python. Google for it :-)) Gabor Urban NMC - ART -- http://mail.python.org/mailman/listinfo/python-list
IDLE problem
Hi, I have a strange problem with the latest 2.4.4 on MS XP. If I rrun a test script in DOS window, it is ok. From the Python shell I got error: Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. IDLE 1.1.4 >>> RESTART >>> -- Ran 8 tests in 0.016s OK Traceback (most recent call last): File "D:\Gabaux\Python\TodoList\datetest.py", line 76, in -toplevel- unittest.main() File "D:\Python24\lib\unittest.py", line 759, in __init__ self.runTests() File "D:\Python24\lib\unittest.py", line 797, in runTests sys.exit(not result.wasSuccessful()) SystemExit: False >>> The script I was executing was a simple unittest.TestCase descendant. Any ideas? Gabor Urban NMC - ART -- http://mail.python.org/mailman/listinfo/python-list
Volume id
Hi, I have a problem, which may be trivial, but I could not find an answer. I have to write a Python script, which does a directory tree walking on given mounted disk. But I do need to extract the volume id, somehow. And that's the problem. An additional issue, the script will be used on unix type systems, and on MS XP or Vista, too Any ideas are wellcome. Gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: Volume id
OK, you are right... Problem was not precise enough. I need to process CDs to create a list. Does it ring a bell for you? Thanks 2007/11/15, Laszlo Nagy <[EMAIL PROTECTED]>: > > Gabor Urban wrote: > > Hi, > > > > I have a problem, which may be trivial, but I could not find an answer. > > > > I have to write a Python script, which does a directory tree walking > > on given mounted disk. But I do need to extract the volume id, > > somehow. And that's the problem. An additional issue, the script will > > be used on unix type systems, and on MS XP or Vista, too > > > > Any ideas are wellcome. > I believe (although not 100% sure) that "volume id" always belongs to a > FAT partition (maybe an NTFS partition?). When you format a partition, > it will give you a - hopefully unique - volume identifier. I don't think > that unix partitions (like reiserfs, ext2, ext3, ufs2 etc.) has that > identifier. I may be wrong, others will probably correct me. > > Do you want to know the identifier (serial number?) of the disk device > instead? E.g. not the partition but the hard disk? > > Can you list the platforms/operating systems where you want to use your > program? It might help to look at the documentation/source code or the > various hardware diagnostic utilities. > > Best, > >Laszlo > > -- http://mail.python.org/mailman/listinfo/python-list
Porting to new Python version
Hi, I have a tough issue: we are using a Python application written quite a time ago for version 2.4. The code is mature, and there are no bugs. My bosses came up with the idea to port it to the latest release... I am not really convinced that it's a good step. I wellcome any information pro and contra. I would like to get the background as precisely as possible. Thanks in advance and good day to You! Gabor -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, can i ask for a little help? (Andrew Chung)
I gues, it was rather simple... Begin with simple tasks, figure out how to do them. If you are proceding well, then increase difficulty/complexity. Gabor -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking old post on developers who like IDEs vs developers who like simple languages
Hi guys, I think this issue is long-long displute over tools and IDE-s. No need to combine it with the question of the complexity of the programming language used. I know guys, who did every development project using a simple GVIM and command line tools, and vere extremly productive. Even in Java, C++, and any other languages. For myself I can say, I am a seasoned Emacs user, and would not switch to any fancy IDE. BUT that is personal view. IMHO this question does not bellong here, though I was very pleased to read arguments instead of flames :-)) Gabor -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
I use Emacs, as for the other editing activities. I like it for it is very powerfull. -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Re: What text editor is everyone using for Python
Hi guys, I would like to reflect this issue for the last time, though I found this thread to be quite inspiring. In one the last postings about this topic Steven D'Aprano has written: "As a general rule, menus are discoverable, while keyboard commands aren't. There's nothing inherent to text editing functions which makes then inherently undiscoverable, and KDE apps like kate and kwrite do a reasonable job of making them so." I agree with this assumption if, and only if we are speaking about outsider users. This is a Python mailing list, which supposed to be a forum of people using the Python programming language. So Python source is a plain text, so Python interpreter should be a command-driven application. With no other UI than the plain old Command Line Intreface. MOre than that, all we are supposed to be techmen, who does acknowledge and appreciate the conceot of wrtitten User Manual or Reference. All we have learned Python from tutorials and not from the menues. As a summary, any open source editor should be perfect, which is extensible, optionally language-sensitive, portable, basically independent of any OS features. THat cuts the list drammatically. Gabor -- http://mail.python.org/mailman/listinfo/python-list
Two questions ( Oracle and modules )
Hi guys, I have two questions. 1. I have choice to introduce Python to my new employee. We are to write and application that uses databases stored partially in Oracle 10 and partially in Oracle 11. We have to execute standard SQL commands and stored procedures as well. Which is best conection / module to use. A couple of years ago we had DCOracle2 for the same task, but is written for Oracle8, so I gues it might not be a good idea to use. What is your oppinion? 2. We have tp write a module that will be imported a couple of places. Though we must be sure, this module's initialization is performed only once. How can we implement this? I do not know what to google for..... Gabor -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Re: best vi / emacs python features
Hey guys, this is supposed to be a Python mailing list... Both editors are great and are with great potentials. I do use both of them daily, though for different purposes. It is meaningless to start this old issue of preferences anew. -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Question on PEP 337
Hy guys, this PEP is very well written, and I have found the discussion inspiring. Every time I use the logging module, I have the configuration hardcoded in the application. That is why I never used the configuration file based approach. Now I will give it a try. I think we should discuss the following scenario (it was not clear in the PEP for me) : an application has the logging configuration in a config file and it is currently running. The user edits this file, so the configuiration in the running process should be changed. -- How will be the logging mechanism reconfigured? -- How can the logging module guarantee that there will be no data loss during the reconfiguration process? Regards, Gabor -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on PEP 337 (Vinay Sajip)
Hy guys, Sorry, Vinay Sajip was right. I wrote my questions about PEP 391. I would like to know your ideas about my questions posted in my last mail. Gabor -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
More Python versions on an XP machine
Hi guys, this a very MS specific question. I do use a rather old Python version, because we have a couple of applications written for that. Porting them to a newer Python is not allowed by the bosses. Now we will start a new project with latest stable Python. Can I have them both on my computer, and how should I do that. Thanks, PS: This is my computer at the office :-) -- Linux: Choice of a GNU Generation -- http://mail.python.org/mailman/listinfo/python-list
Class attributes / methods lost?
Hi guys,
I am building a nested data structure with the following compontens:
<>
class Item:
def __init__(self, pId, pChange, pComment):
self.ID = pId
self.Delta = pChange
self.Comment = pComment
def PrintItem(self):
str = '%s,%s,%s'%(self.ID,self.Delta,self.comment)
return str
class Package:
def __init__(self, pSerial, pDate, pOwner, pSchema):
self.serial = pSerial
self.date = pDate
self.owner = pOwner
self.schema = pSchema
self.items = []
def insertItem(self, pItem):
self.items.append(pItem)
def printPackage(self):
lines = []
str = '%s,%s,%s,%s'%(self.serial,self.date,self.owner,self.schema)
number = self.items.length
for idx in xrange(number):
line = ''
istr = self.items[idx].PrintItem()
line = str + ',' + istr
lines.append(line)
return lines
<>
The above structure is processed with next code:
<>
size = len(packages)
package = None
for index in xrange(size):
logger.info('PrettyPrinting package id=%d',index)
oplines = []
oplines = packages[index].printPackage()
for i in xrange(oplines.length):
data.append(oplines[i])
<>
I've got the next error message:
' Traceback (most recent call last):
File "XmlHistory_orig.py", line 203, in ?
oplines = packages[index].printPackage()
TypeError: unbound method printPackage() must be called with Package
instance as first argument (got nothing instead) '
I did give a try to access the fields directly
<>
packages = []
data = []
size = len(packages)
for index in xrange(size):
str =
'%s,%s,%s,%s'%(packages[index].serial,packages[index].date,packages[index].owner,packages[index].schema)
itemnum = len(packages[index].items)
oplines = []
for itemIndx in xrange(itemnum):
element =
'%s,%s,%s'%(packages[index].items[itemIdx].ID,packages[index].items[itemIdx].Delta,packages[index].items[itemIdx].comment)
oplines.append(str + ','+elemt)
<>
Error:
Traceback (most recent call last):
File "XmlHistory.py", line 204, in ?
str =
'%s,%s,%s,%s'%(packages[index].serial,packages[index].date,packages[index].owner,packages[index].schema)
AttributeError: class Package has no attribute 'serial'
The strange in this issue for me, that I do not see why are the class
methods and fields lost.
Any idea is wellcome.
Gabor
--
Linux: Choice of a GNU Generation
--
http://mail.python.org/mailman/listinfo/python-list
Class attributes / methods..... full Python script
Hi guys,
thanks for the ideas. Here you are the code. Not transcoded from Java
for I do not know Java enough..
I am scanning an XML file, and have a large ammount of logging.
Any ideas are wellcome as before
Thnx
Code:>
#-
## Generate CSV from OEP History XML
#-
import sys
import os
from xml.dom.minidom import parse, parseString
import xml.dom
import logging
versionStr = '0.01'
class Item:
def __init__(self, pId, pChange, pComment):
self.ID = pId
self.Delta = pChange
self.Comment = pComment
def PrintItem(self):
str = '%s,%s,%s'%(self.ID,self.Delta,self.comment)
return str
class Package:
def __init__(self, pSerial, pDate, pOwner, pSchema):
self.serial = pSerial
self.date = pDate
self.owner = pOwner
self.schema = pSchema
self.items = []
def insertItem(self, pItem):
self.items.append(pItem)
def printPackage(self):
lines = []
str = '%s,%s,%s,%s'%(self.serial,self.date,self.owner,self.schema)
number = self.items.length
for idx in xrange(number):
line = ''
istr = self.items[idx].PrintItem()
line = str + ',' + istr
lines.append(line)
return lines
def getItem(tracer, pkgItem, itemName):
retval = -1
name = ""
found = 0
str = ""
tracer.info('Function getItem entry, name = %s',itemName)
nItem = pkgItem.getElementsByTagName(itemName).item(0)
for node in pkgItem.childNodes:
if node.nodeType != xml.dom.Node.TEXT_NODE:
tracer.debug('Scanning node name = %s',node.nodeName)
if node.nodeName == itemName:
tracer.debug('Pkg %s found',itemName)
else:
tracer.warning('Pkg %s is not found',itemName)
continue
for entity in node.childNodes:
if entity.nodeType == xml.dom.Node.TEXT_NODE:
retval = entity.nodeValue
tracer.debug("Node value found %s",retval)
found = 1
break
if found == 1:
break
tracer.debug('Function getItem returns %s',retval)
return retval
logger = logging.getLogger('XmlHistory')
handler = logging.FileHandler("Xmlhistory.trc",'a')
## handler = logging.StreamHandler(sys.stderr)
logger.addHandler(handler)
formatter = logging.Formatter("%(name)s %(asctime)s %(filename)s
%(lineno)d %(levelname)s %(message)s")
handler.setFormatter(formatter)
logger.setLevel(2)
fileName = "history.xml"
output = 'history.csv'
logger.info('Xml history generator version %s',versionStr)
logger.info('Starting history generation on file:%s',fileName)
packages = []
data = []
## Start XML processing
dataSource = parse(fileName)
print dataSource.documentElement.tagName
listCsomag = dataSource.getElementsByTagName("csomag")
size = listCsomag.length
logger.debug('Number of packages = %d',size)
for idx in xrange(size):
attrib = ""
package = None
serial = 0
date = ""
owner = ""
schema = ""
flag = False
logger.info('Parsing package id=%d',idx)
attrib = getItem(logger, listCsomag.item(idx),'sorszam')
if attrib <> "NUM" and attrib <> -1:
serial = int(attrib)
flag = True
logger.debug('Package serial set to %d',serial)
else:
logger.debug("Template package found.")
break
attrib = ""
attrib = getItem(logger,listCsomag.item(idx),"datum")
if attrib <> -1:
date = attrib
flag = flag and True
logger.debug('Package date set to %s',date)
attrib = ""
attrib = getItem(logger,listCsomag.item(idx),"ki")
if attrib <> -1:
owner = attrib
flag = flag and True
logger.debug('Package owner set to %s',owner)
attrib = ""
attrib = getItem(logger,listCsomag.item(idx),"sema")
if attrib <> -1:
schema = attrib
flag = flag and True
logger.debug('Package schema set to %s',schema)
if flag <> True:
logger.error('Package id=%d is inconsistent',idx)
break
else:
logger.info('Package id=%d is ok',idx)
package = Package(serial,date,owner,schema)
listItem = listCsomag.item(idx).getElementsByTagName("item")
itemSize = listItem.length
logger.debug('Number of items = %d',itemSize)
for num in xrange(itemSize):
flag = False
value = -1
listId = 0
change = ""
comment = ""
item = None
logger.info('Parsing item id = %d',num)
value = getItem(logger,listItem.item(num),"item_id")
if value <> -1:
listId = int(value)
flag = True
logger.debug('List id set to %d',listId)
value = ""
value = getItem(logger,listItem.item(num),"valtozas")
if value <> -1:
change = value
Logging question
Hi guys,
I have embarassing problem using the logging module. I would like to
encapsulate the creation and setting up of the logger in a class, but
it does not seem working.
Here are my relevant parts of the code:
--
import sys
import logging
class LogClass:
def __init__(self, fileName, loggerName = 'classLog'):
self.Logger = logging.getLogger(loggerName)
self.traceName = fileName
handler = logging.FileHandler(self.traceName,'a')
formatter = logging.Formatter("%(name)s %(asctime)s
%(filename)s %(lineno)d %(levelname)s %(message)s")
handler.setFormatter(formatter)
self.Logger.addHandler(handler)
self.Handler = handler
def closeLog(self):
self.Handler.flush()
self.Handler.close()
def fetchLogger(self):
return self.Logger
if __name__ == "__main__":
name = 'testlog.trc'
classLog = LogClass(name)
logger = classLog.fetchLogger()
logger.info("Created")
logger.debug("Test")
logger.info("Created .. ")
logger.debug("Test data")
classLog.closeLog()
--
The trace file is created properly but contains no lines at all. If I
put the code directly in __main__, it works fine.
What did I miss? Any ideas are wellcome.
Gabor
--
Linux: Choice of a GNU Generation
--
http://mail.python.org/mailman/listinfo/python-list
Missing logging output in Python
Hi,
I would like to enable loggin in my script using the logging module that comes
with Python 2.7.3.
I have the following few lines setting up logging in my script, but for
whatever reason I don't seem to get any output to stdout or to a file
provided to the basicConfig method.
Any ideas?
# cinfiguring logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s
%(levelname)8s %(message)s',
datefmt='%Y-%m-%d\t%H:%M:%s',
filename=config["currentLoop"], filemode='a')
# define a Handler that writes INFO messages to sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set format that is cleaber for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
--
http://mail.python.org/mailman/listinfo/python-list
A question about import
Hi guys, I need something about modules to be clarified. Suppose I have written a module eg: ModuleA which imports an other module, let us say the datetime. If I import ModuleA in a script, will be datetime imported automatically? Thanks in advance, -- Urbán Gábor Linux is like a wigwam: no Gates, no Windows and an Apache inside. -- https://mail.python.org/mailman/listinfo/python-list
